xref: /btstack/src/l2cap.c (revision 98e87e7776ef9a7fe55135aea8cddc761fe3a7a5)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
24  * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "l2cap.c"
39 
40 /*
41  *  l2cap.c
42  *  Logical Link Control and Adaption Protocol (L2CAP)
43  */
44 
45 #include "l2cap.h"
46 #include "hci.h"
47 #include "hci_dump.h"
48 #include "bluetooth_sdp.h"
49 #include "bluetooth_psm.h"
50 #include "btstack_bool.h"
51 #include "btstack_debug.h"
52 #include "btstack_event.h"
53 #include "btstack_memory.h"
54 
55 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
56 // TODO avoid dependency on higher layer: used to trigger pairing for outgoing connections
57 #include "ble/sm.h"
58 #endif
59 
60 #include <stdarg.h>
61 #include <string.h>
62 
63 /*
64  * @brief L2CAP Supervisory function in S-Frames
65  */
66 typedef enum {
67     L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY = 0,
68     L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT,
69     L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY,
70     L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT
71 } l2cap_supervisory_function_t;
72 
73 /**
74  * @brief L2CAP Information Types used in Information Request & Response
75  */
76 typedef enum {
77   L2CAP_INFO_TYPE_CONNECTIONLESS_MTU = 1,
78   L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED,
79   L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED,
80 } l2cap_info_type_t;
81 
82 /**
83  * @brief L2CAP Configuration Option Types used in Configurateion Request & Response
84  */
85 typedef enum {
86   L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT = 1,
87   L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT,
88   L2CAP_CONFIG_OPTION_TYPE_QUALITY_OF_SERVICE,
89   L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL,
90   L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE,
91   L2CAP_CONFIG_OPTION_TYPE_EXTENDED_FLOW_SPECIFICATION,
92   L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE,
93 } l2cap_config_option_type_t;
94 
95 
96 #define L2CAP_SIG_ID_INVALID 0
97 
98 // size of HCI ACL + L2CAP Header for regular data packets (8)
99 #define COMPLETE_L2CAP_HEADER (HCI_ACL_HEADER_SIZE + L2CAP_HEADER_SIZE)
100 
101 // L2CAP Configuration Result Codes
102 #define L2CAP_CONF_RESULT_SUCCESS                  0x0000
103 #define L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS  0x0001
104 #define L2CAP_CONF_RESULT_REJECT                   0x0002
105 #define L2CAP_CONF_RESULT_UNKNOWN_OPTIONS          0x0003
106 #define L2CAP_CONF_RESULT_PENDING                  0x0004
107 #define L2CAP_CONF_RESULT_FLOW_SPEC_REJECTED       0x0005
108 
109 // L2CAP Reject Result Codes
110 #define L2CAP_REJ_CMD_UNKNOWN                      0x0000
111 
112 // Response Timeout eXpired
113 #define L2CAP_RTX_TIMEOUT_MS   10000
114 
115 // Extended Response Timeout eXpired
116 #define L2CAP_ERTX_TIMEOUT_MS 120000
117 
118 // nr of buffered acl packets in outgoing queue to get max performance
119 #define NR_BUFFERED_ACL_PACKETS 3
120 
121 // used to cache l2cap rejects, echo, and informational requests
122 #define NR_PENDING_SIGNALING_RESPONSES 3
123 
124 // nr of credits provided to remote if credits fall below watermark
125 #define L2CAP_CREDIT_BASED_FLOW_CONTROL_MODE_AUTOMATIC_CREDITS_WATERMARK 5
126 #define L2CAP_CREDIT_BASED_FLOW_CONTROL_MODE_AUTOMATIC_CREDITS_INCREMENT 5
127 
128 // offsets for L2CAP SIGNALING COMMANDS
129 #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
130 #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
131 #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
132 #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
133 
134 #if defined(ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE) && !defined(ENABLE_CLASSIC)
135 #error "ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE depends on ENABLE_CLASSIC."
136 #error "Please remove ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE or add ENABLE_CLASSIC in btstack_config.h"
137 #endif
138 
139 
140 #ifdef ENABLE_LE_DATA_CHANNELS
141 #warning "ENABLE_LE_DATA_CHANNELS has been deprecated."
142 #warning "Please use ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE instead in btstack_config.h"
143 #define ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
144 #endif
145 
146 #if defined(ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE) || defined(ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE)
147 #define L2CAP_USES_CREDIT_BASED_CHANNELS
148 #endif
149 
150 #if defined(L2CAP_USES_CREDIT_BASED_CHANNELS) || defined(ENABLE_CLASSIC)
151 #define L2CAP_USES_CHANNELS
152 #endif
153 
154 // prototypes
155 static void l2cap_run(void);
156 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
157 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size );
158 static void l2cap_notify_channel_can_send(void);
159 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel);
160 static uint8_t  l2cap_next_sig_id(void);
161 static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid);
162 #ifdef ENABLE_CLASSIC
163 static void l2cap_handle_security_level_incoming_sufficient(l2cap_channel_t * channel);
164 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm);
165 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel);
166 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel);
167 static void l2cap_handle_information_request_complete(hci_connection_t * connection);
168 static inline l2cap_service_t * l2cap_get_service(uint16_t psm);
169 static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
170 static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
171 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel);
172 static int  l2cap_channel_ready_for_open(l2cap_channel_t *channel);
173 static uint8_t l2cap_classic_send(l2cap_channel_t * channel, const uint8_t *data, uint16_t len);
174 #endif
175 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
176 static void l2cap_cbm_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
177 static void l2cap_cbm_emit_incoming_connection(l2cap_channel_t *channel);
178 static void l2cap_credit_based_notify_channel_can_send(l2cap_channel_t *channel);
179 static void l2cap_cbm_finialize_channel_close(l2cap_channel_t *channel);
180 static inline l2cap_service_t * l2cap_cbm_get_service(uint16_t le_psm);
181 #endif
182 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
183 static uint8_t l2cap_credit_based_send_data(l2cap_channel_t * channel, const uint8_t * data, uint16_t size);
184 static void l2cap_credit_based_send_pdu(l2cap_channel_t *channel);
185 static void l2cap_credit_based_send_credits(l2cap_channel_t *channel);
186 static bool l2cap_credit_based_handle_credit_indication(hci_con_handle_t handle, const uint8_t * command, uint16_t len);
187 static void l2cap_credit_based_handle_pdu(l2cap_channel_t * l2cap_channel, const uint8_t * packet, uint16_t size);
188 #endif
189 #ifdef L2CAP_USES_CHANNELS
190 static uint16_t l2cap_next_local_cid(void);
191 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid);
192 static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code);
193 static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size);
194 static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, l2cap_channel_type_t channel_type, bd_addr_t address, bd_addr_type_t address_type,
195         uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level);
196 static void l2cap_finalize_channel_close(l2cap_channel_t *channel);
197 static void l2cap_free_channel_entry(l2cap_channel_t * channel);
198 #endif
199 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
200 static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel);
201 static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts);
202 static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts);
203 #endif
204 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
205 static void l2cap_ecbm_handle_security_level_incoming(l2cap_channel_t *channel);
206 static int l2cap_ecbm_signaling_handler_dispatch(hci_con_handle_t handle, uint16_t signaling_cid, uint8_t * command, uint8_t sig_id);
207 static void l2cap_run_trigger_callback(void * context);
208 #endif
209 
210 // l2cap_fixed_channel_t entries
211 #ifdef ENABLE_BLE
212 static l2cap_fixed_channel_t l2cap_fixed_channel_le_att;
213 static l2cap_fixed_channel_t l2cap_fixed_channel_le_sm;
214 #endif
215 #ifdef ENABLE_CLASSIC
216 static l2cap_fixed_channel_t l2cap_fixed_channel_classic_connectionless;
217 static l2cap_fixed_channel_t l2cap_fixed_channel_classic_sm;
218 #endif
219 
220 #ifdef ENABLE_CLASSIC
221 static btstack_linked_list_t l2cap_services;
222 static uint8_t l2cap_require_security_level2_for_outgoing_sdp;
223 static bd_addr_t l2cap_outgoing_classic_addr;
224 #endif
225 
226 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
227 static btstack_linked_list_t l2cap_le_services;
228 #endif
229 
230 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
231 static btstack_linked_list_t l2cap_enhanced_services;
232 static uint16_t l2cap_enhanced_mps_min;
233 static uint16_t l2cap_enhanced_mps_max;
234 static btstack_context_callback_registration_t l2cap_trigger_run_registration;
235 #endif
236 
237 // single list of channels for connection-oriented channels (basic, ertm, cbm, ecbf) Classic Connectionless, ATT, and SM
238 static btstack_linked_list_t l2cap_channels;
239 #ifdef L2CAP_USES_CHANNELS
240 // next channel id for new connections
241 static uint16_t  l2cap_local_source_cid;
242 #endif
243 // next signaling sequence number
244 static uint8_t   l2cap_sig_seq_nr;
245 
246 // used to cache l2cap rejects, echo, and informational requests
247 static l2cap_signaling_response_t l2cap_signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
248 static int l2cap_signaling_responses_pending;
249 static btstack_packet_callback_registration_t l2cap_hci_event_callback_registration;
250 
251 static bool l2cap_call_notify_channel_in_run;
252 
253 #ifdef ENABLE_BLE
254 // only used for connection parameter update events
255 static uint16_t l2cap_le_custom_max_mtu;
256 #endif
257 
258 /* callbacks for events */
259 static btstack_linked_list_t l2cap_event_handlers;
260 
261 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
262 
263 // enable for testing
264 // #define L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL 16
265 
266 /*
267  * CRC lookup table for generator polynom D^16 + D^15 + D^2 + 1
268  */
269 static const uint16_t crc16_table[256] = {
270     0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
271     0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841,
272     0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41,
273     0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040,
274     0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441,
275     0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840,
276     0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40,
277     0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041,
278     0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
279     0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840,
280     0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
281     0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041,
282     0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440,
283     0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841,
284     0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41,
285     0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040,
286 };
287 
288 static uint16_t crc16_calc(uint8_t * data, uint16_t len){
289     uint16_t crc = 0;   // initial value = 0
290     while (len--){
291         crc = (crc >> 8) ^ crc16_table[ (crc ^ ((uint16_t) *data++)) & 0x00FF ];
292     }
293     return crc;
294 }
295 
296 static inline uint16_t l2cap_encanced_control_field_for_information_frame(uint8_t tx_seq, int final, uint8_t req_seq, l2cap_segmentation_and_reassembly_t sar){
297     return (((uint16_t) sar) << 14) | (req_seq << 8) | (final << 7) | (tx_seq << 1) | 0;
298 }
299 
300 static inline uint16_t l2cap_encanced_control_field_for_supevisor_frame(l2cap_supervisory_function_t supervisory_function, int poll, int final, uint8_t req_seq){
301     return (req_seq << 8) | (final << 7) | (poll << 4) | (((int) supervisory_function) << 2) | 1;
302 }
303 
304 static int l2cap_next_ertm_seq_nr(int seq_nr){
305     return (seq_nr + 1) & 0x3f;
306 }
307 
308 static bool l2cap_ertm_can_store_packet_now(l2cap_channel_t * channel){
309     // get num free tx buffers
310     int num_free_tx_buffers = channel->num_tx_buffers - channel->num_stored_tx_frames;
311     // calculate num tx buffers for remote MTU
312     int num_tx_buffers_for_max_remote_mtu;
313     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
314     if (channel->remote_mtu <= effective_mps){
315         // MTU fits into single packet
316         num_tx_buffers_for_max_remote_mtu = 1;
317     } else {
318         // include SDU Length
319         num_tx_buffers_for_max_remote_mtu = (channel->remote_mtu + 2 + (effective_mps - 1)) / effective_mps;
320     }
321     log_debug("num_free_tx_buffers %u, num_tx_buffers_for_max_remote_mtu %u", num_free_tx_buffers, num_tx_buffers_for_max_remote_mtu);
322     return num_tx_buffers_for_max_remote_mtu <= num_free_tx_buffers;
323 }
324 
325 static void l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel_t * l2cap_channel){
326     log_info("Retransmit unacknowleged frames");
327     l2cap_channel->unacked_frames = 0;;
328     l2cap_channel->tx_send_index  = l2cap_channel->tx_read_index;
329 }
330 
331 static void l2cap_ertm_next_tx_write_index(l2cap_channel_t * channel){
332     channel->tx_write_index++;
333     if (channel->tx_write_index < channel->num_tx_buffers) return;
334     channel->tx_write_index = 0;
335 }
336 
337 static void l2cap_ertm_start_monitor_timer(l2cap_channel_t * channel){
338     log_info("Start Monitor timer");
339     btstack_run_loop_remove_timer(&channel->monitor_timer);
340     btstack_run_loop_set_timer_handler(&channel->monitor_timer, &l2cap_ertm_monitor_timeout_callback);
341     btstack_run_loop_set_timer_context(&channel->monitor_timer, channel);
342     btstack_run_loop_set_timer(&channel->monitor_timer, channel->local_monitor_timeout_ms);
343     btstack_run_loop_add_timer(&channel->monitor_timer);
344 }
345 
346 static void l2cap_ertm_stop_monitor_timer(l2cap_channel_t * channel){
347     log_info("Stop Monitor timer");
348     btstack_run_loop_remove_timer(&channel->monitor_timer);
349 }
350 
351 static void l2cap_ertm_start_retransmission_timer(l2cap_channel_t * channel){
352     log_info("Start Retransmission timer");
353     btstack_run_loop_remove_timer(&channel->retransmission_timer);
354     btstack_run_loop_set_timer_handler(&channel->retransmission_timer, &l2cap_ertm_retransmission_timeout_callback);
355     btstack_run_loop_set_timer_context(&channel->retransmission_timer, channel);
356     btstack_run_loop_set_timer(&channel->retransmission_timer, channel->local_retransmission_timeout_ms);
357     btstack_run_loop_add_timer(&channel->retransmission_timer);
358 }
359 
360 static void l2cap_ertm_stop_retransmission_timer(l2cap_channel_t * l2cap_channel){
361     log_info("Stop Retransmission timer");
362     btstack_run_loop_remove_timer(&l2cap_channel->retransmission_timer);
363 }
364 
365 static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts){
366     log_info("Monitor timeout");
367     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
368 
369     // TODO: we assume that it's the oldest packet
370     l2cap_ertm_tx_packet_state_t * tx_state;
371     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
372 
373     // check retry count
374     if (tx_state->retry_count < l2cap_channel->remote_max_transmit){
375         // increment retry count
376         tx_state->retry_count++;
377 
378         // start retransmit
379         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
380 
381         // start monitor timer
382         l2cap_ertm_start_monitor_timer(l2cap_channel);
383 
384         // send RR/P=1
385         l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
386     } else {
387         log_info("Monitor timer expired & retry count >= max transmit -> disconnect");
388         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
389     }
390     l2cap_run();
391 }
392 
393 static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts){
394     log_info("Retransmission timeout");
395     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
396 
397     // TODO: we assume that it's the oldest packet
398     l2cap_ertm_tx_packet_state_t * tx_state;
399     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
400 
401     // set retry count = 1
402     tx_state->retry_count = 1;
403 
404     // start retransmit
405     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
406 
407     // start monitor timer
408     l2cap_ertm_start_monitor_timer(l2cap_channel);
409 
410     // send RR/P=1
411     l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
412     l2cap_run();
413 }
414 
415 static int l2cap_ertm_send_information_frame(l2cap_channel_t * channel, int index, int final){
416     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
417     hci_reserve_packet_buffer();
418     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
419     uint16_t control = l2cap_encanced_control_field_for_information_frame(tx_state->tx_seq, final, channel->req_seq, tx_state->sar);
420     log_info("I-Frame: control 0x%04x", control);
421     little_endian_store_16(acl_buffer, 8, control);
422     (void)memcpy(&acl_buffer[8 + 2],
423                  &channel->tx_packets_data[index * channel->local_mps],
424                  tx_state->len);
425     // (re-)start retransmission timer on
426     l2cap_ertm_start_retransmission_timer(channel);
427     // send
428     return l2cap_send_prepared(channel->local_cid, 2 + tx_state->len);
429 }
430 
431 static void l2cap_ertm_store_fragment(l2cap_channel_t * channel, l2cap_segmentation_and_reassembly_t sar, uint16_t sdu_length, const uint8_t * data, uint16_t len){
432     // get next index for storing packets
433     int index = channel->tx_write_index;
434 
435     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
436     tx_state->tx_seq = channel->next_tx_seq;
437     tx_state->sar = sar;
438     tx_state->retry_count = 0;
439 
440     uint8_t * tx_packet = &channel->tx_packets_data[index * channel->local_mps];
441     log_debug("index %u, local mps %u, remote mps %u, packet tx %p, len %u", index, channel->local_mps, channel->remote_mps, tx_packet, len);
442     int pos = 0;
443     if (sar == L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU){
444         little_endian_store_16(tx_packet, 0, sdu_length);
445         pos += 2;
446     }
447     (void)memcpy(&tx_packet[pos], data, len);
448     tx_state->len = pos + len;
449 
450     // update
451     channel->num_stored_tx_frames++;
452     channel->next_tx_seq = l2cap_next_ertm_seq_nr(channel->next_tx_seq);
453     l2cap_ertm_next_tx_write_index(channel);
454 
455     log_info("l2cap_ertm_store_fragment: tx_read_index %u, tx_write_index %u, num stored %u", channel->tx_read_index, channel->tx_write_index, channel->num_stored_tx_frames);
456 
457 }
458 
459 static uint8_t l2cap_ertm_send(l2cap_channel_t * channel, const uint8_t * data, uint16_t len){
460     if (len > channel->remote_mtu){
461         log_error("l2cap_ertm_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
462         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
463     }
464 
465     if (!l2cap_ertm_can_store_packet_now(channel)){
466         log_error("l2cap_ertm_send cid 0x%02x, fragment store full", channel->local_cid);
467         return BTSTACK_ACL_BUFFERS_FULL;
468     }
469 
470     // check if it needs to get fragmented
471     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
472     if (len > effective_mps){
473         // fragmentation needed.
474         l2cap_segmentation_and_reassembly_t sar =  L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU;
475         uint16_t chunk_len = 0;
476         while (len){
477             switch (sar){
478                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
479                     chunk_len = effective_mps - 2;    // sdu_length
480                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
481                     sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU;
482                     break;
483                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
484                     chunk_len = effective_mps;
485                     if (chunk_len >= len){
486                         sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU;
487                         chunk_len = len;
488                     }
489                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
490                     break;
491                 default:
492                     btstack_unreachable();
493                     break;
494             }
495             len  -= chunk_len;
496             data += chunk_len;
497         }
498 
499     } else {
500         l2cap_ertm_store_fragment(channel, L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU, 0, data, len);
501     }
502 
503     // try to send
504     l2cap_notify_channel_can_send();
505     return ERROR_CODE_SUCCESS;
506 }
507 
508 static uint16_t l2cap_setup_options_ertm_request(l2cap_channel_t * channel, uint8_t * config_options){
509     int pos = 0;
510     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
511     config_options[pos++] = 9;      // length
512     config_options[pos++] = (uint8_t) channel->mode;
513     config_options[pos++] = channel->num_rx_buffers;    // == TxWindows size
514     config_options[pos++] = channel->local_max_transmit;
515     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
516     pos += 2;
517     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
518     pos += 2;
519     little_endian_store_16( config_options, pos, channel->local_mps);
520     pos += 2;
521     //
522     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT;
523     config_options[pos++] = 2;     // length
524     little_endian_store_16(config_options, pos, channel->local_mtu);
525     pos += 2;
526 
527     // Issue: iOS (e.g. 10.2) uses "No FCS" as default while Core 5.0 specifies "FCS" as default
528     // Workaround: try to actively negotiate FCS option
529     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
530     config_options[pos++] = 1;     // length
531     config_options[pos++] = channel->fcs_option;
532     return pos; // 11+4+3=18
533 }
534 
535 static uint16_t l2cap_setup_options_ertm_response(l2cap_channel_t * channel, uint8_t * config_options){
536     int pos = 0;
537     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
538     config_options[pos++] = 9;      // length
539     config_options[pos++] = (uint8_t) channel->mode;
540     // less or equal to remote tx window size
541     config_options[pos++] = btstack_min(channel->num_tx_buffers, channel->remote_tx_window_size);
542     // max transmit in response shall be ignored -> use sender values
543     config_options[pos++] = channel->remote_max_transmit;
544     // A value for the Retransmission time-out shall be sent in a positive Configuration Response
545     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
546     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
547     pos += 2;
548     // A value for the Monitor time-out shall be sent in a positive Configuration Response
549     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
550     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
551     pos += 2;
552     // less or equal to remote mps
553     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
554     little_endian_store_16( config_options, pos, effective_mps);
555     pos += 2;
556     //
557     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
558     config_options[pos++] = 2;     // length
559     little_endian_store_16(config_options, pos, channel->remote_mtu);
560     pos += 2;
561 #if 0
562     //
563     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
564     config_options[pos++] = 1;     // length
565     config_options[pos++] = channel->fcs_option;
566 #endif
567     return pos; // 11+4=15
568 }
569 
570 static int l2cap_ertm_send_supervisor_frame(l2cap_channel_t * channel, uint16_t control){
571     hci_reserve_packet_buffer();
572     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
573     log_info("S-Frame: control 0x%04x", control);
574     little_endian_store_16(acl_buffer, 8, control);
575     return l2cap_send_prepared(channel->local_cid, 2);
576 }
577 
578 static uint8_t l2cap_ertm_validate_local_config(l2cap_ertm_config_t * ertm_config){
579 
580     uint8_t result = ERROR_CODE_SUCCESS;
581     if (ertm_config->max_transmit < 1){
582         log_error("max_transmit must be >= 1");
583         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
584     }
585     if (ertm_config->retransmission_timeout_ms < 2000){
586         log_error("retransmission_timeout_ms must be >= 2000 ms");
587         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
588     }
589     if (ertm_config->monitor_timeout_ms < 12000){
590         log_error("monitor_timeout_ms must be >= 12000 ms");
591         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
592     }
593     if (ertm_config->local_mtu < 48){
594         log_error("local_mtu must be >= 48");
595         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
596     }
597     if (ertm_config->num_rx_buffers < 1){
598         log_error("num_rx_buffers must be >= 1");
599         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
600     }
601     if (ertm_config->num_tx_buffers < 1){
602         log_error("num_rx_buffers must be >= 1");
603         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
604     }
605     return result;
606 }
607 
608 static void l2cap_ertm_setup_buffers(l2cap_channel_t * channel, uint8_t * buffer, uint32_t size){
609     btstack_assert( (((uintptr_t) buffer) & 0x0f) == 0);
610 
611     // setup state buffers - use void cast to avoid -Wcast-align warning
612     uint32_t pos = 0;
613     channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) (void *) &buffer[pos];
614     pos += channel->num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
615     channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) (void *) &buffer[pos];
616     pos += channel->num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
617 
618     // setup reassembly buffer
619     channel->reassembly_buffer = &buffer[pos];
620     pos += channel->local_mtu;
621 
622     // setup rx buffers
623     channel->rx_packets_data = &buffer[pos];
624     pos += channel->num_rx_buffers * channel->local_mps;
625 
626     // setup tx buffers
627     channel->tx_packets_data = &buffer[pos];
628     pos += channel->num_rx_buffers * channel->remote_mps;
629 
630     btstack_assert(pos <= size);
631     UNUSED(pos);
632 }
633 
634 static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
635 
636     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
637     channel->ertm_mandatory = ertm_config->ertm_mandatory;
638     channel->local_max_transmit = ertm_config->max_transmit;
639     channel->local_retransmission_timeout_ms = ertm_config->retransmission_timeout_ms;
640     channel->local_monitor_timeout_ms = ertm_config->monitor_timeout_ms;
641     channel->local_mtu = ertm_config->local_mtu;
642     channel->num_rx_buffers = ertm_config->num_rx_buffers;
643     channel->num_tx_buffers = ertm_config->num_tx_buffers;
644     channel->fcs_option = ertm_config->fcs_option;
645 
646     // align buffer to 16-byte boundary to assert l2cap_ertm_rx_packet_state_t is aligned
647     int bytes_till_alignment = 16 - (((uintptr_t) buffer) & 0x0f);
648     buffer += bytes_till_alignment;
649     size   -= bytes_till_alignment;
650 
651     // calculate space for rx and tx buffers
652     uint32_t state_len = channel->num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t) + channel->num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
653     uint32_t buffer_space = size - state_len - channel->local_mtu;
654 
655     // divide rest of data equally for initial config
656     uint16_t mps = buffer_space / (ertm_config->num_rx_buffers + ertm_config->num_tx_buffers);
657     channel->local_mps  = mps;
658     channel->remote_mps = mps;
659     l2cap_ertm_setup_buffers(channel, buffer, size);
660 
661     log_info("Local MPS: %u", channel->local_mps);
662 }
663 
664 uint8_t l2cap_ertm_create_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
665     l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
666 
667     log_info("l2cap_ertm_create_channel addr %s, psm 0x%x, local mtu %u", bd_addr_to_str(address), psm, ertm_config->local_mtu);
668 
669     // validate local config
670     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
671     if (result) return result;
672 
673     // determine security level based on psm
674     const gap_security_level_t security_level = l2cap_security_level_0_allowed_for_PSM(psm) ? LEVEL_0 : gap_get_security_level();
675 
676     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, address, BD_ADDR_TYPE_ACL, psm, ertm_config->local_mtu, security_level);
677     if (!channel) {
678         return BTSTACK_MEMORY_ALLOC_FAILED;
679     }
680 
681     // configure ERTM
682     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
683 
684     // add to connections list
685     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
686 
687     // store local_cid
688     if (out_local_cid){
689        *out_local_cid = channel->local_cid;
690     }
691 
692     // check if hci connection is already usable
693     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
694     if (conn){
695         log_info("l2cap_create_channel, hci connection already exists");
696         l2cap_handle_connection_complete(conn->con_handle, channel);
697         // check if remote supported fearures are already received
698         if (hci_remote_features_available(conn->con_handle)) {
699             l2cap_handle_remote_supported_features_received(channel);
700         } else {
701             hci_remote_features_query(conn->con_handle);
702         };
703     }
704 
705     l2cap_run();
706 
707     return 0;
708 }
709 
710 static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel){
711     if (l2cap_ertm_can_store_packet_now(channel)){
712         channel->waiting_for_can_send_now = 0;
713         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
714     }
715 }
716 
717 uint8_t l2cap_ertm_accept_connection(uint16_t local_cid, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
718 
719     log_info("l2cap_ertm_accept_connection local_cid 0x%x", local_cid);
720     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
721     if (!channel) {
722         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
723         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
724     }
725 
726     // validate local config
727     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
728     if (result) return result;
729 
730     // configure L2CAP ERTM
731     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
732 
733     // we need to know if ERTM is supported before sending a config response
734     channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
735     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
736     btstack_assert(connection != NULL);
737     switch (connection->l2cap_state.information_state){
738         case L2CAP_INFORMATION_STATE_IDLE:
739             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
740             break;
741         case L2CAP_INFORMATION_STATE_DONE:
742             l2cap_handle_information_request_complete(connection);
743             break;
744         default:
745             break;
746     }
747 
748     l2cap_run();
749 
750     return ERROR_CODE_SUCCESS;
751 }
752 
753 uint8_t l2cap_ertm_decline_connection(uint16_t local_cid){
754     l2cap_decline_connection(local_cid);
755     return ERROR_CODE_SUCCESS;
756 }
757 
758 uint8_t l2cap_ertm_set_busy(uint16_t local_cid){
759     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
760     if (!channel) {
761         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
762         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
763     }
764     if (!channel->local_busy){
765         channel->local_busy = 1;
766         channel->send_supervisor_frame_receiver_not_ready = 1;
767         l2cap_run();
768     }
769     return ERROR_CODE_SUCCESS;
770 }
771 
772 uint8_t l2cap_ertm_set_ready(uint16_t local_cid){
773     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
774     if (!channel) {
775         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
776         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
777     }
778     if (channel->local_busy){
779         channel->local_busy = 0;
780         channel->send_supervisor_frame_receiver_ready_poll = 1;
781         l2cap_run();
782     }
783     return ERROR_CODE_SUCCESS;
784 }
785 
786 // Process-ReqSeq
787 static void l2cap_ertm_process_req_seq(l2cap_channel_t * l2cap_channel, uint8_t req_seq){
788     int num_buffers_acked = 0;
789     l2cap_ertm_tx_packet_state_t * tx_state;
790     log_info("l2cap_ertm_process_req_seq: tx_read_index %u, tx_write_index %u, req_seq %u", l2cap_channel->tx_read_index, l2cap_channel->tx_write_index, req_seq);
791     while (true){
792 
793         // no unack packets left
794         if (l2cap_channel->unacked_frames == 0) {
795             // stop retransmission timer
796             l2cap_ertm_stop_retransmission_timer(l2cap_channel);
797             break;
798         }
799 
800         tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
801         // calc delta
802         int delta = (req_seq - tx_state->tx_seq) & 0x03f;
803         if (delta == 0) break;  // all packets acknowledged
804         if (delta > l2cap_channel->remote_tx_window_size) break;
805 
806         num_buffers_acked++;
807         l2cap_channel->num_stored_tx_frames--;
808         l2cap_channel->unacked_frames--;
809         log_info("RR seq %u => packet with tx_seq %u done", req_seq, tx_state->tx_seq);
810 
811         l2cap_channel->tx_read_index++;
812         if (l2cap_channel->tx_read_index >= l2cap_channel->num_rx_buffers){
813             l2cap_channel->tx_read_index = 0;
814         }
815     }
816     if (num_buffers_acked){
817         log_info("num_buffers_acked %u", num_buffers_acked);
818     l2cap_ertm_notify_channel_can_send(l2cap_channel);
819 }
820 }
821 
822 static l2cap_ertm_tx_packet_state_t * l2cap_ertm_get_tx_state(l2cap_channel_t * l2cap_channel, uint8_t tx_seq){
823     int i;
824     for (i=0;i<l2cap_channel->num_tx_buffers;i++){
825         l2cap_ertm_tx_packet_state_t * tx_state = &l2cap_channel->tx_packets_state[i];
826         if (tx_state->tx_seq == tx_seq) return tx_state;
827     }
828     return NULL;
829 }
830 
831 // @param delta number of frames in the future, >= 1
832 // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
833 static void l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel_t * l2cap_channel, l2cap_segmentation_and_reassembly_t sar, int delta, const uint8_t * payload, uint16_t size){
834     log_info("Store SDU with delta %u", delta);
835     // get rx state for packet to store
836     int index = l2cap_channel->rx_store_index + delta - 1;
837     if (index > l2cap_channel->num_rx_buffers){
838         index -= l2cap_channel->num_rx_buffers;
839     }
840     log_info("Index of packet to store %u", index);
841     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
842     // check if buffer is free
843     if (rx_state->valid){
844         log_error("Packet buffer already used");
845         return;
846     }
847     rx_state->valid = 1;
848     rx_state->sar = sar;
849     rx_state->len = size;
850     uint8_t * rx_buffer = &l2cap_channel->rx_packets_data[index];
851     (void)memcpy(rx_buffer, payload, size);
852 }
853 
854 // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
855 static void l2cap_ertm_handle_in_sequence_sdu(l2cap_channel_t * l2cap_channel, l2cap_segmentation_and_reassembly_t sar, const uint8_t * payload, uint16_t size){
856     uint16_t reassembly_sdu_length;
857     switch (sar){
858         case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
859             // assert total packet size <= our mtu
860             if (size > l2cap_channel->local_mtu) break;
861             // packet complete -> disapatch
862             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, (uint8_t*) payload, size);
863             break;
864         case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
865             // read SDU len
866             reassembly_sdu_length = little_endian_read_16(payload, 0);
867             payload += 2;
868             size    -= 2;
869             // assert reassembled size <= our mtu
870             if (reassembly_sdu_length > l2cap_channel->local_mtu) break;
871             // store start segment
872             l2cap_channel->reassembly_sdu_length = reassembly_sdu_length;
873             (void)memcpy(&l2cap_channel->reassembly_buffer[0], payload, size);
874             l2cap_channel->reassembly_pos = size;
875             break;
876         case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
877             // assert size of reassembled data <= our mtu
878             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
879             // store continuation segment
880             (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
881                          payload, size);
882             l2cap_channel->reassembly_pos += size;
883             break;
884         case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
885             // assert size of reassembled data <= our mtu
886             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
887             // store continuation segment
888             (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
889                          payload, size);
890             l2cap_channel->reassembly_pos += size;
891             // assert size of reassembled data matches announced sdu length
892             if (l2cap_channel->reassembly_pos != l2cap_channel->reassembly_sdu_length) break;
893             // packet complete -> disapatch
894             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->reassembly_buffer, l2cap_channel->reassembly_pos);
895             l2cap_channel->reassembly_pos = 0;
896             break;
897         default:
898             btstack_assert(false);
899             break;
900     }
901 }
902 
903 static void l2cap_ertm_channel_send_information_frame(l2cap_channel_t * channel){
904     channel->unacked_frames++;
905     int index = channel->tx_send_index;
906     channel->tx_send_index++;
907     if (channel->tx_send_index >= channel->num_tx_buffers){
908         channel->tx_send_index = 0;
909     }
910     l2cap_ertm_send_information_frame(channel, index, 0);   // final = 0
911 }
912 
913 #endif
914 
915 #ifdef L2CAP_USES_CHANNELS
916 static uint16_t l2cap_next_local_cid(void){
917     do {
918         if (l2cap_local_source_cid == 0xfffeu) {
919             l2cap_local_source_cid = 0x40;
920         } else {
921             l2cap_local_source_cid++;
922         }
923     } while (l2cap_get_channel_for_local_cid(l2cap_local_source_cid) != NULL);
924     return l2cap_local_source_cid;
925 }
926 #endif
927 
928 static uint8_t l2cap_next_sig_id(void){
929     if (l2cap_sig_seq_nr == 0xffu) {
930         l2cap_sig_seq_nr = 1;
931     } else {
932         l2cap_sig_seq_nr++;
933     }
934     return l2cap_sig_seq_nr;
935 }
936 
937 void l2cap_init(void){
938 #ifdef L2CAP_USES_CHANNELS
939     l2cap_local_source_cid  = 0x40;
940 #endif
941     l2cap_sig_seq_nr  = 0xff;
942 
943 #ifdef ENABLE_CLASSIC
944     // Setup Connectionless Channel
945     l2cap_fixed_channel_classic_connectionless.local_cid     = L2CAP_CID_CONNECTIONLESS_CHANNEL;
946     l2cap_fixed_channel_classic_connectionless.channel_type  = L2CAP_CHANNEL_TYPE_CONNECTIONLESS;
947     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_classic_connectionless);
948 #endif
949 
950 #ifdef ENABLE_BLE
951     // Setup fixed ATT Channel
952     l2cap_fixed_channel_le_att.local_cid    = L2CAP_CID_ATTRIBUTE_PROTOCOL;
953     l2cap_fixed_channel_le_att.channel_type = L2CAP_CHANNEL_TYPE_FIXED_LE;
954     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_le_att);
955 
956     // Setup fixed SM Channel
957     l2cap_fixed_channel_le_sm.local_cid     = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
958     l2cap_fixed_channel_le_sm.channel_type  = L2CAP_CHANNEL_TYPE_FIXED_LE;
959     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_le_sm);
960 #endif
961 #ifdef ENABLE_CLASSIC
962     // Setup fixed SM Channel
963     l2cap_fixed_channel_classic_sm.local_cid     = L2CAP_CID_BR_EDR_SECURITY_MANAGER;
964     l2cap_fixed_channel_classic_sm.channel_type  = L2CAP_CHANNEL_TYPE_FIXED_CLASSIC;
965     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_classic_sm);
966 #endif
967 
968 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
969     l2cap_enhanced_mps_min = 0x0001;
970     l2cap_enhanced_mps_max = 0xffff;
971     l2cap_trigger_run_registration.callback = &l2cap_run_trigger_callback;
972 #endif
973 
974     //
975     // register callback with HCI
976     //
977     l2cap_hci_event_callback_registration.callback = &l2cap_hci_event_handler;
978     hci_add_event_handler(&l2cap_hci_event_callback_registration);
979 
980     hci_register_acl_packet_handler(&l2cap_acl_handler);
981 
982 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
983 #ifdef ENABLE_CLASSIC
984     gap_connectable_control(0); // no services yet
985 #endif
986 #endif
987 }
988 
989 /**
990  * @brief De-Init L2CAP
991  */
992 void l2cap_deinit(void){
993     l2cap_channels = NULL;
994     l2cap_signaling_responses_pending = 0;
995 #ifdef ENABLE_CLASSIC
996     l2cap_require_security_level2_for_outgoing_sdp = 0;
997     (void)memset(&l2cap_fixed_channel_classic_connectionless, 0, sizeof(l2cap_fixed_channel_classic_connectionless));
998     l2cap_services = NULL;
999     (void)memset(l2cap_outgoing_classic_addr, 0, 6);
1000     (void)memset(&l2cap_fixed_channel_classic_sm, 0, sizeof(l2cap_fixed_channel_classic_sm));
1001 #endif
1002 #ifdef ENABLE_BLE
1003     l2cap_le_custom_max_mtu = 0;
1004     (void)memset(&l2cap_fixed_channel_le_att, 0, sizeof(l2cap_fixed_channel_le_att));
1005     (void)memset(&l2cap_fixed_channel_le_sm, 0, sizeof(l2cap_fixed_channel_le_sm));
1006 #endif
1007 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
1008     l2cap_le_services = NULL;
1009 #endif
1010 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1011     l2cap_enhanced_services = NULL;
1012 #endif
1013     l2cap_event_handlers = NULL;
1014 }
1015 
1016 void l2cap_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
1017     btstack_linked_list_add_tail(&l2cap_event_handlers, (btstack_linked_item_t*) callback_handler);
1018 }
1019 
1020 void l2cap_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
1021     btstack_linked_list_remove(&l2cap_event_handlers, (btstack_linked_item_t*) callback_handler);
1022 }
1023 
1024 static void l2cap_emit_event(uint8_t *event, uint16_t size) {
1025     hci_dump_packet( HCI_EVENT_PACKET, 1, event, size);
1026     // dispatch to all event handlers
1027     btstack_linked_list_iterator_t it;
1028     btstack_linked_list_iterator_init(&it, &l2cap_event_handlers);
1029     while (btstack_linked_list_iterator_has_next(&it)){
1030         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
1031         entry->callback(HCI_EVENT_PACKET, 0, event, size);
1032     }
1033 }
1034 
1035 void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
1036     UNUSED(con_handle);  // ok: there is no con handle
1037 
1038     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
1039     if (!channel) return;
1040     channel->waiting_for_can_send_now = 1;
1041     l2cap_notify_channel_can_send();
1042 }
1043 
1044 bool l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
1045     UNUSED(channel_id); // ok: only depends on Controller LE buffers
1046 
1047     return hci_can_send_acl_packet_now(con_handle);
1048 }
1049 
1050 uint8_t *l2cap_get_outgoing_buffer(void){
1051     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
1052 }
1053 
1054 // only for L2CAP Basic Channels
1055 bool l2cap_reserve_packet_buffer(void){
1056     return hci_reserve_packet_buffer();
1057 }
1058 
1059 // only for L2CAP Basic Channels
1060 void l2cap_release_packet_buffer(void){
1061     hci_release_packet_buffer();
1062 }
1063 
1064 static void l2cap_setup_header(uint8_t * acl_buffer, hci_con_handle_t con_handle, uint8_t packet_boundary, uint16_t remote_cid, uint16_t len){
1065     // 0 - Connection handle : PB=pb : BC=00
1066     little_endian_store_16(acl_buffer, 0u, con_handle | (packet_boundary << 12u) | (0u << 14u));
1067     // 2 - ACL length
1068     little_endian_store_16(acl_buffer, 2u,  len + 4u);
1069     // 4 - L2CAP packet length
1070     little_endian_store_16(acl_buffer, 4u,  len + 0u);
1071     // 6 - L2CAP channel DEST
1072     little_endian_store_16(acl_buffer, 6,  remote_cid);
1073 }
1074 
1075 // assumption - only on LE connections
1076 uint8_t l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
1077 
1078     if (!hci_is_packet_buffer_reserved()){
1079         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
1080         return BTSTACK_ACL_BUFFERS_FULL;
1081     }
1082 
1083     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
1084         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
1085         return BTSTACK_ACL_BUFFERS_FULL;
1086     }
1087 
1088     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
1089 
1090     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1091     l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
1092     // send
1093     return hci_send_acl_packet_buffer(len+8u);
1094 }
1095 
1096 // assumption - only on LE connections
1097 uint8_t l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
1098 
1099     if (!hci_can_send_acl_packet_now(con_handle)){
1100         log_info("l2cap_send cid 0x%02x, cannot send", cid);
1101         return BTSTACK_ACL_BUFFERS_FULL;
1102     }
1103 
1104     hci_reserve_packet_buffer();
1105     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1106 
1107     (void)memcpy(&acl_buffer[8], data, len);
1108 
1109     return l2cap_send_prepared_connectionless(con_handle, cid, len);
1110 }
1111 
1112 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
1113     log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
1114     uint8_t event[4];
1115     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
1116     event[1] = sizeof(event) - 2u;
1117     little_endian_store_16(event, 2, channel);
1118     hci_dump_packet( HCI_EVENT_PACKET, 1, event, sizeof(event));
1119     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
1120 }
1121 
1122 #ifdef L2CAP_USES_CHANNELS
1123 static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
1124     (* (channel->packet_handler))(type, channel->local_cid, data, size);
1125 }
1126 
1127 static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
1128     uint8_t event[4];
1129     event[0] = event_code;
1130     event[1] = sizeof(event) - 2u;
1131     little_endian_store_16(event, 2, channel->local_cid);
1132     hci_dump_packet( HCI_EVENT_PACKET, 1, event, sizeof(event));
1133     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1134 }
1135 #endif
1136 
1137 #ifdef ENABLE_CLASSIC
1138 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
1139     log_info("L2CAP_EVENT_CHANNEL_OPENED status 0x%x addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x local_mtu %u, remote_mtu %u, flush_timeout %u",
1140              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
1141              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
1142     uint8_t event[26];
1143     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
1144     event[1] = sizeof(event) - 2;
1145     event[2] = status;
1146     reverse_bd_addr(channel->address, &event[3]);
1147     little_endian_store_16(event,  9, channel->con_handle);
1148     little_endian_store_16(event, 11, channel->psm);
1149     little_endian_store_16(event, 13, channel->local_cid);
1150     little_endian_store_16(event, 15, channel->remote_cid);
1151     little_endian_store_16(event, 17, channel->local_mtu);
1152     little_endian_store_16(event, 19, channel->remote_mtu);
1153     little_endian_store_16(event, 21, channel->flush_timeout);
1154     event[23] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
1155 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1156     log_info("ERTM mode %u, fcs enabled %u", channel->mode, channel->fcs_option);
1157     event[24] = channel->mode;
1158     event[25] = channel->fcs_option;
1159 
1160 #else
1161     event[24] = L2CAP_CHANNEL_MODE_BASIC;
1162     event[25] = 0;
1163 #endif
1164     hci_dump_packet( HCI_EVENT_PACKET, 1, event, sizeof(event));
1165     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1166 }
1167 
1168 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
1169     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
1170              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
1171     uint8_t event[16];
1172     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
1173     event[1] = sizeof(event) - 2;
1174     reverse_bd_addr(channel->address, &event[2]);
1175     little_endian_store_16(event,  8, channel->con_handle);
1176     little_endian_store_16(event, 10, channel->psm);
1177     little_endian_store_16(event, 12, channel->local_cid);
1178     little_endian_store_16(event, 14, channel->remote_cid);
1179     hci_dump_packet( HCI_EVENT_PACKET, 1, event, sizeof(event));
1180     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1181 }
1182 
1183 static void l2cap_handle_channel_open_failed(l2cap_channel_t * channel, uint8_t status){
1184 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1185     // emit ertm buffer released, as it's not needed. if in basic mode, it was either not allocated or already released
1186     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1187         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1188     }
1189 #endif
1190     l2cap_emit_channel_opened(channel, status);
1191 }
1192 
1193 #endif
1194 
1195 #ifdef L2CAP_USES_CHANNELS
1196 
1197 static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
1198     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
1199     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
1200 }
1201 
1202 static void l2cap_handle_channel_closed(l2cap_channel_t * channel){
1203 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1204     // emit ertm buffer released, as it's not needed anymore. if in basic mode, it was either not allocated or already released
1205     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1206         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1207     }
1208 #endif
1209     l2cap_emit_channel_closed(channel);
1210 }
1211 #endif
1212 
1213 static l2cap_fixed_channel_t * l2cap_channel_item_by_cid(uint16_t cid){
1214     btstack_linked_list_iterator_t it;
1215     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1216     while (btstack_linked_list_iterator_has_next(&it)){
1217         l2cap_fixed_channel_t * channel = (l2cap_fixed_channel_t*) btstack_linked_list_iterator_next(&it);
1218         if (channel->local_cid == cid) {
1219             return channel;
1220         }
1221     }
1222     return NULL;
1223 }
1224 
1225 // used for fixed channels in LE (ATT/SM) and Classic (Connectionless Channel). CID < 0x04
1226 static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid){
1227     if (local_cid >= 0x40u) return NULL;
1228     return (l2cap_fixed_channel_t*) l2cap_channel_item_by_cid(local_cid);
1229 }
1230 
1231 #ifdef L2CAP_USES_CHANNELS
1232 
1233 static int l2cap_is_dynamic_channel_type(l2cap_channel_type_t channel_type) {
1234     switch (channel_type) {
1235         case L2CAP_CHANNEL_TYPE_CLASSIC:
1236         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
1237         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
1238             return 1;
1239         default:
1240             return 0;
1241     }
1242 }
1243 
1244 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
1245     if (local_cid < 0x40u) return NULL;
1246     return (l2cap_channel_t*) l2cap_channel_item_by_cid(local_cid);
1247 }
1248 
1249 static l2cap_channel_t * l2cap_get_channel_for_local_cid_and_handle(uint16_t local_cid, hci_con_handle_t con_handle){
1250     if (local_cid < 0x40u) return NULL;
1251     l2cap_channel_t * l2cap_channel = (l2cap_channel_t*) l2cap_channel_item_by_cid(local_cid);
1252     if (l2cap_channel == NULL)  return NULL;
1253     if (l2cap_channel->con_handle != con_handle) return NULL;
1254     return l2cap_channel;
1255 }
1256 #endif
1257 
1258 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
1259 static l2cap_channel_t * l2cap_get_channel_for_remote_handle_and_cid(hci_con_handle_t con_handle, uint16_t remote_cid){
1260     btstack_linked_list_iterator_t it;
1261     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1262     while (btstack_linked_list_iterator_has_next(&it)){
1263         l2cap_fixed_channel_t * channel = (l2cap_fixed_channel_t*) btstack_linked_list_iterator_next(&it);
1264         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
1265         l2cap_channel_t * dynamic_channel = (l2cap_channel_t *) channel;
1266         if (dynamic_channel->con_handle != con_handle) continue;
1267         if (dynamic_channel->remote_cid != remote_cid) continue;
1268         return dynamic_channel;
1269     }
1270     return NULL;
1271 }
1272 #endif
1273 
1274 #ifdef L2CAP_USES_CHANNELS
1275 uint8_t l2cap_request_can_send_now_event(uint16_t local_cid){
1276     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1277     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
1278     channel->waiting_for_can_send_now = 1;
1279     switch (channel->channel_type){
1280         case L2CAP_CHANNEL_TYPE_CLASSIC:
1281 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1282             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1283                 l2cap_ertm_notify_channel_can_send(channel);
1284                 return ERROR_CODE_SUCCESS;
1285             }
1286 #endif
1287             l2cap_notify_channel_can_send();
1288             break;
1289 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
1290         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
1291             l2cap_credit_based_notify_channel_can_send(channel);
1292             break;
1293 #endif
1294 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1295         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
1296             l2cap_credit_based_notify_channel_can_send(channel);
1297             break;
1298 #endif
1299         default:
1300             break;
1301     }
1302     return ERROR_CODE_SUCCESS;
1303 }
1304 
1305 bool l2cap_can_send_packet_now(uint16_t local_cid){
1306     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1307     if (!channel) return false;
1308     if (channel->state != L2CAP_STATE_OPEN) return false;
1309     switch (channel->channel_type){
1310         case L2CAP_CHANNEL_TYPE_CLASSIC:
1311 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1312             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1313                 return l2cap_ertm_can_store_packet_now(channel);
1314             }
1315 #endif
1316             return hci_can_send_acl_packet_now(channel->con_handle);
1317 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
1318         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
1319             return channel->send_sdu_buffer == NULL;
1320 #endif
1321 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1322         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
1323             return channel->send_sdu_buffer == NULL;
1324 #endif
1325         default:
1326             return false;
1327     }
1328 }
1329 
1330 uint8_t l2cap_send(uint16_t local_cid, const uint8_t *data, uint16_t len){
1331     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1332     if (!channel) {
1333         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
1334         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
1335     }
1336     switch (channel->channel_type){
1337 #ifdef ENABLE_CLASSIC
1338         case L2CAP_CHANNEL_TYPE_CLASSIC:
1339             return l2cap_classic_send(channel, data, len);
1340 #endif
1341 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
1342         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
1343             return l2cap_credit_based_send_data(channel, data, len);
1344 #endif
1345 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1346         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
1347             return l2cap_credit_based_send_data(channel, data, len);
1348 #endif
1349         default:
1350             return ERROR_CODE_UNSPECIFIED_ERROR;
1351     }
1352 }
1353 #endif
1354 
1355 #ifdef ENABLE_CLASSIC
1356 bool l2cap_can_send_prepared_packet_now(uint16_t local_cid){
1357     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1358     if (!channel) return false;
1359 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1360     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1361         return false;
1362     }
1363 #endif
1364     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
1365 }
1366 
1367 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
1368     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1369     if (channel) {
1370         return channel->remote_mtu;
1371     }
1372     return 0;
1373 }
1374 #endif
1375 
1376 #ifdef ENABLE_CLASSIC
1377 // RTX Timer only exist for dynamic channels
1378 static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
1379     btstack_linked_list_iterator_t it;
1380     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1381     while (btstack_linked_list_iterator_has_next(&it)){
1382         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1383         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
1384         if (&channel->rtx == ts) {
1385             return channel;
1386         }
1387     }
1388     return NULL;
1389 }
1390 
1391 static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
1392     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
1393     if (!channel) return;
1394 
1395     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
1396 
1397     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
1398     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
1399     // notify client
1400     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
1401 
1402     // discard channel
1403     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1404     l2cap_free_channel_entry(channel);
1405 }
1406 
1407 static uint8_t l2cap_classic_packet_boundary_flag(void){
1408     return (hci_non_flushable_packet_boundary_flag_supported() && (hci_automatic_flush_timeout() == 0)) ? 0x00 : 0x02;
1409 }
1410 #endif
1411 
1412 #ifdef L2CAP_USES_CHANNELS
1413 static void l2cap_stop_rtx(l2cap_channel_t * channel){
1414     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
1415     btstack_run_loop_remove_timer(&channel->rtx);
1416 }
1417 #endif
1418 
1419 static uint8_t l2cap_send_signaling_packet(hci_con_handle_t handle, uint8_t pb_flags, uint16_t cid, L2CAP_SIGNALING_COMMANDS cmd, int identifier, va_list argptr){
1420     if (!hci_can_send_acl_packet_now(handle)){
1421         log_info("l2cap_send_classic_signaling_packet, cannot send");
1422         return BTSTACK_ACL_BUFFERS_FULL;
1423     }
1424     hci_reserve_packet_buffer();
1425     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1426     uint16_t len = l2cap_create_signaling_packet(acl_buffer, handle, pb_flags, cid, cmd, identifier, argptr);
1427     va_end(argptr);
1428     return hci_send_acl_packet_buffer(len);
1429 }
1430 
1431 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
1432 static int l2cap_send_general_signaling_packet(hci_con_handle_t handle, uint16_t signaling_cid, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1433     va_list argptr;
1434     va_start(argptr, identifier);
1435     uint8_t pb_flags = 0x00;
1436 #ifdef ENABLE_CLASSIC
1437     if (signaling_cid == L2CAP_CID_SIGNALING){
1438         pb_flags = l2cap_classic_packet_boundary_flag();
1439     }
1440 #endif
1441 uint8_t result = l2cap_send_signaling_packet(handle, pb_flags, signaling_cid, cmd, identifier, argptr);
1442     va_end(argptr);
1443     return result;
1444 }
1445 #endif
1446 
1447 #ifdef ENABLE_CLASSIC
1448 
1449 static void l2cap_start_rtx(l2cap_channel_t * channel){
1450     l2cap_stop_rtx(channel);
1451     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
1452     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1453     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
1454     btstack_run_loop_add_timer(&channel->rtx);
1455 }
1456 
1457 static void l2cap_start_ertx(l2cap_channel_t * channel){
1458     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
1459     l2cap_stop_rtx(channel);
1460     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1461     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
1462     btstack_run_loop_add_timer(&channel->rtx);
1463 }
1464 
1465 void l2cap_require_security_level_2_for_outgoing_sdp(void){
1466     l2cap_require_security_level2_for_outgoing_sdp = 1;
1467 }
1468 
1469 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
1470     return (psm == BLUETOOTH_PSM_SDP) && (!l2cap_require_security_level2_for_outgoing_sdp);
1471 }
1472 
1473 static int l2cap_send_classic_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1474     va_list argptr;
1475     va_start(argptr, identifier);
1476     uint8_t pb_flag = l2cap_classic_packet_boundary_flag();
1477     uint8_t result = l2cap_send_signaling_packet(handle, pb_flag, L2CAP_CID_SIGNALING, cmd, identifier, argptr);
1478     va_end(argptr);
1479     return result;
1480 }
1481 
1482 // assumption - only on Classic connections
1483 // cannot be used for L2CAP ERTM
1484 uint8_t l2cap_send_prepared(uint16_t local_cid, uint16_t len){
1485 
1486     if (!hci_is_packet_buffer_reserved()){
1487         log_error("l2cap_send_prepared called without reserving packet first");
1488         return BTSTACK_ACL_BUFFERS_FULL;
1489     }
1490 
1491     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1492     if (!channel) {
1493         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
1494         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
1495     }
1496 
1497     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
1498         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
1499         return BTSTACK_ACL_BUFFERS_FULL;
1500     }
1501 
1502     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
1503 
1504     int fcs_size = 0;
1505 
1506 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1507     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->fcs_option){
1508         fcs_size = 2;
1509     }
1510 #endif
1511 
1512     // set non-flushable packet boundary flag if supported on Controller
1513     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1514     uint8_t packet_boundary_flag = l2cap_classic_packet_boundary_flag();
1515     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
1516 
1517 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1518     if (fcs_size){
1519         // calculate FCS over l2cap data
1520         uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
1521         log_info("I-Frame: fcs 0x%04x", fcs);
1522         little_endian_store_16(acl_buffer, 8 + len, fcs);
1523     }
1524 #endif
1525 
1526     // send
1527     return hci_send_acl_packet_buffer(len+8+fcs_size);
1528 }
1529 
1530 // assumption - only on Classic connections
1531 static uint8_t l2cap_classic_send(l2cap_channel_t * channel, const uint8_t *data, uint16_t len){
1532 
1533 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1534     // send in ERTM
1535     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1536         return l2cap_ertm_send(channel, data, len);
1537     }
1538 #endif
1539 
1540     if (len > channel->remote_mtu){
1541         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
1542         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
1543     }
1544 
1545     if (!hci_can_send_acl_packet_now(channel->con_handle)){
1546         log_info("l2cap_send cid 0x%02x, cannot send", channel->local_cid);
1547         return BTSTACK_ACL_BUFFERS_FULL;
1548     }
1549 
1550     hci_reserve_packet_buffer();
1551     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1552     (void)memcpy(&acl_buffer[8], data, len);
1553     return l2cap_send_prepared(channel->local_cid, len);
1554 }
1555 
1556 int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
1557     return l2cap_send_classic_signaling_packet(con_handle, ECHO_REQUEST, l2cap_next_sig_id(), len, data);
1558 }
1559 
1560 static inline void channelStateVarSetFlag(l2cap_channel_t *channel, uint16_t flag){
1561     channel->state_var = channel->state_var | flag;
1562 }
1563 
1564 static inline void channelStateVarClearFlag(l2cap_channel_t *channel, uint16_t flag){
1565     channel->state_var = channel->state_var & ~flag;
1566 }
1567 #endif
1568 
1569 
1570 #ifdef ENABLE_BLE
1571 static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1572     va_list argptr;
1573     va_start(argptr, identifier);
1574     uint8_t pb_flags = 0x00;  // First non-automatically-flushable packet of a higher layer message
1575     uint8_t result = l2cap_send_signaling_packet(handle, pb_flags, L2CAP_CID_SIGNALING_LE, cmd, identifier, argptr);
1576     va_end(argptr);
1577     return result;
1578 }
1579 #endif
1580 
1581 uint16_t l2cap_max_mtu(void){
1582     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
1583 }
1584 
1585 #ifdef ENABLE_BLE
1586 uint16_t l2cap_max_le_mtu(void){
1587     if (l2cap_le_custom_max_mtu != 0u) return l2cap_le_custom_max_mtu;
1588     return l2cap_max_mtu();
1589 }
1590 
1591 void l2cap_set_max_le_mtu(uint16_t max_mtu){
1592     if (max_mtu < l2cap_max_mtu()){
1593         l2cap_le_custom_max_mtu = max_mtu;
1594     }
1595 }
1596 #endif
1597 
1598 #ifdef ENABLE_CLASSIC
1599 
1600 static uint16_t l2cap_setup_options_mtu(uint8_t * config_options, uint16_t mtu){
1601     config_options[0] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
1602     config_options[1] = 2; // len param
1603     little_endian_store_16(config_options, 2, mtu);
1604     return 4;
1605 }
1606 
1607 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1608 static int l2cap_ertm_mode(l2cap_channel_t * channel){
1609     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
1610     return ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE)
1611         &&  (connection->l2cap_state.extended_feature_mask & 0x08));
1612 }
1613 #endif
1614 
1615 static uint16_t l2cap_setup_options_request(l2cap_channel_t * channel, uint8_t * config_options){
1616 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1617     // use ERTM options if supported by remote and channel ready to use it
1618     if (l2cap_ertm_mode(channel) && channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1619         return l2cap_setup_options_ertm_request(channel, config_options);
1620     }
1621 #endif
1622     uint16_t mtu = channel->local_mtu;
1623     return l2cap_setup_options_mtu(config_options, mtu);
1624 }
1625 
1626 static uint16_t l2cap_setup_options_mtu_response(l2cap_channel_t * channel, uint8_t * config_options){
1627     uint16_t mtu = btstack_min(channel->local_mtu, channel->remote_mtu);
1628     return l2cap_setup_options_mtu(config_options, mtu);
1629 }
1630 
1631 static uint32_t l2cap_extended_features_mask(void){
1632     // extended features request supported, features: fixed channels, unicast connectionless data reception
1633     uint32_t features = 0x280;
1634 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1635     features |= 0x0028;
1636 #endif
1637     return features;
1638 }
1639 #endif
1640 
1641 //
1642 #ifdef ENABLE_CLASSIC
1643 
1644 // returns true if channel was finalized
1645 static bool l2cap_run_for_classic_channel(l2cap_channel_t * channel){
1646 
1647 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1648     uint8_t  config_options[18];
1649 #else
1650     uint8_t  config_options[10];
1651 #endif
1652 
1653     switch (channel->state){
1654 
1655         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1656         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
1657             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1658             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
1659                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
1660                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONN_RESP_PEND);
1661                 l2cap_send_classic_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id,
1662                                                     channel->local_cid, channel->remote_cid, 1, 0);
1663             }
1664             break;
1665 
1666         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1667             if (!hci_can_send_command_packet_now()) break;
1668             // send connection request - set state first
1669             channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
1670             // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
1671             (void)memcpy(l2cap_outgoing_classic_addr, channel->address, 6);
1672             hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_get_allow_role_switch());
1673             break;
1674 
1675         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
1676             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1677             channel->state = L2CAP_STATE_INVALID;
1678             l2cap_send_classic_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id,
1679                                                 channel->local_cid, channel->remote_cid, channel->reason, 0);
1680             // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1681             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1682             l2cap_free_channel_entry(channel);
1683             channel = NULL;
1684             break;
1685 
1686         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
1687             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1688             channel->state = L2CAP_STATE_CONFIG;
1689             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1690             l2cap_send_classic_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id,
1691                                                 channel->local_cid, channel->remote_cid, 0, 0);
1692             break;
1693 
1694         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
1695             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1696             // success, start l2cap handshake
1697             channel->local_sig_id = l2cap_next_sig_id();
1698             channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
1699             l2cap_send_classic_signaling_packet(channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id,
1700                                                 channel->psm, channel->local_cid);
1701             l2cap_start_rtx(channel);
1702             break;
1703 
1704         case L2CAP_STATE_CONFIG:
1705             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1706 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1707             // fallback to basic mode if ERTM requested but not not supported by remote
1708             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1709                 if (!l2cap_ertm_mode(channel)){
1710                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1711                     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
1712                 }
1713             }
1714 #endif
1715             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
1716                 uint16_t flags = 0;
1717                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1718                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
1719                     flags = 1;
1720                 } else {
1721                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1722                 }
1723                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
1724                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1725                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1726                                                         channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS,
1727                                                         1, &channel->unknown_option);
1728 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1729                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
1730                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1731                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1732                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1733                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1734                                                         channel->remote_cid, flags,
1735                                                         L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS, options_size,
1736                                                         &config_options);
1737                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM){
1738                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
1739                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1740                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1741                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1742                                                         channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS,
1743                                                         options_size, &config_options);
1744 #endif
1745                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
1746                     channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1747                     uint16_t options_size = l2cap_setup_options_mtu_response(channel, config_options);
1748                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1749                                                         channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS,
1750                                                         options_size, &config_options);
1751                 } else {
1752                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1753                                                         channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
1754                 }
1755                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1756             }
1757             else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
1758                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1759                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
1760                 channel->local_sig_id = l2cap_next_sig_id();
1761                 uint16_t options_size = l2cap_setup_options_request(channel, config_options);
1762                 l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id,
1763                                                     channel->remote_cid, 0, options_size, &config_options);
1764                 l2cap_start_rtx(channel);
1765             }
1766             if (l2cap_channel_ready_for_open(channel)){
1767                 channel->state = L2CAP_STATE_OPEN;
1768                 l2cap_emit_channel_opened(channel, 0);  // success
1769             }
1770             break;
1771 
1772         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1773             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1774             channel->state = L2CAP_STATE_INVALID;
1775             l2cap_send_classic_signaling_packet(channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id,
1776                                                 channel->local_cid, channel->remote_cid);
1777             // we don't start an RTX timer for a disconnect - there's no point in closing the channel if the other side doesn't respond :)
1778             l2cap_finalize_channel_close(channel);  // -- remove from list
1779             channel = NULL;
1780             break;
1781 
1782         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1783             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1784             channel->local_sig_id = l2cap_next_sig_id();
1785             channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1786             l2cap_send_classic_signaling_packet(channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id,
1787                                                 channel->remote_cid, channel->local_cid);
1788             break;
1789         default:
1790             break;
1791     }
1792 
1793     // handle channel finalize on L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE and L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE
1794     return channel == NULL;
1795 }
1796 
1797 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1798 static void l2cap_run_for_classic_channel_ertm(l2cap_channel_t * channel){
1799 
1800     // ERTM mode
1801     if (channel->mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) return;
1802 
1803     // check if we can still send
1804     if (channel->con_handle == HCI_CON_HANDLE_INVALID) return;
1805     if (!hci_can_send_acl_packet_now(channel->con_handle)) return;
1806 
1807     if (channel->send_supervisor_frame_receiver_ready){
1808         channel->send_supervisor_frame_receiver_ready = 0;
1809         log_info("Send S-Frame: RR %u, final %u", channel->req_seq, channel->set_final_bit_after_packet_with_poll_bit_set);
1810         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 0,  channel->set_final_bit_after_packet_with_poll_bit_set, channel->req_seq);
1811         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1812         l2cap_ertm_send_supervisor_frame(channel, control);
1813         return;
1814     }
1815     if (channel->send_supervisor_frame_receiver_ready_poll){
1816         channel->send_supervisor_frame_receiver_ready_poll = 0;
1817         log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
1818         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
1819         l2cap_ertm_send_supervisor_frame(channel, control);
1820         return;
1821     }
1822     if (channel->send_supervisor_frame_receiver_not_ready){
1823         channel->send_supervisor_frame_receiver_not_ready = 0;
1824         log_info("Send S-Frame: RNR %u", channel->req_seq);
1825         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
1826         l2cap_ertm_send_supervisor_frame(channel, control);
1827         return;
1828     }
1829     if (channel->send_supervisor_frame_reject){
1830         channel->send_supervisor_frame_reject = 0;
1831         log_info("Send S-Frame: REJ %u", channel->req_seq);
1832         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 0, 0, channel->req_seq);
1833         l2cap_ertm_send_supervisor_frame(channel, control);
1834         return;
1835     }
1836     if (channel->send_supervisor_frame_selective_reject){
1837         channel->send_supervisor_frame_selective_reject = 0;
1838         log_info("Send S-Frame: SREJ %u", channel->expected_tx_seq);
1839         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT, 0, channel->set_final_bit_after_packet_with_poll_bit_set, channel->expected_tx_seq);
1840         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1841         l2cap_ertm_send_supervisor_frame(channel, control);
1842         return;
1843     }
1844 
1845     if (channel->srej_active){
1846         int i;
1847         for (i=0;i<channel->num_tx_buffers;i++){
1848             l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
1849             if (tx_state->retransmission_requested) {
1850                 tx_state->retransmission_requested = 0;
1851                 uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set;
1852                 channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1853                 l2cap_ertm_send_information_frame(channel, i, final);
1854                 break;
1855             }
1856         }
1857         if (i == channel->num_tx_buffers){
1858             // no retransmission request found
1859             channel->srej_active = 0;
1860         } else {
1861             // packet was sent
1862             return;
1863         }
1864     }
1865 }
1866 #endif /* ERTM */
1867 #endif /* Classic */
1868 
1869 static void l2cap_run_signaling_response(void) {
1870 
1871     // check pending signaling responses
1872     while (l2cap_signaling_responses_pending){
1873 
1874         hci_con_handle_t handle = l2cap_signaling_responses[0].handle;
1875 
1876         if (!hci_can_send_acl_packet_now(handle)) break;
1877 
1878         uint8_t  sig_id        = l2cap_signaling_responses[0].sig_id;
1879         uint8_t  response_code = l2cap_signaling_responses[0].code;
1880         uint16_t result        = l2cap_signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT, REJECT_SM_PAIRING, L2CAP_CREDIT_BASED_CONNECTION_REQUEST
1881         uint8_t  buffer[4];                                          // REJECT_SM_PAIRING
1882         uint16_t source_cid    = l2cap_signaling_responses[0].cid;   // CONNECTION_REQUEST, REJECT_SM_PAIRING, DISCONNECT_REQUEST
1883 #ifdef ENABLE_CLASSIC
1884         uint16_t info_type     = l2cap_signaling_responses[0].data;  // INFORMATION_REQUEST
1885 #endif
1886 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1887         uint8_t num_channels = l2cap_signaling_responses[0].cid >> 8;                 // L2CAP_CREDIT_BASED_CONNECTION_REQUEST
1888         uint16_t signaling_cid = (uint16_t) l2cap_signaling_responses[0].cid & 0xff;  // L2CAP_CREDIT_BASED_CONNECTION_REQUEST, L2CAP_CREDIT_BASED_CONNECTION_REQUEST
1889 #endif
1890 
1891         // remove first item before sending (to avoid sending response mutliple times)
1892         l2cap_signaling_responses_pending--;
1893         int i;
1894         for (i=0; i < l2cap_signaling_responses_pending; i++){
1895             (void)memcpy(&l2cap_signaling_responses[i],
1896                          &l2cap_signaling_responses[i + 1],
1897                          sizeof(l2cap_signaling_response_t));
1898         }
1899 
1900         switch (response_code){
1901 #ifdef ENABLE_CLASSIC
1902             case CONNECTION_REQUEST:
1903                 l2cap_send_classic_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
1904                 break;
1905             case ECHO_REQUEST:
1906                 l2cap_send_classic_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
1907                 break;
1908             case INFORMATION_REQUEST:
1909                 switch (info_type){
1910                     case L2CAP_INFO_TYPE_CONNECTIONLESS_MTU: {
1911                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
1912                         l2cap_send_classic_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0,
1913                                                             sizeof(connectionless_mtu), &connectionless_mtu);
1914                         }
1915                         break;
1916                     case L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED: {
1917                             uint32_t features = l2cap_extended_features_mask();
1918                         l2cap_send_classic_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0,
1919                                                             sizeof(features), &features);
1920                         }
1921                         break;
1922                     case L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED: {
1923                             uint8_t map[8];
1924                             memset(map, 0, 8);
1925                             // L2CAP Signaling Channel + Connectionless reception
1926                             map[0] = (1 << L2CAP_CID_SIGNALING) | (1 << L2CAP_CID_CONNECTIONLESS_CHANNEL);
1927 #if defined(ENABLE_BLE) || defined (ENABLE_EXPLICIT_BR_EDR_SECURITY_MANAGER)
1928                             // BR/EDR Security Manager (bit 7) if BR/EDR Secure Connections possible
1929                             if (gap_secure_connections_active()){
1930                                 map[0] |= (1 << L2CAP_CID_BR_EDR_SECURITY_MANAGER);
1931                             }
1932 #endif
1933                             l2cap_send_classic_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0,
1934                                                             sizeof(map), &map);
1935                         }
1936                         break;
1937                     default:
1938                         // all other types are not supported
1939                         l2cap_send_classic_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 1, 0, NULL);
1940                         break;
1941                 }
1942                 break;
1943             case COMMAND_REJECT:
1944                 l2cap_send_classic_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
1945                 break;
1946 #endif
1947 #ifdef ENABLE_BLE
1948             case LE_CREDIT_BASED_CONNECTION_REQUEST:
1949                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
1950                 break;
1951             case DISCONNECTION_REQUEST:
1952                 // Invalid CID, local cid, remote cid
1953                 little_endian_store_16(buffer, 0, result);
1954                 little_endian_store_16(buffer, 2, source_cid);
1955                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, 0x0002, 4, buffer);
1956                 break;
1957             case COMMAND_REJECT_LE:
1958                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
1959                 break;
1960 #endif
1961 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1962             case L2CAP_CREDIT_BASED_CONNECTION_REQUEST: {
1963                 // send variable size array or cids with each cid being zero
1964                 uint16_t cids[6];
1965                 (void) memset(cids, 0xff, sizeof(cids));
1966                 (void) memset(cids, 0x00, num_channels * sizeof(uint16_t));
1967                 l2cap_send_general_signaling_packet(handle, signaling_cid, L2CAP_CREDIT_BASED_CONNECTION_RESPONSE,
1968                                                     sig_id, 0, 0, 0, result, cids);
1969                 break;
1970             }
1971 
1972             case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
1973                 l2cap_send_general_signaling_packet(handle, signaling_cid, L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE,
1974                                                     sig_id, result);
1975                 break;
1976 #endif
1977             case SM_PAIRING_FAILED:
1978                 buffer[0] = SM_CODE_PAIRING_FAILED;
1979                 buffer[1] = (uint8_t) result;
1980                 l2cap_send_connectionless(handle, source_cid, buffer, 2);
1981                 break;
1982             default:
1983                 // should not happen
1984                 break;
1985         }
1986     }
1987 }
1988 
1989 #ifdef ENABLE_CLASSIC
1990 static bool l2ap_run_information_requests(void){
1991     // send l2cap information request if requested
1992     btstack_linked_list_iterator_t it;
1993     hci_connections_get_iterator(&it);
1994     uint8_t info_type;
1995     l2cap_information_state_t new_state;
1996     while(btstack_linked_list_iterator_has_next(&it)){
1997         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1998         switch (connection->l2cap_state.information_state){
1999             case L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST:
2000                 info_type = L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED;
2001                 new_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
2002                 break;
2003             case L2CAP_INFORMATION_STATE_W2_SEND_FIXED_CHANNELS_REQUEST:
2004                 info_type = L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED;
2005                 new_state = L2CAP_INFORMATION_STATE_W4_FIXED_CHANNELS_RESPONSE;
2006                 break;
2007             default:
2008                 continue;
2009         }
2010         if (!hci_can_send_acl_packet_now(connection->con_handle)) break;
2011 
2012         connection->l2cap_state.information_state = new_state;
2013         uint8_t sig_id = l2cap_next_sig_id();
2014         l2cap_send_classic_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
2015     }
2016     return false;
2017 }
2018 #endif
2019 
2020 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2021 static void l2cap_cbm_run_channels(void){
2022     btstack_linked_list_iterator_t it;
2023     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2024     while (btstack_linked_list_iterator_has_next(&it)){
2025         uint16_t mps;
2026         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2027 
2028         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CHANNEL_CBM) continue;
2029 
2030         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
2031         switch (channel->state){
2032             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
2033                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
2034                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
2035                 // le psm, source cid, mtu, mps, initial credits
2036                 channel->local_sig_id = l2cap_next_sig_id();
2037                 channel->credits_incoming =  channel->new_credits_incoming;
2038                 channel->new_credits_incoming = 0;
2039                 channel->local_mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
2040                 l2cap_send_le_signaling_packet( channel->con_handle, LE_CREDIT_BASED_CONNECTION_REQUEST,
2041                                                 channel->local_sig_id, channel->psm, channel->local_cid, channel->local_mtu,
2042                                                 channel->local_mps, channel->credits_incoming);
2043                 break;
2044             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
2045                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
2046                 // TODO: support larger MPS
2047                 channel->state = L2CAP_STATE_OPEN;
2048                 channel->credits_incoming =  channel->new_credits_incoming;
2049                 channel->new_credits_incoming = 0;
2050                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
2051                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->local_mtu, mps, channel->credits_incoming, 0);
2052                 // notify client
2053                 l2cap_cbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
2054                 break;
2055             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
2056                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
2057                 channel->state = L2CAP_STATE_INVALID;
2058                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
2059                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
2060                 btstack_linked_list_iterator_remove(&it);
2061                 l2cap_free_channel_entry(channel);
2062                 break;
2063             case L2CAP_STATE_OPEN:
2064                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
2065                 if (channel->new_credits_incoming){
2066                     l2cap_credit_based_send_credits(channel);
2067                 }
2068                 break;
2069             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2070                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
2071                 channel->local_sig_id = l2cap_next_sig_id();
2072                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
2073                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
2074                 break;
2075             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
2076                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
2077                 channel->state = L2CAP_STATE_INVALID;
2078                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
2079                 l2cap_cbm_finialize_channel_close(channel);  // -- remove from list
2080                 break;
2081             default:
2082                 break;
2083         }
2084     }
2085 }
2086 
2087 static inline uint8_t l2cap_cbm_status_for_result(uint16_t result) {
2088     switch (result) {
2089         case L2CAP_CBM_CONNECTION_RESULT_SUCCESS:
2090             return ERROR_CODE_SUCCESS;
2091         case L2CAP_CBM_CONNECTION_RESULT_SPSM_NOT_SUPPORTED:
2092             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_PSM;
2093         case L2CAP_CBM_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE:
2094             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_RESOURCES;
2095         case L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHENTICATION:
2096         case L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHORIZATION:
2097         case L2CAP_CBM_CONNECTION_RESULT_ENCYRPTION_KEY_SIZE_TOO_SHORT:
2098         case L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_ENCRYPTION:
2099             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY;
2100         default:
2101             // invalid Source CID, Source CID already allocated, unacceptable parameters
2102             return L2CAP_CONNECTION_RESPONSE_UNKNOWN_ERROR;
2103     }
2104 }
2105 
2106 #endif
2107 
2108 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2109 
2110 static void l2cap_run_trigger_callback(void * context){
2111     UNUSED(context);
2112     l2cap_run();
2113 }
2114 
2115 static void l2cap_run_trigger(void){
2116     btstack_run_loop_execute_on_main_thread(&l2cap_trigger_run_registration);
2117 }
2118 
2119 // 11BH22222
2120 static void l2cap_ecbm_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
2121     log_info("opened ecbm channel status 0x%x addr_type %u addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x local_mtu %u, remote_mtu %u",
2122             status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
2123             channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
2124     uint8_t event[23];
2125     event[0] = L2CAP_EVENT_ECBM_CHANNEL_OPENED;
2126     event[1] = sizeof(event) - 2u;
2127     event[2] = status;
2128     event[3] = channel->address_type;
2129     reverse_bd_addr(channel->address, &event[4]);
2130     little_endian_store_16(event, 10, channel->con_handle);
2131     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
2132     little_endian_store_16(event, 13, channel->psm);
2133     little_endian_store_16(event, 15, channel->local_cid);
2134     little_endian_store_16(event, 17, channel->remote_cid);
2135     little_endian_store_16(event, 19, channel->local_mtu);
2136     little_endian_store_16(event, 21, channel->remote_mtu);
2137     hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
2138     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
2139 }
2140 
2141 static void l2cap_ecbm_emit_reconfigure_complete(l2cap_channel_t *channel, uint16_t result) {
2142     // emit event
2143     uint8_t event[6];
2144     event[0] = L2CAP_EVENT_ECBM_RECONFIGURATION_COMPLETE;
2145     event[1] = sizeof(event) - 2;
2146     little_endian_store_16(event, 2, channel->local_cid);
2147     little_endian_store_16(event, 4, result);
2148     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
2149 }
2150 
2151 static void l2cap_ecbm_run_channels(void) {
2152     hci_con_handle_t con_handle = HCI_CON_HANDLE_INVALID;
2153     // num max channels + 1 for signaling pdu generator
2154     uint16_t cids[L2CAP_ECBM_MAX_CID_ARRAY_SIZE + 1];
2155     uint8_t num_cids = 0;
2156     uint8_t sig_id;
2157     uint16_t spsm;
2158     L2CAP_STATE matching_state;
2159     bool match_remote_sig_cid;
2160     uint8_t result = 0;
2161     uint16_t local_mtu;
2162     uint16_t initial_credits;
2163     uint16_t signaling_cid;
2164     L2CAP_STATE new_state;
2165     uint16_t local_mps;
2166 
2167     // pick first channel that needs to send a combined signaling pdu and setup collection via break
2168     // then collect all others that belong to the same pdu
2169     btstack_linked_list_iterator_t it;
2170     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2171     while (btstack_linked_list_iterator_has_next(&it)) {
2172         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2173         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CHANNEL_ECBM) continue;
2174         if (con_handle == HCI_CON_HANDLE_INVALID) {
2175             switch (channel->state) {
2176                 case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST:
2177                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2178                     local_mtu = channel->local_mtu;
2179                     local_mps = channel->local_mps;
2180                     spsm = channel->psm;
2181                     result = channel->reason;
2182                     initial_credits = channel->credits_incoming;
2183                     sig_id = channel->local_sig_id;
2184                     new_state = L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE;
2185                     match_remote_sig_cid = false;
2186                     break;
2187                 case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE:
2188                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2189                     local_mtu = channel->local_mtu;
2190                     local_mps = channel->local_mps;
2191                     initial_credits = channel->credits_incoming;
2192                     sig_id = channel->remote_sig_id;
2193                     new_state = L2CAP_STATE_OPEN;
2194                     match_remote_sig_cid = true;
2195                     break;
2196                 case L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST:
2197                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2198                     sig_id = channel->local_sig_id;
2199                     local_mtu = channel->renegotiate_mtu;
2200                     local_mps = channel->local_mps;
2201                     new_state = L2CAP_STATE_WAIT_ENHANCED_RENEGOTIATION_RESPONSE;
2202                     match_remote_sig_cid = false;
2203                     break;
2204                 case L2CAP_STATE_OPEN:
2205                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2206                     if (channel->new_credits_incoming) {
2207                         l2cap_credit_based_send_credits(channel);
2208                     }
2209                     continue;
2210                 case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2211                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2212                     channel->local_sig_id = l2cap_next_sig_id();
2213                     channel->state = L2CAP_STATE_WAIT_DISCONNECT;
2214                     signaling_cid = channel->address_type == BD_ADDR_TYPE_ACL ? L2CAP_CID_SIGNALING : L2CAP_CID_SIGNALING_LE;
2215                     l2cap_send_general_signaling_packet(channel->con_handle, signaling_cid, DISCONNECTION_REQUEST,
2216                                                         channel->local_sig_id, channel->remote_cid, channel->local_cid);
2217                     continue;
2218                 case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
2219                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2220                     channel->state = L2CAP_STATE_INVALID;
2221                     signaling_cid = channel->address_type == BD_ADDR_TYPE_ACL ? L2CAP_CID_SIGNALING : L2CAP_CID_SIGNALING_LE;
2222                     l2cap_send_general_signaling_packet(channel->con_handle, signaling_cid, DISCONNECTION_RESPONSE,
2223                                                         channel->remote_sig_id, channel->local_cid,
2224                                                         channel->remote_cid);
2225                     l2cap_cbm_finialize_channel_close(channel);  // -- remove from list
2226                     continue;
2227                 default:
2228                     continue;
2229             }
2230 
2231             // channel picked - setup cid array and collect info
2232             (void) memset(cids, 0xff, sizeof(cids));
2233             (void) memset(cids, 0, channel->num_cids * sizeof(uint16_t));
2234             matching_state = channel->state;
2235             con_handle = channel->con_handle;
2236             signaling_cid = channel->address_type == BD_ADDR_TYPE_ACL ? L2CAP_CID_SIGNALING : L2CAP_CID_SIGNALING_LE;
2237             num_cids = channel->num_cids;
2238 
2239         } else {
2240             // check if it matches first channel by state, con_handle, and signaling id
2241             if (matching_state != channel->state) continue;
2242             if (channel->con_handle != con_handle) continue;
2243             if (match_remote_sig_cid) {
2244                 if (channel->remote_sig_id != sig_id) continue;
2245             } else {
2246                 if (channel->local_sig_id != sig_id) continue;
2247             }
2248         }
2249 
2250         // add this cid
2251         cids[channel->cid_index] = channel->local_cid;
2252 
2253         // set new state
2254         channel->state = new_state;
2255 
2256         // handle open for L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE
2257         if (matching_state == L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE) {
2258             if (channel->reason == L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS) {
2259                 l2cap_ecbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
2260             } else {
2261                 result = channel->reason;
2262                 btstack_linked_list_iterator_remove(&it);
2263                 btstack_memory_l2cap_channel_free(channel);
2264             }
2265         }
2266     }
2267 
2268     if (con_handle != HCI_CON_HANDLE_INVALID) {
2269         switch (matching_state) {
2270             case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST:
2271                 log_info("send combined connection request for %u cids", num_cids);
2272                 l2cap_send_general_signaling_packet(con_handle, signaling_cid, L2CAP_CREDIT_BASED_CONNECTION_REQUEST,
2273                                                     sig_id, spsm, local_mtu, local_mps, initial_credits, cids);
2274                 break;
2275             case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE:
2276                 log_info("send combined connection response for %u cids", num_cids);
2277                 l2cap_send_general_signaling_packet(con_handle, signaling_cid, L2CAP_CREDIT_BASED_CONNECTION_RESPONSE,
2278                                                     sig_id, local_mtu, local_mps, initial_credits, result, cids);
2279                 break;
2280             case L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST:
2281                 log_info("send combined renegotiation request for %u cids", num_cids);
2282                 l2cap_send_general_signaling_packet(con_handle, signaling_cid, L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST,
2283                                                     sig_id, local_mtu, local_mps, cids);
2284                 break;
2285             default:
2286                 break;
2287         }
2288     }
2289 }
2290 #endif
2291 
2292 // MARK: L2CAP_RUN
2293 // process outstanding signaling tasks
2294 static void l2cap_run(void){
2295 
2296     // log_info("l2cap_run: entered");
2297     l2cap_run_signaling_response();
2298 
2299 #ifdef ENABLE_CLASSIC
2300     bool done = l2ap_run_information_requests();
2301     if (done) return;
2302 #endif
2303 
2304 #if defined(ENABLE_CLASSIC) || defined(ENABLE_BLE)
2305     btstack_linked_list_iterator_t it;
2306 #endif
2307 
2308 #ifdef ENABLE_CLASSIC
2309     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2310     while (btstack_linked_list_iterator_has_next(&it)){
2311 
2312         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2313 
2314         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CLASSIC) continue;
2315 
2316         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
2317         bool finalized = l2cap_run_for_classic_channel(channel);
2318 
2319         if (!finalized) {
2320 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2321             l2cap_run_for_classic_channel_ertm(channel);
2322 #endif
2323         }
2324     }
2325 #endif
2326 
2327 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2328     l2cap_cbm_run_channels();
2329 #endif
2330 
2331 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2332     l2cap_ecbm_run_channels();
2333 #endif
2334 
2335 #ifdef ENABLE_BLE
2336     // send l2cap con paramter update if necessary
2337     hci_connections_get_iterator(&it);
2338     while(btstack_linked_list_iterator_has_next(&it)){
2339         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
2340         if ((connection->address_type != BD_ADDR_TYPE_LE_PUBLIC) && (connection->address_type != BD_ADDR_TYPE_LE_RANDOM)) continue;
2341         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
2342         switch (connection->le_con_parameter_update_state){
2343             case CON_PARAMETER_UPDATE_SEND_REQUEST:
2344                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2345                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, l2cap_next_sig_id(),
2346                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
2347                 break;
2348             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
2349                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
2350                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
2351                 break;
2352             case CON_PARAMETER_UPDATE_DENY:
2353                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2354                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
2355                 break;
2356             default:
2357                 break;
2358         }
2359     }
2360 #endif
2361 
2362     if (l2cap_call_notify_channel_in_run){
2363         l2cap_call_notify_channel_in_run = false;
2364         l2cap_notify_channel_can_send();
2365     }
2366 
2367     // log_info("l2cap_run: exit");
2368 }
2369 
2370 #ifdef ENABLE_CLASSIC
2371 static void l2cap_ready_to_connect(l2cap_channel_t * channel){
2372 
2373 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2374     // assumption: outgoing connection
2375     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
2376         // ERTM requested: trigger information request if not already started then wait for response
2377         hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
2378         switch (connection->l2cap_state.information_state){
2379             case L2CAP_INFORMATION_STATE_DONE:
2380                 break;
2381             case L2CAP_INFORMATION_STATE_IDLE:
2382                 connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2383                 /* fall through */
2384             default:
2385                 channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
2386                 return;
2387         }
2388     }
2389 #endif
2390 
2391     // fine, go ahead
2392     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
2393 }
2394 
2395 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
2396     if ((channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE) || (channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION)) {
2397         log_info("connection complete con_handle %04x - for channel %p cid 0x%04x", (int) con_handle, channel, channel->local_cid);
2398         channel->con_handle = con_handle;
2399         // query remote features if pairing is required
2400         if (channel->required_security_level > LEVEL_0){
2401             channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
2402             hci_remote_features_query(con_handle);
2403         } else {
2404             l2cap_ready_to_connect(channel);
2405         }
2406     }
2407 }
2408 
2409 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
2410     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
2411 
2412     bool security_required = channel->required_security_level > LEVEL_0;
2413 
2414     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) != 0){
2415 
2416         // Core V5.2, Vol 3, Part C, 5.2.2.2 - Security Mode 4
2417         //   When a remote device attempts to access a service offered by a Bluetooth device that is in security mode 4
2418         //   and a sufficient link key exists and authentication has not been performed the local device shall authenticate
2419         //   the remote device and enable encryption after the channel establishment request is received but before a channel
2420         //   establishment confirmation (L2CAP_ConnectRsp with result code of 0x0000 or a higher-level channel establishment
2421         //   confirmation such as that of RFCOMM) is sent.
2422 
2423         //   If the remote device has indicated support for Secure Simple Pairing, a channel establishment request is
2424         //   received for a service other than SDP, and encryption has not yet been enabled, then the local device shall
2425         //   disconnect the ACL link with error code 0x05 - Authentication Failure.
2426 
2427         // => Disconnect if l2cap request received in mode 4 and ssp supported, non-sdp psm, not encrypted, no link key available
2428         if ((gap_get_security_mode() == GAP_SECURITY_MODE_4)
2429         && gap_ssp_supported_on_both_sides(channel->con_handle)
2430         && (channel->psm != PSM_SDP)
2431         && (gap_encryption_key_size(channel->con_handle) == 0)){
2432             hci_disconnect_security_block(channel->con_handle);
2433             return;
2434         }
2435 
2436         // incoming: assert security requirements
2437         channel->state = L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
2438         if (channel->required_security_level <= gap_security_level(channel->con_handle)){
2439             l2cap_handle_security_level_incoming_sufficient(channel);
2440         } else {
2441             // send connection pending if not already done
2442             if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONN_RESP_PEND) == 0){
2443                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND;
2444             }
2445             gap_request_security_level(channel->con_handle, channel->required_security_level);
2446         }
2447     } else {
2448         // outgoing: we have been waiting for remote supported features
2449         if (security_required){
2450             // request security level
2451             channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
2452             gap_request_security_level(channel->con_handle, channel->required_security_level);
2453         } else {
2454             l2cap_ready_to_connect(channel);
2455         }
2456     }
2457 }
2458 #endif
2459 
2460 #ifdef L2CAP_USES_CHANNELS
2461 static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, l2cap_channel_type_t channel_type, bd_addr_t address, bd_addr_type_t address_type,
2462     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
2463 
2464     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
2465     if (!channel) {
2466         return NULL;
2467     }
2468 
2469     // fill in
2470     channel->packet_handler = packet_handler;
2471     channel->channel_type   = channel_type;
2472     bd_addr_copy(channel->address, address);
2473     channel->address_type = address_type;
2474     channel->psm = psm;
2475     channel->local_mtu  = local_mtu;
2476     channel->remote_mtu = L2CAP_DEFAULT_MTU;
2477     channel->required_security_level = security_level;
2478 
2479     //
2480     channel->local_cid = l2cap_next_local_cid();
2481     channel->con_handle = HCI_CON_HANDLE_INVALID;
2482 
2483     // set initial state
2484     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
2485     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
2486     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
2487     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
2488 
2489     log_info("create channel %p, local_cid 0x%04x", channel, channel->local_cid);
2490 
2491     return channel;
2492 }
2493 
2494 static void l2cap_free_channel_entry(l2cap_channel_t * channel){
2495     log_info("free channel %p, local_cid 0x%04x", channel, channel->local_cid);
2496     // assert all timers are stopped
2497     l2cap_stop_rtx(channel);
2498 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2499     l2cap_ertm_stop_retransmission_timer(channel);
2500     l2cap_ertm_stop_monitor_timer(channel);
2501 #endif
2502     // free  memory
2503     btstack_memory_l2cap_channel_free(channel);
2504 }
2505 #endif
2506 
2507 #ifdef ENABLE_CLASSIC
2508 
2509 /**
2510  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
2511  * @param packet_handler
2512  * @param address
2513  * @param psm
2514  * @param mtu
2515  * @param local_cid
2516  */
2517 
2518 uint8_t l2cap_create_channel(btstack_packet_handler_t channel_packet_handler, bd_addr_t address, uint16_t psm, uint16_t mtu, uint16_t * out_local_cid){
2519     // limit MTU to the size of our outgoing HCI buffer
2520     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
2521 
2522 	// determine security level based on psm
2523 	const gap_security_level_t security_level = l2cap_security_level_0_allowed_for_PSM(psm) ? LEVEL_0 : gap_get_security_level();
2524 	log_info("create channel addr %s psm 0x%x mtu %u -> local mtu %u, sec level %u", bd_addr_to_str(address), psm, mtu, local_mtu, (int) security_level);
2525 
2526     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, address, BD_ADDR_TYPE_ACL, psm, local_mtu, security_level);
2527     if (!channel) {
2528         return BTSTACK_MEMORY_ALLOC_FAILED;
2529     }
2530 
2531 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2532     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2533 #endif
2534 
2535     // add to connections list
2536     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2537 
2538     // store local_cid
2539     if (out_local_cid){
2540        *out_local_cid = channel->local_cid;
2541     }
2542 
2543 	// state: L2CAP_STATE_WILL_SEND_CREATE_CONNECTION
2544 
2545     // check if hci connection is already usable,
2546     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
2547     if (conn && conn->state == OPEN){
2548     	// simulate connection complete
2549 	    l2cap_handle_connection_complete(conn->con_handle, channel);
2550 
2551 	    // state: L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES or L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST
2552 
2553         // simulate if remote supported features if requested and already received
2554         if ((channel->state == L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) && hci_remote_features_available(conn->con_handle)) {
2555         	// simulate remote features received
2556             l2cap_handle_remote_supported_features_received(channel);
2557         }
2558     }
2559 
2560     l2cap_run();
2561 
2562     return ERROR_CODE_SUCCESS;
2563 }
2564 
2565 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
2566     // mark all channels before emitting open events as these could trigger new connetion requests to the same device
2567     btstack_linked_list_iterator_t it;
2568     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2569     while (btstack_linked_list_iterator_has_next(&it)){
2570         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2571         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2572         if (bd_addr_cmp( channel->address, address) != 0) continue;
2573         // channel for this address found
2574         switch (channel->state){
2575             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2576             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2577                 channel->state = L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD;
2578                 break;
2579             default:
2580                 break;
2581         }
2582     }
2583     // emit and free marked entries. restart loop to deal with list changes
2584     int done = 0;
2585     while (!done) {
2586         done = 1;
2587         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2588         while (btstack_linked_list_iterator_has_next(&it)){
2589             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2590             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2591             if (channel->state == L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD){
2592                 done = 0;
2593                 // failure, forward error code
2594                 l2cap_handle_channel_open_failed(channel, status);
2595                 // discard channel
2596                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2597                 l2cap_free_channel_entry(channel);
2598                 break;
2599             }
2600         }
2601     }
2602 
2603 }
2604 
2605 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
2606     btstack_linked_list_iterator_t it;
2607     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2608     while (btstack_linked_list_iterator_has_next(&it)){
2609         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2610         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2611         if ( ! bd_addr_cmp( channel->address, address) ){
2612             l2cap_handle_connection_complete(handle, channel);
2613         }
2614     }
2615 
2616 #ifdef ENABLE_L2CAP_INFORMATION_REQUESTS_ON_CONNECT
2617     // trigger query of extended features and fixed channels right away (instead of later)
2618     hci_connection_t * hci_connection = hci_connection_for_handle(handle);
2619     btstack_assert(hci_connection != NULL);
2620     hci_connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2621 #endif
2622 
2623     // process
2624     l2cap_run();
2625 }
2626 #endif
2627 
2628 static bool l2cap_channel_ready_to_send(l2cap_channel_t * channel){
2629     switch (channel->channel_type){
2630 #ifdef ENABLE_CLASSIC
2631         case L2CAP_CHANNEL_TYPE_CLASSIC:
2632             if (channel->state != L2CAP_STATE_OPEN) return false;
2633 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2634             // send if we have more data and remote windows isn't full yet
2635             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2636                 if (channel->unacked_frames >= btstack_min(channel->num_stored_tx_frames, channel->remote_tx_window_size)) return false;
2637                 return hci_can_send_acl_packet_now(channel->con_handle);
2638             }
2639 #endif
2640             if (!channel->waiting_for_can_send_now) return false;
2641             return hci_can_send_acl_packet_now(channel->con_handle);
2642         case L2CAP_CHANNEL_TYPE_FIXED_CLASSIC:
2643         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2644             if (!channel->waiting_for_can_send_now) return false;
2645             return hci_can_send_acl_classic_packet_now();
2646 #endif
2647 #ifdef ENABLE_BLE
2648         case L2CAP_CHANNEL_TYPE_FIXED_LE:
2649             if (!channel->waiting_for_can_send_now) return false;
2650             return hci_can_send_acl_le_packet_now();
2651 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2652         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
2653             if (channel->state != L2CAP_STATE_OPEN) return false;
2654             if (channel->send_sdu_buffer == NULL) return false;
2655             if (channel->credits_outgoing == 0u) return false;
2656             return hci_can_send_acl_packet_now(channel->con_handle);
2657 #endif
2658 #endif
2659 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2660         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
2661             if (channel->state != L2CAP_STATE_OPEN) return false;
2662             if (channel->send_sdu_buffer == NULL) return false;
2663             if (channel->credits_outgoing == 0u) return false;
2664             return hci_can_send_acl_packet_now(channel->con_handle);
2665 #endif
2666         default:
2667             return false;
2668     }
2669 }
2670 
2671 static void l2cap_channel_trigger_send(l2cap_channel_t * channel){
2672     switch (channel->channel_type){
2673 #ifdef ENABLE_CLASSIC
2674         case L2CAP_CHANNEL_TYPE_CLASSIC:
2675 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2676             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2677                 l2cap_ertm_channel_send_information_frame(channel);
2678                 return;
2679             }
2680 #endif
2681             channel->waiting_for_can_send_now = 0;
2682             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2683             break;
2684         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2685         case L2CAP_CHANNEL_TYPE_FIXED_CLASSIC:
2686             channel->waiting_for_can_send_now = 0;
2687             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2688             break;
2689 #endif
2690 #ifdef ENABLE_BLE
2691         case L2CAP_CHANNEL_TYPE_FIXED_LE:
2692             channel->waiting_for_can_send_now = 0;
2693             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2694             break;
2695 #endif
2696 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2697         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
2698             l2cap_credit_based_send_pdu(channel);
2699             break;
2700 #endif
2701 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2702         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
2703             l2cap_credit_based_send_pdu(channel);
2704             break;
2705 #endif
2706         default:
2707             btstack_unreachable();
2708             break;
2709     }
2710 }
2711 
2712 static void l2cap_notify_channel_can_send(void){
2713     bool done = false;
2714     while (!done){
2715         done = true;
2716         btstack_linked_list_iterator_t it;
2717         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2718         while (btstack_linked_list_iterator_has_next(&it)){
2719             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2720             bool ready = l2cap_channel_ready_to_send(channel);
2721             if (!ready) continue;
2722 
2723             // requeue channel for fairness
2724             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2725             btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2726 
2727             // trigger sending
2728             l2cap_channel_trigger_send(channel);
2729 
2730             // exit inner loop as we just broke the iterator, but try again
2731             done = false;
2732             break;
2733         }
2734     }
2735 }
2736 
2737 #ifdef L2CAP_USES_CHANNELS
2738 
2739 uint8_t l2cap_disconnect(uint16_t local_cid){
2740     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2741     if (!channel) {
2742         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2743     }
2744     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2745     l2cap_run();
2746     return ERROR_CODE_SUCCESS;
2747 }
2748 
2749 static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){
2750     // open cannot fail for for incoming connections
2751     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0;
2752 
2753     // check state
2754     switch (channel->state){
2755         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2756         case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2757         case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES:
2758         case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2759         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
2760         case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES:
2761         case L2CAP_STATE_WAIT_CONNECT_RSP:
2762         case L2CAP_STATE_CONFIG:
2763         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
2764         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
2765         case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE:
2766         case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD:
2767             return 1;
2768 
2769         case L2CAP_STATE_OPEN:
2770         case L2CAP_STATE_CLOSED:
2771         case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES:
2772         case L2CAP_STATE_WAIT_DISCONNECT:
2773         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY:
2774         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
2775         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
2776         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2777         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
2778         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
2779         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
2780         case L2CAP_STATE_INVALID:
2781         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2782             return 0;
2783 
2784         default:
2785             // get a "warning" about new states
2786             btstack_assert(false);
2787             return 0;
2788     }
2789 }
2790 #endif
2791 
2792 #ifdef ENABLE_CLASSIC
2793 static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){
2794     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2795         l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2796     } else {
2797         l2cap_handle_channel_closed(channel);
2798     }
2799     l2cap_free_channel_entry(channel);
2800 }
2801 #endif
2802 
2803 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2804 static void l2cap_handle_hci_le_disconnect_event(l2cap_channel_t * channel){
2805     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2806         l2cap_cbm_emit_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2807     } else {
2808         l2cap_emit_channel_closed(channel);
2809     }
2810     l2cap_free_channel_entry(channel);
2811 }
2812 #endif
2813 
2814 #ifdef ENABLE_CLASSIC
2815 static void l2cap_check_classic_timeout(hci_con_handle_t handle){
2816     if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) {
2817         return;
2818     }
2819     if (hci_authentication_active_for_handle(handle)) {
2820         return;
2821     }
2822     bool hci_con_used = false;
2823     btstack_linked_list_iterator_t it;
2824     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2825     while (btstack_linked_list_iterator_has_next(&it)){
2826         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2827         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2828         if (channel->con_handle != handle) continue;
2829         hci_con_used = true;
2830         break;
2831     }
2832     if (hci_con_used) {
2833         return;
2834     }
2835     if (!hci_can_send_command_packet_now()) {
2836         return;
2837     }
2838     hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
2839 }
2840 
2841 static void l2cap_handle_features_complete(hci_con_handle_t handle){
2842     if (hci_remote_features_available(handle) == false){
2843         return;
2844     }
2845     btstack_linked_list_iterator_t it;
2846     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2847     while (btstack_linked_list_iterator_has_next(&it)){
2848         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2849         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2850         if (channel->con_handle != handle) continue;
2851         log_info("remote supported features, channel %p, cid %04x - state %u", channel, channel->local_cid, channel->state);
2852         l2cap_handle_remote_supported_features_received(channel);
2853     }
2854 }
2855 
2856 static void l2cap_handle_security_level_incoming_sufficient(l2cap_channel_t * channel){
2857     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2858     l2cap_emit_incoming_connection(channel);
2859 }
2860 
2861 static void l2cap_handle_security_level(hci_con_handle_t handle, gap_security_level_t actual_level){
2862     log_info("security level update for handle 0x%04x", handle);
2863 
2864     // trigger l2cap information requests
2865     if (actual_level > LEVEL_0){
2866         hci_connection_t * hci_connection = hci_connection_for_handle(handle);
2867         btstack_assert(hci_connection != NULL);
2868         if (hci_connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
2869             hci_connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2870         }
2871     }
2872 
2873     bool done = false;
2874     while (!done){
2875         done = true;
2876         btstack_linked_list_iterator_t it;
2877         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2878         while (btstack_linked_list_iterator_has_next(&it)){
2879             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2880             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2881             if (channel->con_handle != handle) continue;
2882 
2883             gap_security_level_t required_level = channel->required_security_level;
2884 
2885             log_info("channel %p, cid %04x - state %u: actual %u >= required %u?", channel, channel->local_cid, channel->state, actual_level, required_level);
2886 
2887             switch (channel->state){
2888                 case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2889                     if (actual_level >= required_level){
2890                         l2cap_handle_security_level_incoming_sufficient(channel);
2891                     } else {
2892                         channel->reason = L2CAP_CONNECTION_RESULT_SECURITY_BLOCK;
2893                         channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2894                     }
2895                     break;
2896 
2897                 case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2898                     if (actual_level >= required_level){
2899                         l2cap_ready_to_connect(channel);
2900                     } else {
2901                         // security level insufficient, report error and free channel
2902                         l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY);
2903                         btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t  *) channel);
2904                         l2cap_free_channel_entry(channel);
2905                     }
2906                     break;
2907 
2908                 default:
2909                     break;
2910             }
2911         }
2912     }
2913 }
2914 #endif
2915 
2916 #ifdef L2CAP_USES_CHANNELS
2917 static void l2cap_handle_disconnection_complete(hci_con_handle_t handle){
2918     // collect channels to close
2919     btstack_linked_list_t channels_to_close = NULL;
2920     btstack_linked_list_iterator_t it;
2921     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2922     while (btstack_linked_list_iterator_has_next(&it)) {
2923         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2924         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2925         if (channel->con_handle != handle) continue;
2926         btstack_linked_list_iterator_remove(&it);
2927         btstack_linked_list_add(&channels_to_close, (btstack_linked_item_t *) channel);
2928     }
2929     // send l2cap open failed or closed events for all channels on this handle and free them
2930     btstack_linked_list_iterator_init(&it, &channels_to_close);
2931     while (btstack_linked_list_iterator_has_next(&it)) {
2932         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2933         btstack_linked_list_iterator_remove(&it);
2934         switch(channel->channel_type){
2935 #ifdef ENABLE_CLASSIC
2936             case L2CAP_CHANNEL_TYPE_CLASSIC:
2937                 l2cap_handle_hci_disconnect_event(channel);
2938                 break;
2939 #endif
2940 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2941             case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
2942                 l2cap_handle_hci_le_disconnect_event(channel);
2943                 break;
2944 #endif
2945 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2946             case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
2947                 switch (channel->state) {
2948                     case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST:
2949                     case L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE:
2950                         // emit open failed if disconnected before connection complete
2951                         l2cap_ecbm_emit_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2952                         break;
2953                     case L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST:
2954                     case L2CAP_STATE_WAIT_ENHANCED_RENEGOTIATION_RESPONSE:
2955                         // emit reconfigure failure - result = 0xffff
2956                         l2cap_ecbm_emit_reconfigure_complete(channel, 0xffff);
2957                         break;
2958                     default:
2959                         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
2960                         break;
2961                 }
2962                 l2cap_free_channel_entry(channel);
2963                 break;
2964 #endif
2965             default:
2966                 break;
2967         }
2968     }
2969 }
2970 #endif
2971 
2972 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
2973 
2974     UNUSED(packet_type); // ok: registered with hci_event_callback_registration
2975     UNUSED(cid);         // ok: there is no channel
2976     UNUSED(size);        // ok: fixed format events read from HCI buffer
2977 
2978 #ifdef ENABLE_CLASSIC
2979     bd_addr_t address;
2980     gap_security_level_t security_level;
2981 #endif
2982 #ifdef L2CAP_USES_CHANNELS
2983     hci_con_handle_t handle;
2984 #endif
2985 
2986     switch(hci_event_packet_get_type(packet)){
2987 
2988         // Notify channel packet handler if they can send now
2989         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2990         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
2991         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
2992 #ifdef ENABLE_TESTING_SUPPORT
2993         case HCI_EVENT_NOP:
2994 #endif
2995             l2cap_call_notify_channel_in_run = true;
2996             break;
2997 
2998         case HCI_EVENT_COMMAND_STATUS:
2999 #ifdef ENABLE_CLASSIC
3000             // check command status for create connection for errors
3001             if (hci_event_command_status_get_command_opcode(packet) == HCI_OPCODE_HCI_CREATE_CONNECTION){
3002                 // cache outgoing address and reset
3003                 (void)memcpy(address, l2cap_outgoing_classic_addr, 6);
3004                 memset(l2cap_outgoing_classic_addr, 0, 6);
3005                 // error => outgoing connection failed
3006                 uint8_t status = hci_event_command_status_get_status(packet);
3007                 if (status){
3008                     l2cap_handle_connection_failed_for_addr(address, status);
3009                 }
3010             }
3011 #endif
3012             l2cap_run();    // try sending signaling packets first
3013             break;
3014 
3015 #ifdef ENABLE_CLASSIC
3016         // handle connection complete events
3017         case HCI_EVENT_CONNECTION_COMPLETE:
3018             reverse_bd_addr(&packet[5], address);
3019             if (packet[2] == 0){
3020                 handle = little_endian_read_16(packet, 3);
3021                 l2cap_handle_connection_success_for_addr(address, handle);
3022             } else {
3023                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
3024             }
3025             break;
3026 
3027         // handle successful create connection cancel command
3028         case HCI_EVENT_COMMAND_COMPLETE:
3029             if (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_CREATE_CONNECTION_CANCEL) {
3030                 if (packet[5] == 0){
3031                     reverse_bd_addr(&packet[6], address);
3032                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
3033                     l2cap_handle_connection_failed_for_addr(address, 0x16);
3034                 }
3035             }
3036             l2cap_run();    // try sending signaling packets first
3037             break;
3038 #endif
3039 
3040 #ifdef L2CAP_USES_CHANNELS
3041         // handle disconnection complete events
3042         case HCI_EVENT_DISCONNECTION_COMPLETE:
3043             handle = little_endian_read_16(packet, 3);
3044             l2cap_handle_disconnection_complete(handle);
3045             break;
3046 #endif
3047 
3048         // HCI Connection Timeouts
3049 #ifdef ENABLE_CLASSIC
3050         case L2CAP_EVENT_TIMEOUT_CHECK:
3051             handle = little_endian_read_16(packet, 2);
3052             l2cap_check_classic_timeout(handle);
3053             break;
3054 
3055         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
3056         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
3057             handle = little_endian_read_16(packet, 3);
3058             l2cap_handle_features_complete(handle);
3059             break;
3060 
3061         case GAP_EVENT_SECURITY_LEVEL:
3062             handle = little_endian_read_16(packet, 2);
3063             security_level = (gap_security_level_t) packet[4];
3064             l2cap_handle_security_level(handle, security_level);
3065             break;
3066 #endif
3067         default:
3068             break;
3069     }
3070 
3071     l2cap_run();
3072 }
3073 
3074 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t cid, uint16_t data){
3075     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indicates the connection was refused."
3076     if (l2cap_signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
3077         l2cap_signaling_responses[l2cap_signaling_responses_pending].handle = handle;
3078         l2cap_signaling_responses[l2cap_signaling_responses_pending].code = code;
3079         l2cap_signaling_responses[l2cap_signaling_responses_pending].sig_id = sig_id;
3080         l2cap_signaling_responses[l2cap_signaling_responses_pending].cid = cid;
3081         l2cap_signaling_responses[l2cap_signaling_responses_pending].data = data;
3082         l2cap_signaling_responses_pending++;
3083         l2cap_run();
3084     }
3085 }
3086 
3087 #ifdef ENABLE_CLASSIC
3088 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint8_t identifier){
3089     switch (channel->state){
3090         case L2CAP_STATE_CONFIG:
3091         case L2CAP_STATE_OPEN:
3092         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
3093         case L2CAP_STATE_WAIT_DISCONNECT:
3094             break;
3095         default:
3096             // ignore in other states
3097             return;
3098     }
3099 
3100     channel->remote_sig_id = identifier;
3101     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
3102     l2cap_run();
3103 }
3104 
3105 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
3106 
3107     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
3108     l2cap_service_t *service = l2cap_get_service(psm);
3109     if (!service) {
3110         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CONNECTION_RESULT_PSM_NOT_SUPPORTED);
3111         return;
3112     }
3113 
3114     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
3115     if (!hci_connection) {
3116         //
3117         log_error("no hci_connection for handle %u", handle);
3118         return;
3119     }
3120 
3121     // if SC only mode is active and service requires encryption, reject connection if SC not active or use security level
3122     gap_security_level_t required_level = service->required_security_level;
3123     if (gap_get_secure_connections_only_mode() && (required_level != LEVEL_0)){
3124         if (gap_secure_connection(handle)){
3125             required_level = LEVEL_4;
3126         } else {
3127             l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CONNECTION_RESULT_SECURITY_BLOCK);
3128             return;
3129         }
3130     }
3131 
3132     // alloc structure
3133     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, hci_connection->address, BD_ADDR_TYPE_ACL,
3134     psm, service->mtu, required_level);
3135     if (!channel){
3136         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE);
3137         return;
3138     }
3139 
3140     channel->con_handle = handle;
3141     channel->remote_cid = source_cid;
3142     channel->remote_sig_id = sig_id;
3143 
3144     // limit local mtu to max acl packet length - l2cap header
3145     if (channel->local_mtu > l2cap_max_mtu()) {
3146         channel->local_mtu = l2cap_max_mtu();
3147     }
3148 
3149     // set initial state
3150     channel->state =     L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
3151     channel->state_var = L2CAP_CHANNEL_STATE_VAR_INCOMING;
3152 
3153     // add to connections list
3154     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
3155 
3156     //
3157     if (required_level > LEVEL_0){
3158         // send conn resp pending if remote supported features have not been received yet
3159         if (hci_remote_features_available(handle)) {
3160             l2cap_handle_remote_supported_features_received(channel);
3161         } else {
3162             channel->state_var |= L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND;
3163             hci_remote_features_query(handle);
3164         }
3165     } else {
3166         l2cap_handle_security_level_incoming_sufficient(channel);
3167     }
3168 }
3169 
3170 void l2cap_accept_connection(uint16_t local_cid){
3171     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
3172     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3173     if (!channel) {
3174         log_error("accept called but local_cid 0x%x not found", local_cid);
3175         return;
3176     }
3177 
3178 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3179     // configure L2CAP Basic mode
3180     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
3181 #endif
3182 
3183     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
3184 
3185     // process
3186     l2cap_run();
3187 }
3188 
3189 void l2cap_decline_connection(uint16_t local_cid){
3190     log_info("decline local_cid 0x%x", local_cid);
3191     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
3192     if (!channel) {
3193         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
3194         return;
3195     }
3196     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
3197     channel->reason = L2CAP_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE;
3198     l2cap_run();
3199 }
3200 
3201 // @pre command len is valid, see check in l2cap_signaling_handler_channel
3202 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
3203 
3204 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3205     uint8_t use_fcs = 1;
3206 #endif
3207 
3208     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
3209 
3210     uint16_t flags = little_endian_read_16(command, 6);
3211     if (flags & 1) {
3212         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
3213     }
3214 
3215     // accept the other's configuration options
3216     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3217     uint16_t pos     = 8;
3218     while (pos < end_pos){
3219         uint8_t option_hint = command[pos] >> 7;
3220         uint8_t option_type = command[pos] & 0x7f;
3221         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
3222         pos++;
3223         uint8_t length = command[pos++];
3224         // MTU { type(8): 1, len(8):2, MTU(16) }
3225         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) && (length == 2)){
3226             channel->remote_mtu = little_endian_read_16(command, pos);
3227             log_info("Remote MTU %u", channel->remote_mtu);
3228             if (channel->remote_mtu > l2cap_max_mtu()){
3229                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
3230                 channel->remote_mtu = l2cap_max_mtu();
3231             }
3232             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
3233         }
3234         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
3235         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT) && (length == 2)){
3236             channel->flush_timeout = little_endian_read_16(command, pos);
3237             log_info("Flush timeout: %u ms", channel->flush_timeout);
3238         }
3239 
3240 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3241         // Retransmission and Flow Control Option
3242         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
3243             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
3244             switch(channel->mode){
3245                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
3246                     // Store remote config
3247                     channel->remote_tx_window_size = command[pos+1];
3248                     channel->remote_max_transmit   = command[pos+2];
3249                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
3250                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
3251                     {
3252                         uint16_t remote_mps = little_endian_read_16(command, pos + 7);
3253                         // optimize our tx buffer configuration based on actual remote mps if remote mps is smaller than planned
3254                         if (remote_mps < channel->remote_mps){
3255                             // get current tx storage
3256                             uint16_t num_bytes_per_tx_buffer_before = sizeof(l2cap_ertm_tx_packet_state_t) + channel->remote_mps;
3257                             uint16_t tx_storage = channel->num_tx_buffers * num_bytes_per_tx_buffer_before;
3258 
3259                             channel->remote_mps = remote_mps;
3260                             uint16_t num_bytes_per_tx_buffer_now = sizeof(l2cap_ertm_tx_packet_state_t) + channel->remote_mps;
3261                             channel->num_tx_buffers = tx_storage / num_bytes_per_tx_buffer_now;
3262                             uint32_t total_storage = (sizeof(l2cap_ertm_rx_packet_state_t) + channel->local_mps) * channel->num_rx_buffers + tx_storage + channel->local_mtu;
3263                             l2cap_ertm_setup_buffers(channel, (uint8_t *) channel->rx_packets_state, total_storage);
3264                         }
3265                         // limit remote mtu by our tx buffers. Include 2 bytes SDU Length
3266                         uint16_t effective_mtu = channel->remote_mps * channel->num_tx_buffers - 2;
3267                         channel->remote_mtu    = btstack_min( effective_mtu, channel->remote_mtu);
3268                     }
3269                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
3270                         channel->remote_tx_window_size,
3271                         channel->remote_max_transmit,
3272                         channel->remote_retransmission_timeout_ms,
3273                         channel->remote_monitor_timeout_ms,
3274                         channel->remote_mps);
3275                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
3276                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3277                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3278                     } else {
3279                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
3280                     }
3281                     break;
3282                 case L2CAP_CHANNEL_MODE_BASIC:
3283                     switch (mode){
3284                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
3285                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
3286                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
3287                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3288                             }
3289                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
3290                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
3291                             break;
3292                         default: // case L2CAP_CHANNEL_MODE_BASIC:
3293                             // TODO store and evaluate configuration
3294                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
3295                             break;
3296                     }
3297                     break;
3298                 default:
3299                     break;
3300             }
3301         }
3302         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
3303             use_fcs = command[pos];
3304         }
3305 #endif
3306         // check for unknown options
3307         if ((option_hint == 0) && ((option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) || (option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE))){
3308             log_info("l2cap cid %u, unknown option 0x%02x", channel->local_cid, option_type);
3309             channel->unknown_option = option_type;
3310             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
3311         }
3312         pos += length;
3313     }
3314 
3315 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3316         // "FCS" has precedence over "No FCS"
3317         uint8_t update = channel->fcs_option || use_fcs;
3318         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
3319         channel->fcs_option = update;
3320         // If ERTM mandatory, but remote didn't send Retransmission and Flowcontrol options -> disconnect
3321         if (((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM) == 0) & (channel->ertm_mandatory)){
3322             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3323         }
3324 #endif
3325 }
3326 
3327 // @pre command len is valid, see check in l2cap_signaling_handler_channel
3328 static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint16_t result, uint8_t *command){
3329     log_info("l2cap_signaling_handle_configure_response");
3330 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3331     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3332     uint16_t pos     = 10;
3333     while (pos < end_pos){
3334         uint8_t option_hint = command[pos] >> 7;
3335         uint8_t option_type = command[pos] & 0x7f;
3336         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
3337         pos++;
3338         uint8_t length = command[pos++];
3339 
3340         // Retransmission and Flow Control Option
3341         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
3342             switch (channel->mode){
3343                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
3344                     if (channel->ertm_mandatory){
3345                         // ??
3346                     } else {
3347                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
3348                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
3349                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3350                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3351                         }
3352                     }
3353                     break;
3354                 case L2CAP_CHANNEL_MODE_BASIC:
3355                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
3356                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
3357                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3358                     }
3359                     break;
3360                 default:
3361                     break;
3362             }
3363         }
3364 
3365         // check for unknown options
3366         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
3367             log_info("l2cap cid %u, unknown option 0x%02x", channel->local_cid, option_type);
3368             channel->unknown_option = option_type;
3369             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
3370         }
3371 
3372         pos += length;
3373     }
3374 #else
3375     UNUSED(channel);  // ok: no code
3376     UNUSED(result);   // ok: no code
3377     UNUSED(command);  // ok: no code
3378 #endif
3379 }
3380 
3381 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
3382     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
3383     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
3384     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
3385     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
3386     if (channel->state == L2CAP_STATE_OPEN) return 0;
3387     return 1;
3388 }
3389 
3390 
3391 // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
3392 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
3393 
3394     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3395     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
3396     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3397     uint16_t result = 0;
3398 
3399     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
3400 
3401     // handle DISCONNECT REQUESTS seperately
3402     if (code == DISCONNECTION_REQUEST){
3403         l2cap_handle_disconnect_request(channel, identifier);
3404         return;
3405     }
3406 
3407     // @STATEMACHINE(l2cap)
3408     switch (channel->state) {
3409 
3410         case L2CAP_STATE_WAIT_CONNECT_RSP:
3411             switch (code){
3412                 case CONNECTION_RESPONSE:
3413                     if (cmd_len < 8){
3414                         // command imcomplete
3415                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3416                         break;
3417                     }
3418                     l2cap_stop_rtx(channel);
3419                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3420                     switch (result) {
3421                         case 0:
3422                             // successful connection
3423                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3424                             channel->state = L2CAP_STATE_CONFIG;
3425                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
3426                             break;
3427                         case 1:
3428                             // connection pending. get some coffee, but start the ERTX
3429                             l2cap_start_ertx(channel);
3430                             break;
3431                         default:
3432                             // channel closed
3433                             channel->state = L2CAP_STATE_CLOSED;
3434                             // map l2cap connection response result to BTstack status enumeration
3435                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
3436 
3437                             // drop link key if security block
3438                             if ((L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result) == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
3439                                 gap_drop_link_key_for_bd_addr(channel->address);
3440                             }
3441 
3442                             // discard channel
3443                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3444                             l2cap_free_channel_entry(channel);
3445                             break;
3446                     }
3447                     break;
3448 
3449                 default:
3450                     //@TODO: implement other signaling packets
3451                     break;
3452             }
3453             break;
3454 
3455         case L2CAP_STATE_CONFIG:
3456             switch (code) {
3457                 case CONFIGURE_REQUEST:
3458                     if (cmd_len < 4){
3459                         // command incomplete
3460                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3461                         break;
3462                     }
3463                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
3464                     l2cap_signaling_handle_configure_request(channel, command);
3465                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
3466                         // only done if continuation not set
3467                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
3468                     }
3469                     break;
3470                 case CONFIGURE_RESPONSE:
3471                     if (cmd_len < 6){
3472                         // command incomplete
3473                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3474                         break;
3475                     }
3476                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3477                     l2cap_stop_rtx(channel);
3478                     l2cap_signaling_handle_configure_response(channel, result, command);
3479                     switch (result){
3480                         case 0: // success
3481                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
3482                             break;
3483                         case 4: // pending
3484                             l2cap_start_ertx(channel);
3485                             break;
3486                         default:
3487 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3488                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
3489                                 // remote does not offer ertm but it's required
3490                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3491                                 break;
3492                             }
3493 #endif
3494                             // retry on negative result
3495                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
3496                             break;
3497                     }
3498                     break;
3499                 default:
3500                     break;
3501             }
3502             if (l2cap_channel_ready_for_open(channel)){
3503 
3504 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3505                 // assert that packet can be stored in fragment buffers in ertm
3506                 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3507                     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
3508                     uint16_t usable_mtu = channel->num_tx_buffers == 1 ? effective_mps : channel->num_tx_buffers * effective_mps - 2;
3509                     if (usable_mtu < channel->remote_mtu){
3510                         log_info("Remote MTU %u > max storable ERTM packet, only using MTU = %u", channel->remote_mtu, usable_mtu);
3511                         channel->remote_mtu = usable_mtu;
3512                     }
3513                 }
3514 #endif
3515                 // for open:
3516                 channel->state = L2CAP_STATE_OPEN;
3517                 l2cap_emit_channel_opened(channel, 0);
3518             }
3519             break;
3520 
3521         case L2CAP_STATE_WAIT_DISCONNECT:
3522             switch (code) {
3523                 case DISCONNECTION_RESPONSE:
3524                     l2cap_finalize_channel_close(channel);
3525                     break;
3526                 default:
3527                     //@TODO: implement other signaling packets
3528                     break;
3529             }
3530             break;
3531 
3532         case L2CAP_STATE_CLOSED:
3533             // @TODO handle incoming requests
3534             break;
3535 
3536         case L2CAP_STATE_OPEN:
3537             //@TODO: implement other signaling packets, e.g. re-configure
3538             break;
3539         default:
3540             break;
3541     }
3542     // log_info("new state %u", channel->state);
3543 }
3544 
3545 #ifdef ENABLE_CLASSIC
3546 static void l2cap_handle_information_request_complete(hci_connection_t * connection){
3547 
3548     connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
3549 
3550     // emit event
3551     uint8_t event[8];
3552     event[0] = L2CAP_EVENT_INFORMATION_RESPONSE;
3553     event[1] = sizeof(event) - 2;
3554     little_endian_store_16(event, 2, connection->con_handle);
3555     little_endian_store_16(event, 4, connection->l2cap_state.extended_feature_mask);
3556     little_endian_store_16(event, 6, connection->l2cap_state.fixed_channels_supported);
3557     l2cap_emit_event(event, sizeof(event));
3558 
3559     // trigger connection request
3560     btstack_linked_list_iterator_t it;
3561     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3562     while (btstack_linked_list_iterator_has_next(&it)){
3563         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3564         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3565         if (channel->con_handle != connection->con_handle) continue;
3566 
3567         // incoming connection: information request was triggered after user has accepted connection,
3568         // now: verify channel configuration, esp. if ertm will be mandatory
3569         if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
3570             // default: continue
3571             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
3572 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3573             if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
3574                 // ERTM not possible, select basic mode and release buffer
3575                 channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3576                 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3577 
3578                 // bail if ERTM is mandatory
3579                 if (channel->ertm_mandatory){
3580                     // We chose 'no resources available' for "ERTM mandatory but you don't even know ERTM exists"
3581                     log_info("ERTM mandatory -> reject connection");
3582                     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
3583                     channel->reason = L2CAP_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE;
3584                 }  else {
3585                     log_info("ERTM not supported by remote -> use Basic mode");
3586                 }
3587             }
3588 #endif
3589             continue;
3590         }
3591 
3592         // outgoing connection: information request is triggered before connection request
3593         if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
3594 
3595 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3596             // if ERTM was requested, but is not listed in extended feature mask:
3597             if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
3598 
3599                 if (channel->ertm_mandatory){
3600                     // bail if ERTM is mandatory
3601                     channel->state = L2CAP_STATE_CLOSED;
3602                     // map l2cap connection response result to BTstack status enumeration
3603                     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
3604                     // discard channel
3605                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3606                     l2cap_free_channel_entry(channel);
3607                     continue;
3608 
3609                 } else {
3610                     // fallback to Basic mode
3611                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3612                     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3613                 }
3614             }
3615 #endif
3616 
3617             // respond to connection request
3618             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
3619             continue;
3620         }
3621     }
3622 }
3623 #endif
3624 
3625 // @pre command len is valid, see check in l2cap_acl_classic_handler
3626 static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
3627 
3628     hci_connection_t * connection;
3629     btstack_linked_list_iterator_t it;
3630 
3631     // get code, signal identifier and command len
3632     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3633     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
3634     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3635 
3636     // general commands without an assigned channel
3637     switch(code) {
3638 
3639         case CONNECTION_REQUEST:
3640             if (cmd_len == 4){
3641                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3642                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3643                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
3644             } else {
3645                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3646             }
3647             return;
3648 
3649         case ECHO_REQUEST:
3650             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
3651             return;
3652 
3653         case INFORMATION_REQUEST:
3654             if (cmd_len == 2) {
3655                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3656                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
3657                 return;
3658             }
3659             break;
3660 
3661         case INFORMATION_RESPONSE:
3662             connection = hci_connection_for_handle(handle);
3663             if (!connection) return;
3664             switch (connection->l2cap_state.information_state){
3665                 case L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE:
3666                     // get extended features from response if valid
3667                     if (cmd_len >= 6) {
3668                         uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3669                         uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3670                         if (result == 0 && info_type == L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) {
3671                             connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3672                         }
3673                         log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
3674                         if ((connection->l2cap_state.extended_feature_mask & 0x80) != 0){
3675                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_FIXED_CHANNELS_REQUEST;
3676                         } else {
3677                             // information request complete
3678                             l2cap_handle_information_request_complete(connection);
3679                         }
3680                     }
3681                     break;
3682                 case L2CAP_INFORMATION_STATE_W4_FIXED_CHANNELS_RESPONSE:
3683                     if (cmd_len >= 12) {
3684                         uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3685                         uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3686                         if (result == 0 && info_type == L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED) {
3687                             connection->l2cap_state.fixed_channels_supported = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3688                         }
3689                         log_info("fixed channels mask 0x%02x", connection->l2cap_state.fixed_channels_supported);
3690                         // information request complete
3691                         l2cap_handle_information_request_complete(connection);
3692                     }
3693                     break;
3694                 default:
3695                     break;
3696             }
3697             return;
3698 
3699 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
3700         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
3701         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
3702         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
3703         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
3704             l2cap_ecbm_signaling_handler_dispatch(handle, L2CAP_CID_SIGNALING, command, sig_id);
3705             return;
3706         case L2CAP_FLOW_CONTROL_CREDIT_INDICATION:
3707             // return if valid
3708             if (l2cap_credit_based_handle_credit_indication(handle, command, cmd_len)) return;
3709             break;
3710 
3711         case COMMAND_REJECT:
3712             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3713             while (btstack_linked_list_iterator_has_next(&it)) {
3714                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3715                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3716                 if (channel->con_handle != handle) continue;
3717                 if (channel->local_sig_id != sig_id) continue;
3718                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE) continue;
3719 
3720                 // open failed
3721                 channel->state = L2CAP_STATE_CLOSED;
3722                 l2cap_ecbm_emit_channel_opened(channel,
3723                                                ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES);
3724                 // drop failed channel
3725                 btstack_linked_list_iterator_remove(&it);
3726                 l2cap_free_channel_entry(channel);
3727             }
3728             break;
3729 #endif
3730 
3731         default:
3732             break;
3733     }
3734 
3735     // Get potential destination CID
3736     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3737 
3738     // Find channel for this sig_id and connection handle
3739     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3740     while (btstack_linked_list_iterator_has_next(&it)){
3741         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3742         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3743         if (channel->con_handle != handle) continue;
3744         if (code & 1) {
3745             // match odd commands (responses) by previous signaling identifier
3746             if (channel->local_sig_id == sig_id) {
3747                 l2cap_signaling_handler_channel(channel, command);
3748                 return;
3749             }
3750         } else {
3751             // match even commands (requests) by local channel id
3752             if (channel->local_cid == dest_cid) {
3753                 l2cap_signaling_handler_channel(channel, command);
3754                 return;
3755             }
3756         }
3757     }
3758 
3759     // send command reject
3760     l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3761 }
3762 #endif
3763 
3764 #ifdef L2CAP_USES_CHANNELS
3765 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3766     btstack_linked_list_iterator_t it;
3767     btstack_linked_list_iterator_init(&it, services);
3768     while (btstack_linked_list_iterator_has_next(&it)){
3769         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
3770         if ( service->psm == psm){
3771             return service;
3772         };
3773     }
3774     return NULL;
3775 }
3776 #endif
3777 
3778 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
3779 
3780 static uint8_t l2cap_ecbm_setup_channels(btstack_linked_list_t * channels,
3781                                          btstack_packet_handler_t packet_handler, uint8_t num_channels,
3782                                          hci_connection_t * connection, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
3783     uint8_t i;
3784     uint8_t status = ERROR_CODE_SUCCESS;
3785     for (i=0;i<num_channels;i++){
3786         l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_ECBM, connection->address, connection->address_type, psm, mtu, security_level);
3787         if (!channel) {
3788             status = BTSTACK_MEMORY_ALLOC_FAILED;
3789             break;
3790         }
3791         channel->con_handle = connection->con_handle;
3792         btstack_linked_list_add_tail(channels, (btstack_linked_item_t *) channel);
3793     }
3794 
3795     // free channels if not all allocated
3796     if (status != ERROR_CODE_SUCCESS){
3797         while (true) {
3798             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_pop(channels);
3799             if (channel == NULL) break;
3800             l2cap_free_channel_entry(channel);
3801         }
3802     }
3803 
3804     return status;
3805 }
3806 
3807 static inline l2cap_service_t * l2cap_ecbm_get_service(uint16_t spsm){
3808     return l2cap_get_service_internal(&l2cap_enhanced_services, spsm);
3809 }
3810 
3811 static inline uint8_t l2cap_ecbm_status_for_result(uint16_t result) {
3812     switch (result) {
3813         case L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS:
3814             return ERROR_CODE_SUCCESS;
3815         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_SPSM_NOT_SUPPORTED:
3816             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_PSM;
3817         case L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INSUFFICIENT_RESOURCES_AVAILABLE:
3818             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_RESOURCES;
3819         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHENTICATION:
3820         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHORIZATION:
3821         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_ENCYRPTION_KEY_SIZE_TOO_SHORT:
3822         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_ENCRYPTION:
3823             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY;
3824         default:
3825             // invalid Source CID, Source CID already allocated, unacceptable parameters
3826             return L2CAP_CONNECTION_RESPONSE_UNKNOWN_ERROR;
3827     }
3828 }
3829 
3830 static void
3831 l2cap_ecbm_emit_incoming_connection(l2cap_channel_t *channel, uint8_t num_channels) {
3832     uint8_t event[16];
3833     event[0] = L2CAP_EVENT_ECBM_INCOMING_CONNECTION;
3834     event[1] = sizeof(event) - 2;
3835     event[2] = channel->address_type;
3836     reverse_bd_addr(channel->address, &event[3]);
3837     little_endian_store_16(event, 9, channel->con_handle);
3838     little_endian_store_16(event, 11, channel->psm);
3839     event[13] = num_channels;
3840     little_endian_store_16(event, 14, channel->local_cid);
3841     hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
3842     (*channel->packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
3843 }
3844 
3845 static uint8_t
3846 l2cap_ecbm_security_status_for_connection_request(hci_con_handle_t handle, gap_security_level_t required_security_level,
3847                                                   bool requires_authorization) {
3848     // check security in increasing error priority
3849     uint8_t security_status = L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS;
3850 
3851     // security: check encryption
3852     if (required_security_level >= LEVEL_2) {
3853         if (gap_encryption_key_size(handle) < 16) {
3854             security_status = L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_ENCYRPTION_KEY_SIZE_TOO_SHORT;
3855         }
3856         if (gap_encryption_key_size(handle) == 0){
3857             security_status = L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_ENCRYPTION;
3858         }
3859     }
3860 
3861     // security: check authentication
3862     if (required_security_level >= LEVEL_3) {
3863         if (!gap_authenticated(handle)) {
3864             security_status = requires_authorization ?
3865                     L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHORIZATION :
3866                     L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHENTICATION;
3867         }
3868     }
3869     return security_status;
3870 }
3871 
3872 static void l2cap_ecbm_handle_security_level_incoming(l2cap_channel_t * channel){
3873     // count number of l2cap_channels in state L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE with same remote_sig_id
3874     uint8_t sig_id = channel->remote_sig_id;
3875     hci_con_handle_t con_handle = channel->con_handle;
3876 
3877     uint8_t security_status = l2cap_ecbm_security_status_for_connection_request(channel->con_handle,
3878                                                                                 channel->required_security_level,
3879                                                                                 false);
3880     bool security_sufficient = security_status == L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS;
3881 
3882     uint8_t num_channels = 0;
3883     btstack_linked_list_iterator_t it;
3884     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3885     while (btstack_linked_list_iterator_has_next(&it)) {
3886         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3887         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3888         if (channel->con_handle != con_handle) continue;
3889         if (channel->remote_sig_id != sig_id) continue;
3890         if (channel->state != L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE) continue;
3891         num_channels++;
3892 
3893         if (security_sufficient){
3894             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
3895         } else {
3896             btstack_linked_list_iterator_remove(&it);
3897             btstack_memory_l2cap_channel_free(channel);
3898         }
3899     }
3900 
3901     if (security_sufficient){
3902         l2cap_ecbm_emit_incoming_connection(channel, num_channels);
3903     } else {
3904         // combine signaling cid and number channels for l2cap_register_signaling_response
3905         uint16_t signaling_cid = L2CAP_CID_SIGNALING;
3906         uint16_t num_channels_and_signaling_cid = (num_channels << 8) | signaling_cid;
3907         l2cap_register_signaling_response(con_handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3908                                           num_channels_and_signaling_cid, security_status);
3909     }
3910 }
3911 
3912 void l2cap_ecbm_trigger_pending_connection_responses(hci_con_handle_t con_handle){
3913     bool done = false;
3914     while (!done) {
3915         done = true;
3916         btstack_linked_list_iterator_t it;
3917         btstack_linked_list_iterator_init(&it, &l2cap_channels);
3918         while (btstack_linked_list_iterator_has_next(&it)) {
3919             l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3920             if (channel->channel_type != L2CAP_CHANNEL_TYPE_CHANNEL_ECBM) continue;
3921             if (channel->con_handle != con_handle) continue;
3922             if  (channel->state == L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE) {
3923                 l2cap_ecbm_handle_security_level_incoming(channel);
3924                 done = false;
3925             };
3926         }
3927     }
3928 }
3929 
3930 static int l2cap_ecbm_signaling_handler_dispatch(hci_con_handle_t handle, uint16_t signaling_cid, uint8_t *command,
3931                                                  uint8_t sig_id) {
3932 
3933     hci_connection_t *connection;
3934     btstack_linked_list_iterator_t it;
3935     l2cap_service_t *service;
3936     uint16_t spsm;
3937     uint8_t num_channels;
3938     uint16_t num_channels_and_signaling_cid;
3939     uint8_t i;
3940     uint16_t new_mtu;
3941     uint16_t new_mps;
3942     uint16_t initial_credits;
3943     uint16_t result;
3944     uint8_t status;
3945 
3946     uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3947     uint16_t len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3948     log_info("enhanced dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
3949 
3950     switch (code) {
3951         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
3952             // check size
3953             if (len < 10u) return 0u;
3954 
3955             // get hci connection, bail if not found (must not happen)
3956             connection = hci_connection_for_handle(handle);
3957             btstack_assert(connection != NULL);
3958 
3959             // get num channels to establish
3960             num_channels = (len - 8) / sizeof(uint16_t);
3961 
3962             // combine signaling cid and number channels for l2cap_register_signaling_response
3963             num_channels_and_signaling_cid = (num_channels << 8) | signaling_cid;
3964 
3965             // check if service registered
3966             spsm = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3967             service = l2cap_ecbm_get_service(spsm);
3968 
3969             if (service) {
3970 
3971                 uint16_t remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3972                 uint16_t remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3973                 uint16_t credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
3974 
3975                 // param: check remote mtu
3976                 if (service->mtu > remote_mtu) {
3977                     l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3978                                                       num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INVALID_PARAMETERS);
3979                     return 1;
3980                 }
3981 
3982                 // check if authentication is required and possible
3983                 bool send_pending = false;
3984                 uint8_t security_status = l2cap_ecbm_security_status_for_connection_request(handle,
3985                                                                                             service->required_security_level,
3986                                                                                             service->requires_authorization);
3987                 if (security_status != L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS) {
3988                     if (gap_get_bondable_mode() != 0) {
3989                         // if possible, send pending and continue
3990                         send_pending = true;
3991                     } else {
3992                         // otherwise, send refused and abort
3993                         l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3994                                                           num_channels_and_signaling_cid, security_status);
3995                         return 1;
3996                     }
3997                 }
3998 
3999                 // report the last result code != 0
4000                 result = 0;
4001                 // store one of the local channels for the event
4002                 l2cap_channel_t * a_channel = NULL;
4003                 for (i = 0; i < num_channels; i++) {
4004 
4005                     // check source cids
4006                     uint16_t source_cid = little_endian_read_16(command, 12 + (i * 2));
4007                     if (source_cid < 0x40u) {
4008                         result = L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INVALID_SOURCE_CID;
4009                         continue;
4010                     }
4011 
4012                     // go through list of channels for this ACL connection and check if we get a match
4013                     btstack_linked_list_iterator_init(&it, &l2cap_channels);
4014                     bool source_cid_allocated = false;
4015                     while (btstack_linked_list_iterator_has_next(&it)) {
4016                         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4017                         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4018                         if (channel->con_handle != handle) continue;
4019                         if (channel->remote_cid != source_cid) continue;
4020                         source_cid_allocated = true;
4021                         break;
4022                     }
4023                     if (source_cid_allocated) {
4024                         result = 0x00a;
4025                         continue;
4026                     }
4027 
4028                     // setup channel
4029                     l2cap_channel_t *channel = l2cap_create_channel_entry(service->packet_handler,
4030                                                                           L2CAP_CHANNEL_TYPE_CHANNEL_ECBM,
4031                                                                           connection->address,
4032                                                                           connection->address_type, spsm,
4033                                                                           service->mtu,
4034                                                                           service->required_security_level);
4035 
4036                     if (channel == NULL) {
4037                         // Some connections refused – insufficient resources available
4038                         result = 0x004;
4039                         continue;
4040                     }
4041 
4042                     // setup state
4043                     channel->state = L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
4044                     channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
4045                     channel->con_handle = connection->con_handle;
4046                     channel->remote_sig_id = sig_id;
4047                     channel->remote_cid = source_cid;
4048                     channel->remote_mtu = remote_mtu;
4049                     channel->remote_mps = remote_mps;
4050                     channel->credits_outgoing = credits_outgoing;
4051                     channel->cid_index = i;
4052                     channel->num_cids = num_channels;
4053 
4054                     // if more than one error, we can report any of them
4055                     channel->reason = result;
4056 
4057                     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
4058 
4059                     a_channel = channel;
4060                 }
4061 
4062                 // if no channels have been created, all have been refused, and we can respond right away
4063                 if (a_channel == NULL) {
4064                     l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
4065                                                       num_channels_and_signaling_cid, result);
4066                     return 1;
4067                 }
4068 
4069                 // if security is pending, send intermediate response, otherwise, ask user
4070                 if (send_pending){
4071                     l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
4072                                                       num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_PENDING_AUTHENTICATION);
4073                 } else {
4074                     // if security is ok but authorization is required, send intermediate response and ask user
4075                     if (service->requires_authorization){
4076                         l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
4077                                                           num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_PENDING_AUTHORIZATION);
4078                     }
4079                     l2cap_ecbm_handle_security_level_incoming(a_channel);
4080                 }
4081 
4082             } else {
4083                 l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
4084                                                   num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_SPSM_NOT_SUPPORTED);
4085             }
4086             return 1;
4087 
4088         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
4089             // check size
4090             if (len < 10u) return 0u;
4091 
4092             // get hci connection, ignore if not found
4093             connection = hci_connection_for_handle(handle);
4094             if (connection == NULL) return 0;
4095 
4096             // get channel config: mtu, mps, initial credits, result
4097             new_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4098             new_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
4099             initial_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
4100             result = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
4101             status = l2cap_ecbm_status_for_result(result);
4102 
4103             // get num channels to modify
4104             num_channels = (len - 8) / sizeof(uint16_t);
4105             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4106             while (btstack_linked_list_iterator_has_next(&it)) {
4107                 uint8_t channel_status = status;
4108                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4109                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4110                 if (channel->con_handle != handle) continue;
4111                 if (channel->local_sig_id != sig_id) continue;
4112                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE) continue;
4113                 if (channel->cid_index < num_channels) {
4114                     uint16_t remote_cid = little_endian_read_16(command, 12 + channel->cid_index * sizeof(uint16_t));
4115                     if (remote_cid != 0) {
4116                         // check for duplicate remote CIDs
4117                         l2cap_channel_t * original_channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
4118                         if (original_channel == NULL){
4119                             channel->state = L2CAP_STATE_OPEN;
4120                             channel->remote_cid = remote_cid;
4121                             channel->remote_mtu = new_mtu;
4122                             channel->remote_mps = new_mps;
4123                             channel->credits_outgoing = initial_credits;
4124                             l2cap_ecbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
4125                             continue;
4126                         }
4127                         // close original channel
4128                         original_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4129                         channel_status = ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
4130                     }
4131                 }
4132                 // open failed
4133                 l2cap_ecbm_emit_channel_opened(channel, channel_status);
4134                 // drop failed channel
4135                 btstack_linked_list_iterator_remove(&it);
4136                 btstack_memory_l2cap_channel_free(channel);
4137             }
4138             return 1;
4139 
4140         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
4141             // check minimal size
4142             if (len < 6) return 0u;
4143 
4144             // get hci connection, bail if not found (must not happen)
4145             connection = hci_connection_for_handle(handle);
4146             btstack_assert(connection != NULL);
4147 
4148             // get num channels to modify
4149             num_channels = (len - 4) / sizeof(uint16_t);
4150 
4151             // get new mtu and mps
4152             new_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4153             new_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
4154 
4155             // validate request
4156             result = 0;
4157             for (i = 0; i < num_channels; i++) {
4158                 // check cid
4159                 uint16_t remote_cid = little_endian_read_16(command, 8 + (i * sizeof(uint16_t)));
4160                 l2cap_channel_t *channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
4161                 if (channel == NULL) {
4162                     result = L2CAP_ECBM_RECONFIGURE_FAILED_DESTINATION_CID_INVALID;
4163                     break;
4164                 }
4165                 // check MTU is not reduced
4166                 if (channel->remote_mtu > new_mtu) {
4167                     result = L2CAP_ECBM_RECONFIGURE_FAILED_MTU_REDUCTION_NOT_ALLOWED;
4168                     break;
4169                 }
4170                 // check MPS reduction
4171                 if ((num_channels > 1) && (channel->remote_mps > new_mps)) {
4172                     result = L2CAP_ECBM_RECONFIGURE_FAILED_MPS_REDUCTION_MULTIPLE_CHANNELS;
4173                     break;
4174                 }
4175                 // check MPS valid
4176                 if (new_mps < l2cap_enhanced_mps_min) {
4177                     result = L2CAP_ECBM_RECONFIGURE_FAILED_UNACCEPTABLE_PARAMETERS;
4178                     break;
4179                 }
4180             }
4181 
4182             // send reject
4183             if (result != 0) {
4184                 l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST, sig_id, signaling_cid,
4185                                                   result);
4186                 return 1;
4187             }
4188 
4189             // update channels
4190             for (i = 0; i < num_channels; i++) {
4191                 uint16_t remote_cid = little_endian_read_16(command, 8 + (i * sizeof(uint16_t)));
4192                 l2cap_channel_t *channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
4193                 channel->remote_mps = new_mps;
4194                 channel->remote_mtu = new_mtu;
4195                 // emit event
4196                 uint8_t event[8];
4197                 event[0] = L2CAP_EVENT_ECBM_RECONFIGURED;
4198                 event[1] = sizeof(event) - 2;
4199                 little_endian_store_16(event, 2, channel->local_cid);
4200                 little_endian_store_16(event, 4, new_mtu);
4201                 little_endian_store_16(event, 6, new_mps);
4202                 l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
4203             }
4204 
4205             // send accept
4206             l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST, sig_id, signaling_cid, 0);
4207             return 1;
4208 
4209         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
4210             // check size
4211             if (len < 2u) return 0u;
4212 
4213             result = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4214             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4215             while (btstack_linked_list_iterator_has_next(&it)) {
4216                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4217                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4218                 if (channel->con_handle != handle) continue;
4219                 if (channel->local_sig_id != sig_id) continue;
4220                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_RENEGOTIATION_RESPONSE) continue;
4221                 // complete request
4222                 if (result == 0) {
4223                     channel->receive_sdu_buffer = channel->renegotiate_sdu_buffer;
4224                     channel->local_mtu = channel->renegotiate_mtu;
4225                 }
4226                 channel->state = L2CAP_STATE_OPEN;
4227                 // emit event
4228                 l2cap_ecbm_emit_reconfigure_complete(channel, result);
4229             }
4230             break;
4231 
4232         default:
4233             btstack_unreachable();
4234             break;
4235     }
4236     return 0;
4237 }
4238 
4239 #endif
4240 
4241 #ifdef ENABLE_BLE
4242 
4243 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
4244     uint8_t event[6];
4245     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
4246     event[1] = 4;
4247     little_endian_store_16(event, 2, con_handle);
4248     little_endian_store_16(event, 4, result);
4249     l2cap_emit_event(event, sizeof(event));
4250 }
4251 
4252 // @return valid
4253 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
4254     hci_connection_t * connection;
4255     uint16_t result;
4256     uint8_t  event[12];
4257 
4258 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4259     l2cap_channel_t * channel;
4260     btstack_linked_list_iterator_t it;
4261 #endif
4262 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4263     uint16_t local_cid;
4264     uint16_t le_psm;
4265     l2cap_service_t * service;
4266     uint16_t source_cid;
4267 #endif
4268 
4269     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
4270     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
4271     log_info("le dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
4272 
4273     switch (code){
4274 
4275         case CONNECTION_PARAMETER_UPDATE_REQUEST:
4276             // check size
4277             if (len < 8u) return 0u;
4278             connection = hci_connection_for_handle(handle);
4279             if (connection != NULL){
4280                 if (connection->role != HCI_ROLE_MASTER){
4281                     // reject command without notifying upper layer when not in master role
4282                     return 0;
4283                 }
4284                 le_connection_parameter_range_t existing_range;
4285                 gap_get_connection_parameter_range(&existing_range);
4286                 uint16_t le_conn_interval_min   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
4287                 uint16_t le_conn_interval_max   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
4288                 uint16_t le_conn_latency        = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
4289                 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
4290 
4291                 int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
4292                 if (update_parameter){
4293                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
4294                     connection->le_conn_interval_min = le_conn_interval_min;
4295                     connection->le_conn_interval_max = le_conn_interval_max;
4296                     connection->le_conn_latency = le_conn_latency;
4297                     connection->le_supervision_timeout = le_supervision_timeout;
4298                 } else {
4299                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
4300                 }
4301                 connection->le_con_param_update_identifier = sig_id;
4302             }
4303 
4304             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
4305             event[1] = 10;
4306             little_endian_store_16(event, 2, handle);
4307             (void)memcpy(&event[4], &command[4], 8);
4308             l2cap_emit_event(event, sizeof(event));
4309             break;
4310 
4311         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
4312             // check size
4313             if (len < 2u) return 0u;
4314             result = little_endian_read_16(command, 4);
4315             l2cap_emit_connection_parameter_update_response(handle, result);
4316             break;
4317 
4318 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
4319         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
4320         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
4321         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
4322         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
4323             return l2cap_ecbm_signaling_handler_dispatch(handle, L2CAP_CID_SIGNALING_LE, command, sig_id);
4324 #endif
4325 
4326 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4327         case COMMAND_REJECT:
4328             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4329             while (btstack_linked_list_iterator_has_next(&it)){
4330                 channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4331                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4332                 if (channel->con_handle   != handle) continue;
4333                 if (channel->local_sig_id != sig_id) continue;
4334 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4335                 // if received while waiting for le connection response, assume legacy device
4336                 if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
4337                     channel->state = L2CAP_STATE_CLOSED;
4338                     // no official value for this, use: Connection refused – LE_PSM not supported
4339                     l2cap_cbm_emit_channel_opened(channel, L2CAP_CBM_CONNECTION_RESULT_SPSM_NOT_SUPPORTED);
4340 
4341                     // discard channel
4342                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4343                     l2cap_free_channel_entry(channel);
4344                     continue;
4345                 }
4346 #endif
4347 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
4348                 // if received while waiting for le connection response, assume legacy device
4349                 if (channel->state == L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE){
4350                     channel->state = L2CAP_STATE_CLOSED;
4351                     // treat as SPSM not supported
4352                     l2cap_ecbm_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_PSM);
4353 
4354                     // discard channel
4355                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4356                     l2cap_free_channel_entry(channel);
4357                     continue;
4358                 }
4359 #endif
4360             }
4361             break;
4362 #endif
4363 
4364 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4365         case LE_CREDIT_BASED_CONNECTION_REQUEST:
4366             // check size
4367             if (len < 10u) return 0u;
4368 
4369             // get hci connection, bail if not found (must not happen)
4370             connection = hci_connection_for_handle(handle);
4371             if (!connection) return 0;
4372 
4373             // check if service registered
4374             le_psm  = little_endian_read_16(command, 4);
4375             service = l2cap_cbm_get_service(le_psm);
4376             source_cid = little_endian_read_16(command, 6);
4377 
4378             if (service){
4379                 if (source_cid < 0x40u){
4380                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INVALID_SOURCE_CID);
4381                     return 1;
4382                 }
4383 
4384                 // go through list of channels for this ACL connection and check if we get a match
4385                 btstack_linked_list_iterator_init(&it, &l2cap_channels);
4386                 while (btstack_linked_list_iterator_has_next(&it)){
4387                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4388                     if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
4389                     if (a_channel->con_handle != handle) continue;
4390                     if (a_channel->remote_cid != source_cid) continue;
4391                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_SOURCE_CID_ALREADY_ALLOCATED);
4392                     return 1;
4393                 }
4394 
4395                 // security: check encryption
4396                 if (service->required_security_level >= LEVEL_2){
4397                     if (gap_encryption_key_size(handle) == 0){
4398                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_ENCRYPTION);
4399                         return 1;
4400                     }
4401                     // anything less than 16 byte key size is insufficient
4402                     if (gap_encryption_key_size(handle) < 16){
4403                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_ENCYRPTION_KEY_SIZE_TOO_SHORT);
4404                         return 1;
4405                     }
4406                 }
4407 
4408                 // security: check authentication
4409                 if (service->required_security_level >= LEVEL_3){
4410                     if (!gap_authenticated(handle)){
4411                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHENTICATION);
4412                         return 1;
4413                     }
4414                 }
4415 
4416                 // security: check authorization
4417                 if (service->required_security_level >= LEVEL_4){
4418                     if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
4419                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHORIZATION);
4420                         return 1;
4421                     }
4422                 }
4423 
4424                 // allocate channel
4425                 channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_CBM, connection->address,
4426                                                      BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
4427                 if (!channel){
4428                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE);
4429                     return 1;
4430                 }
4431 
4432                 channel->con_handle = handle;
4433                 channel->remote_cid = source_cid;
4434                 channel->remote_sig_id = sig_id;
4435                 channel->remote_mtu = little_endian_read_16(command, 8);
4436                 channel->remote_mps = little_endian_read_16(command, 10);
4437                 channel->credits_outgoing = little_endian_read_16(command, 12);
4438 
4439                 // set initial state
4440                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
4441                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
4442 
4443                 // add to connections list
4444                 btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
4445 
4446                 // post connection request event
4447                 l2cap_cbm_emit_incoming_connection(channel);
4448 
4449             } else {
4450                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_SPSM_NOT_SUPPORTED);
4451             }
4452             break;
4453 
4454         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
4455             // check size
4456             if (len < 10u) return 0u;
4457 
4458             // Find channel for this sig_id and connection handle
4459             channel = NULL;
4460             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4461             while (btstack_linked_list_iterator_has_next(&it)){
4462                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4463                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
4464                 if (a_channel->con_handle   != handle) continue;
4465                 if (a_channel->local_sig_id != sig_id) continue;
4466                 channel = a_channel;
4467                 break;
4468             }
4469             if (!channel) break;
4470 
4471             // cid + 0
4472             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
4473             if (result){
4474                 channel->state = L2CAP_STATE_CLOSED;
4475                 uint8_t status = l2cap_cbm_status_for_result(result);
4476                 l2cap_cbm_emit_channel_opened(channel, status);
4477 
4478                 // discard channel
4479                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4480                 l2cap_free_channel_entry(channel);
4481                 break;
4482             }
4483 
4484             // success
4485             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4486             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
4487             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
4488             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
4489             channel->state = L2CAP_STATE_OPEN;
4490             l2cap_cbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
4491             break;
4492 #endif
4493 
4494 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4495         case L2CAP_FLOW_CONTROL_CREDIT_INDICATION:
4496             return l2cap_credit_based_handle_credit_indication(handle, command, len) ? 1 : 0;
4497 
4498         case DISCONNECTION_REQUEST:
4499             // check size
4500             if (len < 4u) return 0u;
4501 
4502             // find channel
4503             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4504             channel = l2cap_get_channel_for_local_cid_and_handle(local_cid, handle);
4505             if (!channel) {
4506                 l2cap_register_signaling_response(handle, DISCONNECTION_REQUEST, sig_id,
4507                                                   little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2), local_cid);
4508                 break;
4509             }
4510             channel->remote_sig_id = sig_id;
4511             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
4512             break;
4513 
4514         case DISCONNECTION_RESPONSE:
4515             // check size
4516             if (len < 4u) return 0u;
4517 
4518             // find channel
4519             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4520             channel = l2cap_get_channel_for_local_cid_and_handle(local_cid, handle);
4521             if (!channel) break;
4522             if (channel->local_sig_id == sig_id) {
4523                 if (channel->state == L2CAP_STATE_WAIT_DISCONNECT){
4524                     l2cap_finalize_channel_close(channel);
4525                 }
4526             }
4527             break;
4528 #endif
4529 
4530         default:
4531             // command unknown -> reject command
4532             return 0;
4533     }
4534     return 1;
4535 }
4536 #endif
4537 
4538 #ifdef ENABLE_CLASSIC
4539 static void l2cap_acl_classic_handler_for_channel(l2cap_channel_t * l2cap_channel, uint8_t * packet, uint16_t size){
4540 
4541     // forward data only in OPEN state
4542     if (l2cap_channel->state != L2CAP_STATE_OPEN) return;
4543 
4544 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4545     if (l2cap_channel->channel_type == L2CAP_CHANNEL_TYPE_CHANNEL_ECBM){
4546         l2cap_credit_based_handle_pdu(l2cap_channel, packet, size);
4547         return;
4548     }
4549 #endif
4550 
4551 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
4552     if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
4553 
4554         int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
4555 
4556         // assert control + FCS fields are inside
4557         if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) return;
4558 
4559         if (l2cap_channel->fcs_option){
4560             // verify FCS (required if one side requested it)
4561             uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
4562             uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
4563 
4564 #ifdef L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL
4565             // simulate fcs error
4566             static int counter = 0;
4567             if (++counter == L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL) {
4568                 log_info("Simulate fcs error");
4569                 fcs_calculated++;
4570                 counter = 0;
4571             }
4572 #endif
4573 
4574             if (fcs_calculated == fcs_packet){
4575                 log_info("Packet FCS 0x%04x verified", fcs_packet);
4576             } else {
4577                 log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
4578                 // ERTM State Machine in Bluetooth Spec does not handle 'I-Frame with invalid FCS'
4579                 return;
4580             }
4581         }
4582 
4583         // switch on packet type
4584         uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
4585         uint8_t  req_seq = (control >> 8) & 0x3f;
4586         int final = (control >> 7) & 0x01;
4587         if (control & 1){
4588             // S-Frame
4589             int poll  = (control >> 4) & 0x01;
4590             l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
4591             log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
4592             l2cap_ertm_tx_packet_state_t * tx_state;
4593             switch (s){
4594                 case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
4595                     log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
4596                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4597                     if (poll && final){
4598                         // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
4599                         log_error("P=F=1 in S-Frame");
4600                         break;
4601                     }
4602                     if (poll){
4603                         // check if we did request selective retransmission before <==> we have stored SDU segments
4604                         int i;
4605                         int num_stored_out_of_order_packets = 0;
4606                         for (i=0;i<l2cap_channel->num_rx_buffers;i++){
4607                             int index = l2cap_channel->rx_store_index + i;
4608                             if (index >= l2cap_channel->num_rx_buffers){
4609                                 index -= l2cap_channel->num_rx_buffers;
4610                             }
4611                             l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
4612                             if (!rx_state->valid) continue;
4613                             num_stored_out_of_order_packets++;
4614                         }
4615                         if (num_stored_out_of_order_packets){
4616                             l2cap_channel->send_supervisor_frame_selective_reject = 1;
4617                         } else {
4618                             l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
4619                         }
4620                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
4621                     }
4622                     if (final){
4623                         // Stop-MonitorTimer
4624                         l2cap_ertm_stop_monitor_timer(l2cap_channel);
4625                         // If UnackedFrames > 0 then Start-RetransTimer
4626                         if (l2cap_channel->unacked_frames){
4627                             l2cap_ertm_start_retransmission_timer(l2cap_channel);
4628                         }
4629                         // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
4630                         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4631                     }
4632                     break;
4633                 case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
4634                     log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
4635                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4636                     // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
4637                     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4638                     break;
4639                 case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
4640                     log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
4641                     break;
4642                 case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
4643                     log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
4644                     if (poll){
4645                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4646                     }
4647                     // find requested i-frame
4648                     tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
4649                     if (tx_state){
4650                         log_info("Retransmission for tx_seq %u requested", req_seq);
4651                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
4652                         tx_state->retransmission_requested = 1;
4653                         l2cap_channel->srej_active = 1;
4654                     }
4655                     break;
4656                 default:
4657                     break;
4658             }
4659         } else {
4660             // I-Frame
4661             // get control
4662             l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
4663             uint8_t tx_seq = (control >> 1) & 0x3f;
4664             log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
4665             log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
4666             log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
4667             l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4668             if (final){
4669                 // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
4670                 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4671             }
4672 
4673             // get SDU
4674             const uint8_t * payload_data = &packet[COMPLETE_L2CAP_HEADER+2];
4675             uint16_t        payload_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
4676 
4677             // assert SDU size is smaller or equal to our buffers
4678             uint16_t max_payload_size = 0;
4679             switch (sar){
4680                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
4681                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
4682                     // SDU Length + MPS
4683                     max_payload_size = l2cap_channel->local_mps + 2;
4684                     break;
4685                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
4686                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
4687                     max_payload_size = l2cap_channel->local_mps;
4688                     break;
4689                 default:
4690                     btstack_assert(false);
4691                     break;
4692             }
4693             if (payload_len > max_payload_size){
4694                 log_info("payload len %u > max payload %u -> drop packet", payload_len, max_payload_size);
4695                 return;
4696             }
4697 
4698             // check ordering
4699             if (l2cap_channel->expected_tx_seq == tx_seq){
4700                 log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
4701                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
4702                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
4703 
4704                 // process SDU
4705                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, payload_data, payload_len);
4706 
4707                 // process stored segments
4708                 while (true){
4709                     int index = l2cap_channel->rx_store_index;
4710                     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
4711                     if (!rx_state->valid) break;
4712 
4713                     log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
4714                     l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
4715                     l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
4716 
4717                     rx_state->valid = 0;
4718                     l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
4719 
4720                     // update rx store index
4721                     index++;
4722                     if (index >= l2cap_channel->num_rx_buffers){
4723                         index = 0;
4724                     }
4725                     l2cap_channel->rx_store_index = index;
4726                 }
4727 
4728                 //
4729                 l2cap_channel->send_supervisor_frame_receiver_ready = 1;
4730 
4731             } else {
4732                 int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
4733                 if (delta < 2){
4734                     // store segment
4735                     l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, payload_data, payload_len);
4736 
4737                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
4738                     l2cap_channel->send_supervisor_frame_selective_reject = 1;
4739                 } else {
4740                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
4741                     l2cap_channel->send_supervisor_frame_reject = 1;
4742                 }
4743             }
4744         }
4745         return;
4746     }
4747 #endif
4748 
4749     // check size
4750     uint16_t payload_size = size - COMPLETE_L2CAP_HEADER;
4751     if (l2cap_channel->local_mtu < payload_size) return;
4752 
4753     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], payload_size);
4754 }
4755 #endif
4756 
4757 static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
4758 #ifdef ENABLE_CLASSIC
4759     l2cap_channel_t * l2cap_channel;
4760     l2cap_fixed_channel_t * l2cap_fixed_channel;
4761 
4762     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
4763     uint8_t  broadcast_flag = READ_ACL_FLAGS(packet) >> 2;
4764     switch (channel_id) {
4765 
4766         case L2CAP_CID_SIGNALING: {
4767             if (broadcast_flag != 0) break;
4768             uint32_t command_offset = 8;
4769             while ((command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET) < size) {
4770                 // assert signaling command is fully inside packet
4771                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
4772                 uint32_t next_command_offset = command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
4773                 if (next_command_offset > size){
4774                     log_error("l2cap signaling command len invalid -> drop");
4775                     break;
4776                 }
4777                 // handle signaling command
4778                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
4779                 // go to next command
4780                 command_offset = next_command_offset;
4781             }
4782             break;
4783         }
4784 
4785         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
4786             if (broadcast_flag == 0) break;
4787             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL);
4788             if (!l2cap_fixed_channel) break;
4789             if (!l2cap_fixed_channel->packet_handler) break;
4790             (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4791             break;
4792 
4793 #ifdef ENABLE_BLE
4794         case L2CAP_CID_BR_EDR_SECURITY_MANAGER:
4795             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_BR_EDR_SECURITY_MANAGER);
4796             if ((l2cap_fixed_channel == NULL) || (l2cap_fixed_channel->packet_handler == NULL)){
4797                 // Pairing Failed
4798                 l2cap_register_signaling_response(handle, (uint8_t) SM_PAIRING_FAILED, 0, L2CAP_CID_BR_EDR_SECURITY_MANAGER, SM_REASON_PAIRING_NOT_SUPPORTED);
4799             } else {
4800                 (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4801             }
4802             break;
4803 #endif
4804 
4805         default:
4806             if (broadcast_flag != 0) break;
4807             // Find channel for this channel_id and connection handle
4808             l2cap_channel = l2cap_get_channel_for_local_cid_and_handle(channel_id, handle);
4809             if (l2cap_channel != NULL){
4810                 l2cap_acl_classic_handler_for_channel(l2cap_channel, packet, size);
4811             }
4812             break;
4813     }
4814 #else
4815     UNUSED(handle); // ok: no code
4816     UNUSED(packet); // ok: no code
4817     UNUSED(size);   // ok: no code
4818 #endif
4819 }
4820 
4821 static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
4822 #ifdef ENABLE_BLE
4823 
4824     l2cap_fixed_channel_t * l2cap_fixed_channel;
4825 
4826 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4827     l2cap_channel_t * l2cap_channel;
4828 #endif
4829     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
4830     switch (channel_id) {
4831 
4832         case L2CAP_CID_SIGNALING_LE: {
4833             uint8_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
4834             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
4835             if ((COMPLETE_L2CAP_HEADER + 4u + len) > size) break;
4836             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
4837             if (!valid){
4838                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
4839             }
4840             break;
4841         }
4842 
4843         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
4844             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL);
4845             if (!l2cap_fixed_channel) break;
4846             if (!l2cap_fixed_channel->packet_handler) break;
4847             (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4848             break;
4849 
4850         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
4851             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
4852             if ((l2cap_fixed_channel == NULL) || (l2cap_fixed_channel->packet_handler == NULL)){
4853                 // Pairing Failed
4854                 l2cap_register_signaling_response(handle, (uint8_t) SM_PAIRING_FAILED, 0, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, SM_REASON_PAIRING_NOT_SUPPORTED);
4855             } else {
4856                 (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4857             }
4858             break;
4859 
4860         default:
4861 
4862 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4863             l2cap_channel = l2cap_get_channel_for_local_cid_and_handle(channel_id, handle);
4864             if (l2cap_channel != NULL) {
4865                 l2cap_credit_based_handle_pdu(l2cap_channel, packet, size);
4866             }
4867 #endif
4868             break;
4869     }
4870 #else
4871     UNUSED(handle); // ok: no code
4872     UNUSED(packet); // ok: no code
4873     UNUSED(size);   // ok: no code
4874 #endif
4875 }
4876 
4877 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
4878     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
4879     UNUSED(channel);        // ok: there is no channel
4880 
4881     // Assert full L2CAP header present
4882     if (size < COMPLETE_L2CAP_HEADER) return;
4883 
4884     // Dispatch to Classic or LE handler (SCO packets are not dispatched to L2CAP)
4885     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
4886     hci_connection_t *conn = hci_connection_for_handle(handle);
4887     if (!conn) return;
4888     if (conn->address_type == BD_ADDR_TYPE_ACL){
4889         l2cap_acl_classic_handler(handle, packet, size);
4890     } else {
4891         l2cap_acl_le_handler(handle, packet, size);
4892     }
4893 
4894     l2cap_run();
4895 }
4896 
4897 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
4898 void l2cap_register_fixed_channel(btstack_packet_handler_t packet_handler, uint16_t channel_id) {
4899     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
4900     if (!channel) return;
4901     channel->packet_handler = packet_handler;
4902 }
4903 
4904 #ifdef L2CAP_USES_CHANNELS
4905 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
4906 void l2cap_finalize_channel_close(l2cap_channel_t * channel){
4907     channel->state = L2CAP_STATE_CLOSED;
4908     l2cap_handle_channel_closed(channel);
4909     // discard channel
4910     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4911     l2cap_free_channel_entry(channel);
4912 }
4913 #endif
4914 
4915 #ifdef ENABLE_CLASSIC
4916 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
4917     return l2cap_get_service_internal(&l2cap_services, psm);
4918 }
4919 
4920 static void l2cap_update_minimal_security_level(void){
4921     // update minimal service security level
4922     gap_security_level_t minimal_level = LEVEL_1;
4923     btstack_linked_list_iterator_t it;
4924     btstack_linked_list_iterator_init(&it, &l2cap_services);
4925     while (btstack_linked_list_iterator_has_next(&it)){
4926         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
4927         if (service->required_security_level > minimal_level){
4928             minimal_level = service->required_security_level;
4929         };
4930     }
4931     gap_set_minimal_service_security_level(minimal_level);
4932 }
4933 
4934 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
4935 
4936     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
4937 
4938     // check for alread registered psm
4939     l2cap_service_t *service = l2cap_get_service(psm);
4940     if (service) {
4941         log_error("register: PSM %u already registered", psm);
4942         return L2CAP_SERVICE_ALREADY_REGISTERED;
4943     }
4944 
4945     // alloc structure
4946     service = btstack_memory_l2cap_service_get();
4947     if (!service) {
4948         log_error("register: no memory for l2cap_service_t");
4949         return BTSTACK_MEMORY_ALLOC_FAILED;
4950     }
4951 
4952     // fill in
4953     service->psm = psm;
4954     service->mtu = mtu;
4955     service->packet_handler = service_packet_handler;
4956     service->required_security_level = security_level;
4957 
4958     // add to services list
4959     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
4960 
4961     l2cap_update_minimal_security_level();
4962 
4963 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
4964     // enable page scan
4965     gap_connectable_control(1);
4966 #endif
4967 
4968 
4969     return ERROR_CODE_SUCCESS;
4970 }
4971 
4972 uint8_t l2cap_unregister_service(uint16_t psm){
4973 
4974     log_info("unregister psm 0x%x", psm);
4975 
4976     l2cap_service_t *service = l2cap_get_service(psm);
4977     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
4978     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
4979     btstack_memory_l2cap_service_free(service);
4980 
4981     l2cap_update_minimal_security_level();
4982 
4983 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
4984     // disable page scan when no services registered
4985     if (btstack_linked_list_empty(&l2cap_services)) {
4986         gap_connectable_control(0);
4987     }
4988 #endif
4989 
4990     return ERROR_CODE_SUCCESS;
4991 }
4992 #endif
4993 
4994 
4995 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4996 
4997 static void l2cap_credit_based_send_pdu(l2cap_channel_t *channel) {
4998     btstack_assert(channel != NULL);
4999     btstack_assert(channel->send_sdu_buffer != NULL);
5000     btstack_assert(channel->credits_outgoing > 0);
5001 
5002     // send part of SDU
5003     hci_reserve_packet_buffer();
5004     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
5005     uint8_t *l2cap_payload = acl_buffer + 8;
5006     uint16_t pos = 0;
5007     if (!channel->send_sdu_pos) {
5008         // store SDU len
5009         channel->send_sdu_pos += 2u;
5010         little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
5011         pos += 2u;
5012     }
5013     uint16_t payload_size = btstack_min(channel->send_sdu_len + 2u - channel->send_sdu_pos, channel->remote_mps - pos);
5014     log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size,
5015              channel->credits_outgoing);
5016     (void) memcpy(&l2cap_payload[pos],
5017                   &channel->send_sdu_buffer[channel->send_sdu_pos - 2u],
5018                   payload_size); // -2 for virtual SDU len
5019     pos += payload_size;
5020     channel->send_sdu_pos += payload_size;
5021     l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
5022 
5023     channel->credits_outgoing--;
5024 
5025     // update state (mark SDU as done) before calling hci_send_acl_packet_buffer (trigger l2cap_le_send_pdu again)
5026     bool done = channel->send_sdu_pos >= (channel->send_sdu_len + 2u);
5027     if (done) {
5028         channel->send_sdu_buffer = NULL;
5029     }
5030 
5031     hci_send_acl_packet_buffer(8u + pos);
5032 
5033     if (done) {
5034         // send done event
5035         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_PACKET_SENT);
5036         // inform about can send now
5037         l2cap_credit_based_notify_channel_can_send(channel);
5038     }
5039 }
5040 
5041 static uint8_t l2cap_credit_based_send_data(l2cap_channel_t * channel, const uint8_t * data, uint16_t size){
5042 
5043     if (size > channel->remote_mtu){
5044         log_error("l2cap send, cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
5045         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
5046     }
5047 
5048     if (channel->send_sdu_buffer){
5049         log_info("l2cap send, cid 0x%02x, cannot send", channel->local_cid);
5050         return BTSTACK_ACL_BUFFERS_FULL;
5051     }
5052 
5053     channel->send_sdu_buffer = data;
5054     channel->send_sdu_len    = size;
5055     channel->send_sdu_pos    = 0;
5056 
5057     l2cap_notify_channel_can_send();
5058     return ERROR_CODE_SUCCESS;
5059 }
5060 
5061 static uint8_t l2cap_credit_based_provide_credits(uint16_t local_cid, uint16_t credits){
5062     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5063     if (!channel) {
5064         log_error("le credits no channel for cid 0x%02x", local_cid);
5065         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5066     }
5067 
5068     // check state
5069     if (channel->state != L2CAP_STATE_OPEN){
5070         log_error("le credits but channel 0x%02x not open yet", local_cid);
5071     }
5072 
5073     // ignore if set to automatic credits
5074     if (channel->automatic_credits) return ERROR_CODE_SUCCESS;
5075 
5076     // assert incoming credits + credits <= 0xffff
5077     uint32_t total_credits = channel->credits_incoming;
5078     total_credits += channel->new_credits_incoming;
5079     total_credits += credits;
5080     if (total_credits > 0xffffu){
5081         log_error("le credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
5082                   channel->new_credits_incoming, credits);
5083     }
5084 
5085     // set credits_granted
5086     channel->new_credits_incoming += credits;
5087 
5088     // go
5089     l2cap_run();
5090     return ERROR_CODE_SUCCESS;
5091 }
5092 
5093 static void l2cap_credit_based_send_credits(l2cap_channel_t *channel) {
5094     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
5095     channel->local_sig_id = l2cap_next_sig_id();
5096     uint16_t new_credits = channel->new_credits_incoming;
5097     channel->new_credits_incoming = 0;
5098     channel->credits_incoming += new_credits;
5099     uint16_t signaling_cid = channel->address_type == BD_ADDR_TYPE_ACL ? L2CAP_CID_SIGNALING : L2CAP_CID_SIGNALING_LE;
5100     l2cap_send_general_signaling_packet(channel->con_handle, signaling_cid, L2CAP_FLOW_CONTROL_CREDIT_INDICATION, channel->local_sig_id, channel->local_cid, new_credits);
5101 }
5102 
5103 // @return valid
5104 static bool l2cap_credit_based_handle_credit_indication(hci_con_handle_t handle, const uint8_t * command, uint16_t len){
5105     // check size
5106     if (len < 4u) return false;
5107 
5108     // find channel
5109     uint16_t remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
5110     l2cap_channel_t * channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
5111     if (!channel) {
5112         log_error("credit: no channel for handle 0x%04x/cid 0x%02x", handle, remote_cid);
5113         return true;
5114     }
5115     uint16_t new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
5116     uint16_t credits_before = channel->credits_outgoing;
5117     channel->credits_outgoing += new_credits;
5118     // check for credit overrun
5119     if (credits_before > channel->credits_outgoing) {
5120         log_error("credit: new credits caused overrrun for cid 0x%02x, disconnecting", channel->local_cid);
5121         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
5122         return true;
5123     }
5124     log_info("credit: %u credits for 0x%02x, now %u", new_credits, channel->local_cid, channel->credits_outgoing);
5125     l2cap_call_notify_channel_in_run = true;
5126     return true;
5127 }
5128 
5129 static void l2cap_credit_based_handle_pdu(l2cap_channel_t * l2cap_channel, const uint8_t * packet, uint16_t size){
5130     // ignore empty packets
5131     if (size == COMPLETE_L2CAP_HEADER) return;
5132 
5133     // credit counting
5134     if (l2cap_channel->credits_incoming == 0u){
5135         log_info("(e)CBM: packet received but no incoming credits");
5136         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
5137         return;
5138     }
5139     l2cap_channel->credits_incoming--;
5140 
5141     // automatic credits
5142     if ((l2cap_channel->credits_incoming < L2CAP_CREDIT_BASED_FLOW_CONTROL_MODE_AUTOMATIC_CREDITS_WATERMARK) && l2cap_channel->automatic_credits){
5143         l2cap_channel->new_credits_incoming = L2CAP_CREDIT_BASED_FLOW_CONTROL_MODE_AUTOMATIC_CREDITS_INCREMENT;
5144     }
5145 
5146     // first fragment
5147     uint16_t pos = 0;
5148     if (!l2cap_channel->receive_sdu_len){
5149         if (size < (COMPLETE_L2CAP_HEADER + 2)) return;
5150         uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
5151         if (sdu_len > l2cap_channel->local_mtu) {
5152             log_info("(e)CBM: packet received larger than MTU");
5153             l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
5154             return;
5155         }
5156         l2cap_channel->receive_sdu_len = sdu_len;
5157         l2cap_channel->receive_sdu_pos = 0;
5158         pos  += 2u;
5159         size -= 2u;
5160     }
5161 
5162     uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
5163 
5164     // check fragment_size
5165     if (fragment_size > l2cap_channel->local_mps) {
5166         log_info("(e)CBM: fragment larger than local MPS");
5167         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
5168         return;
5169     }
5170 
5171     // check sdu overrun
5172     if ((l2cap_channel->receive_sdu_pos + fragment_size) > l2cap_channel->receive_sdu_len){
5173         log_info("(e)CBM: fragments larger than SDU");
5174         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
5175         return;
5176     }
5177 
5178     (void)memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos],
5179                  &packet[COMPLETE_L2CAP_HEADER + pos],
5180                  fragment_size);
5181     l2cap_channel->receive_sdu_pos += fragment_size;
5182 
5183     // done?
5184     log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
5185     if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
5186         l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
5187         l2cap_channel->receive_sdu_len = 0;
5188     }
5189 }
5190 
5191 static void l2cap_credit_based_notify_channel_can_send(l2cap_channel_t *channel){
5192     if (!channel->waiting_for_can_send_now) return;
5193     if (channel->send_sdu_buffer) return;
5194     channel->waiting_for_can_send_now = 0;
5195     log_debug("le can send now, local_cid 0x%x", channel->local_cid);
5196     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CAN_SEND_NOW);
5197 }
5198 #endif
5199 
5200 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
5201 // 1BH2222
5202 static void l2cap_cbm_emit_incoming_connection(l2cap_channel_t *channel) {
5203     log_info("le incoming addr_type %u, addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x, remote_mtu %u",
5204              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
5205     uint8_t event[19];
5206     event[0] = L2CAP_EVENT_CBM_INCOMING_CONNECTION;
5207     event[1] = sizeof(event) - 2u;
5208     event[2] = channel->address_type;
5209     reverse_bd_addr(channel->address, &event[3]);
5210     little_endian_store_16(event,  9, channel->con_handle);
5211     little_endian_store_16(event, 11, channel->psm);
5212     little_endian_store_16(event, 13, channel->local_cid);
5213     little_endian_store_16(event, 15, channel->remote_cid);
5214     little_endian_store_16(event, 17, channel->remote_mtu);
5215     hci_dump_packet( HCI_EVENT_PACKET, 1, event, sizeof(event));
5216     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
5217 }
5218 // 11BH22222
5219 static void l2cap_cbm_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
5220     log_info("opened le channel status 0x%x addr_type %u addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x local_mtu %u, remote_mtu %u",
5221              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
5222              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
5223     uint8_t event[23];
5224     event[0] = L2CAP_EVENT_CBM_CHANNEL_OPENED;
5225     event[1] = sizeof(event) - 2u;
5226     event[2] = status;
5227     event[3] = channel->address_type;
5228     reverse_bd_addr(channel->address, &event[4]);
5229     little_endian_store_16(event, 10, channel->con_handle);
5230     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
5231     little_endian_store_16(event, 13, channel->psm);
5232     little_endian_store_16(event, 15, channel->local_cid);
5233     little_endian_store_16(event, 17, channel->remote_cid);
5234     little_endian_store_16(event, 19, channel->local_mtu);
5235     little_endian_store_16(event, 21, channel->remote_mtu);
5236     hci_dump_packet( HCI_EVENT_PACKET, 1, event, sizeof(event));
5237     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
5238 }
5239 
5240 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
5241 void l2cap_cbm_finialize_channel_close(l2cap_channel_t * channel){
5242     channel->state = L2CAP_STATE_CLOSED;
5243     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
5244     // discard channel
5245     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
5246     l2cap_free_channel_entry(channel);
5247 }
5248 
5249 static inline l2cap_service_t * l2cap_cbm_get_service(uint16_t le_psm){
5250     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
5251 }
5252 
5253 uint8_t l2cap_cbm_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
5254 
5255     log_info("l2cap_cbm_register_service psm 0x%x", psm);
5256 
5257     // check for alread registered psm
5258     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5259     if (service) {
5260         return L2CAP_SERVICE_ALREADY_REGISTERED;
5261     }
5262 
5263     // alloc structure
5264     service = btstack_memory_l2cap_service_get();
5265     if (!service) {
5266         log_error("register: no memory for l2cap_service_t");
5267         return BTSTACK_MEMORY_ALLOC_FAILED;
5268     }
5269 
5270     // fill in
5271     service->psm = psm;
5272     service->mtu = 0;
5273     service->packet_handler = packet_handler;
5274     service->required_security_level = security_level;
5275     service->requires_authorization = false;
5276 
5277     // add to services list
5278     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
5279 
5280     // done
5281     return ERROR_CODE_SUCCESS;
5282 }
5283 
5284 uint8_t l2cap_cbm_unregister_service(uint16_t psm) {
5285     log_info("l2cap_cbm_unregister_service psm 0x%x", psm);
5286     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5287     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
5288 
5289     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
5290     btstack_memory_l2cap_service_free(service);
5291     return ERROR_CODE_SUCCESS;
5292 }
5293 
5294 uint8_t l2cap_cbm_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
5295     // get channel
5296     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5297     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5298 
5299     // validate state
5300     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
5301         return ERROR_CODE_COMMAND_DISALLOWED;
5302     }
5303 
5304     // set state accept connection
5305     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
5306     channel->receive_sdu_buffer = receive_sdu_buffer;
5307     channel->local_mtu = mtu;
5308     channel->new_credits_incoming = initial_credits;
5309     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5310 
5311     // go
5312     l2cap_run();
5313     return ERROR_CODE_SUCCESS;
5314 }
5315 
5316 uint8_t l2cap_cbm_decline_connection(uint16_t local_cid, uint16_t result) {
5317     // get channel
5318     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5319     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5320 
5321     // validate state
5322     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
5323         return ERROR_CODE_COMMAND_DISALLOWED;
5324     }
5325 
5326     // set state decline connection
5327     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
5328     channel->reason = result;
5329     l2cap_run();
5330     return ERROR_CODE_SUCCESS;
5331 }
5332 
5333 static gap_security_level_t l2cap_cbm_security_level_for_connection(hci_con_handle_t con_handle){
5334     uint8_t encryption_key_size = gap_encryption_key_size(con_handle);
5335     if (encryption_key_size == 0) return LEVEL_0;
5336 
5337     bool authenticated = gap_authenticated(con_handle);
5338     if (!authenticated) return LEVEL_2;
5339 
5340     return encryption_key_size == 16 ? LEVEL_4 : LEVEL_3;
5341 }
5342 
5343 // used to handle pairing complete after triggering to increase
5344 static void l2cap_cbm_sm_packet_handler(uint8_t packet_type, uint16_t channel_nr, uint8_t *packet, uint16_t size) {
5345     UNUSED(channel_nr);
5346     UNUSED(size);
5347     UNUSED(packet_type);
5348     btstack_assert(packet_type == HCI_EVENT_PACKET);
5349     if (hci_event_packet_get_type(packet) != SM_EVENT_PAIRING_COMPLETE) return;
5350     hci_con_handle_t con_handle = sm_event_pairing_complete_get_handle(packet);
5351     btstack_linked_list_iterator_t it;
5352     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5353     while (btstack_linked_list_iterator_has_next(&it)) {
5354         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5355         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5356         if (channel->con_handle != con_handle) continue;
5357         if (channel->state != L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE) continue;
5358 
5359         // found channel, check security level
5360         if (l2cap_cbm_security_level_for_connection(con_handle) < channel->required_security_level){
5361             // pairing failed or wasn't good enough, inform user
5362             l2cap_cbm_emit_channel_opened(channel, ERROR_CODE_INSUFFICIENT_SECURITY);
5363             // discard channel
5364             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
5365             l2cap_free_channel_entry(channel);
5366         } else {
5367             // send conn request now
5368             channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5369             l2cap_run();
5370         }
5371     }
5372 }
5373 
5374 uint8_t l2cap_cbm_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5375     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
5376     uint16_t * out_local_cid) {
5377 
5378     static btstack_packet_callback_registration_t sm_event_callback_registration;
5379     static bool sm_callback_registered = false;
5380 
5381     log_info("create, handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
5382 
5383     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5384     if (!connection) {
5385         log_error("no hci_connection for handle 0x%04x", con_handle);
5386         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5387     }
5388 
5389     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_CBM, connection->address, connection->address_type, psm, mtu, security_level);
5390     if (!channel) {
5391         return BTSTACK_MEMORY_ALLOC_FAILED;
5392     }
5393     log_info("created %p", channel);
5394 
5395     // store local_cid
5396     if (out_local_cid){
5397        *out_local_cid = channel->local_cid;
5398     }
5399 
5400     // setup channel entry
5401     channel->con_handle = con_handle;
5402     channel->receive_sdu_buffer = receive_sdu_buffer;
5403     channel->new_credits_incoming = initial_credits;
5404     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5405 
5406     // add to connections list
5407     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
5408 
5409     // check security level
5410     if (l2cap_cbm_security_level_for_connection(con_handle) < channel->required_security_level){
5411         if (!sm_callback_registered){
5412             sm_callback_registered = true;
5413             // lazy registration for SM events
5414             sm_event_callback_registration.callback = &l2cap_cbm_sm_packet_handler;
5415             sm_add_event_handler(&sm_event_callback_registration);
5416         }
5417 
5418         // start pairing
5419         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
5420         sm_request_pairing(con_handle);
5421     } else {
5422         // send conn request right away
5423         channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5424         l2cap_run();
5425     }
5426 
5427     return ERROR_CODE_SUCCESS;
5428 }
5429 
5430 uint8_t l2cap_cbm_provide_credits(uint16_t local_cid, uint16_t credits){
5431     return l2cap_credit_based_provide_credits(local_cid, credits);
5432 }
5433 #endif
5434 
5435 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
5436 
5437 uint8_t l2cap_ecbm_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, uint16_t min_remote_mtu,
5438                                     gap_security_level_t security_level, bool authorization_required) {
5439 
5440     // check for already registered psm
5441     l2cap_service_t *service = l2cap_ecbm_get_service(psm);
5442     if (service) {
5443         return L2CAP_SERVICE_ALREADY_REGISTERED;
5444     }
5445 
5446     // alloc structure
5447     service = btstack_memory_l2cap_service_get();
5448     if (!service) {
5449         log_error("register: no memory for l2cap_service_t");
5450         return BTSTACK_MEMORY_ALLOC_FAILED;
5451     }
5452 
5453     // fill in
5454     service->psm = psm;
5455     service->mtu = min_remote_mtu;
5456     service->packet_handler = packet_handler;
5457     service->required_security_level = security_level;
5458     service->requires_authorization = authorization_required;
5459 
5460     // add to services list
5461     btstack_linked_list_add(&l2cap_enhanced_services, (btstack_linked_item_t *) service);
5462 
5463     // done
5464     return ERROR_CODE_SUCCESS;
5465 }
5466 
5467 uint8_t l2cap_ecbm_unregister_service(uint16_t psm) {
5468     l2cap_service_t *service = l2cap_ecbm_get_service(psm);
5469     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
5470 
5471     btstack_linked_list_remove(&l2cap_enhanced_services, (btstack_linked_item_t *) service);
5472     btstack_memory_l2cap_service_free(service);
5473     return ERROR_CODE_SUCCESS;
5474 }
5475 
5476 void l2cap_ecbm_mps_set_min(uint16_t mps_min){
5477     l2cap_enhanced_mps_min = mps_min;
5478 }
5479 
5480 void l2cap_ecbm_mps_set_max(uint16_t mps_max){
5481     l2cap_enhanced_mps_max = mps_max;
5482 }
5483 
5484 uint8_t l2cap_ecbm_create_channels(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5485                                        gap_security_level_t security_level,
5486                                        uint16_t psm, uint8_t num_channels, uint16_t initial_credits, uint16_t mtu,
5487                                        uint8_t ** receive_sdu_buffers, uint16_t * out_local_cid){
5488 
5489     log_info("create enhanced, handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
5490 
5491     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5492     if (!connection) {
5493         log_error("no hci_connection for handle 0x%04x", con_handle);
5494         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5495     }
5496 
5497     // setup all channels
5498     btstack_linked_list_t channels = NULL;
5499     uint8_t status = l2cap_ecbm_setup_channels(&channels, packet_handler, num_channels, connection, psm, mtu,
5500                                                security_level);
5501     uint16_t local_mps = btstack_min(l2cap_enhanced_mps_max, btstack_min(l2cap_max_le_mtu(), mtu));
5502 
5503     // add to connections list and set state + local_sig_id
5504     l2cap_channel_t * channel;
5505     uint8_t i = 0;
5506     uint8_t local_sig_id = l2cap_next_sig_id();
5507     while (true) {
5508         channel = (l2cap_channel_t *) btstack_linked_list_pop(&channels);
5509         if (channel == NULL) break;
5510         channel->state              = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST;
5511         channel->local_sig_id       = local_sig_id;
5512         channel->local_mps = local_mps;
5513         channel->cid_index = i;
5514         channel->num_cids = num_channels;
5515         channel->credits_incoming   = initial_credits;
5516         channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5517         channel->receive_sdu_buffer = receive_sdu_buffers[i];
5518         // store local_cid
5519         if (out_local_cid){
5520             out_local_cid[i] = channel->local_cid;
5521         }
5522         btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
5523         i++;
5524     }
5525 
5526 #if 0
5527     // check security level
5528     if (l2cap_le_security_level_for_connection(con_handle) < channel->required_security_level){
5529         if (!sm_callback_registered){
5530             sm_callback_registered = true;
5531             // lazy registration for SM events
5532             sm_event_callback_registration.callback = &l2cap_sm_packet_handler;
5533             sm_add_event_handler(&sm_event_callback_registration);
5534         }
5535 
5536         // start pairing
5537         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
5538         sm_request_pairing(con_handle);
5539     } else {
5540         // send conn request right away
5541         channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5542         l2cap_run();
5543     }
5544 #endif
5545 
5546     l2cap_run();
5547 
5548     return status;
5549 }
5550 
5551 uint8_t l2cap_ecbm_accept_channels(uint16_t local_cid, uint8_t num_channels, uint16_t initial_credits,
5552                                             uint16_t receive_buffer_size, uint8_t ** receive_buffers, uint16_t * out_local_cids){
5553 
5554     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5555     if (!channel) {
5556 
5557         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5558     }
5559 
5560     uint16_t local_mps = btstack_min(l2cap_enhanced_mps_max, btstack_min(l2cap_max_le_mtu(), receive_buffer_size));
5561 
5562     //
5563     hci_con_handle_t  con_handle    = channel->con_handle;
5564     uint8_t           local_sig_id  = channel->local_sig_id;
5565     uint8_t           channel_index = 0;
5566     btstack_linked_list_iterator_t it;
5567     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5568     while (btstack_linked_list_iterator_has_next(&it)) {
5569         channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5570         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5571         if (channel->con_handle != con_handle) continue;
5572         if (channel->local_sig_id != local_sig_id) continue;
5573         if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT) continue;
5574 
5575         if (channel_index < num_channels){
5576             // assign buffer and cid
5577             out_local_cids[channel_index] = channel->local_cid;
5578             channel->receive_sdu_buffer = receive_buffers[channel_index];
5579             channel->local_mtu = receive_buffer_size;
5580             channel->local_mps = local_mps;
5581             channel->credits_incoming   = initial_credits;
5582             channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5583             channel_index++;
5584         } else {
5585             // clear local cid for response packet
5586             channel->local_cid = 0;
5587             channel->reason = L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INSUFFICIENT_RESOURCES_AVAILABLE;
5588         }
5589         // update state
5590         channel->state = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE;
5591     }
5592     l2cap_run_trigger();
5593     return ERROR_CODE_SUCCESS;
5594 }
5595 
5596 uint8_t l2cap_ecbm_decline_channels(uint16_t local_cid, uint16_t result){
5597     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5598     if (!channel) {
5599         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5600     }
5601     //
5602     hci_con_handle_t  con_handle    = channel->con_handle;
5603     uint8_t           local_sig_id  = channel->local_sig_id;
5604     btstack_linked_list_iterator_t it;
5605     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5606     while (btstack_linked_list_iterator_has_next(&it)) {
5607         channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5608         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5609         if (channel->con_handle != con_handle) continue;
5610         if (channel->local_sig_id != local_sig_id) continue;
5611         if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT) continue;
5612 
5613         // prepare response
5614         channel->local_cid = 0;
5615         channel->reason = result;
5616         channel->state = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE;
5617     }
5618     l2cap_run_trigger();
5619     return ERROR_CODE_SUCCESS;
5620 }
5621 
5622 uint8_t l2cap_ecbm_reconfigure_channels(uint8_t num_cids, uint16_t * local_cids, int16_t receive_buffer_size, uint8_t ** receive_buffers){
5623     btstack_assert(receive_buffers != NULL);
5624     btstack_assert(local_cids != NULL);
5625 
5626     if (num_cids > L2CAP_ECBM_MAX_CID_ARRAY_SIZE){
5627         return ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS;
5628     }
5629 
5630     // check if all cids exist and have the same con handle
5631     uint8_t i;
5632     hci_con_handle_t con_handle = HCI_CON_HANDLE_INVALID;
5633     for (i = 0 ; i < num_cids ; i++){
5634         l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cids[i]);
5635         if (!channel) {
5636             return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5637         }
5638         if (channel->state != L2CAP_STATE_OPEN){
5639             return ERROR_CODE_COMMAND_DISALLOWED;
5640         }
5641         if (con_handle == HCI_CON_HANDLE_INVALID){
5642             con_handle = channel->con_handle;
5643         } else if (con_handle != channel->con_handle){
5644             return ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS;
5645         }
5646     }
5647     // set renegotiation data and state
5648     uint8_t sig_id = l2cap_next_sig_id();
5649     for (i = 0 ; i < num_cids ; i++){
5650         l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cids[i]);
5651         channel->cid_index = i;
5652         channel->num_cids = num_cids;
5653         channel->local_sig_id = sig_id;
5654         channel->renegotiate_mtu = receive_buffer_size;
5655         channel->renegotiate_sdu_buffer = receive_buffers[i];
5656         channel->state = L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST;
5657     }
5658 
5659 
5660     l2cap_run();
5661     return ERROR_CODE_SUCCESS;
5662 }
5663 
5664 uint8_t l2cap_ecbm_provide_credits(uint16_t local_cid, uint16_t credits){
5665     return l2cap_credit_based_provide_credits(local_cid, credits);
5666 }
5667 #endif
5668 
5669 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
5670 // @deprecated - please use l2cap_ertm_create_channel
5671 uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
5672                                   l2cap_ertm_config_t * ertm_contig, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
5673     log_error("deprecated - please use l2cap_ertm_create_channel");
5674     return l2cap_ertm_create_channel(packet_handler, address, psm, ertm_contig, buffer, size, out_local_cid);
5675 };
5676 
5677 // @deprecated - please use l2cap_ertm_accept_connection
5678 uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, l2cap_ertm_config_t * ertm_contig, uint8_t * buffer, uint32_t size){
5679     log_error("deprecated - please use l2cap_ertm_accept_connection");
5680     return l2cap_ertm_accept_connection(local_cid, ertm_contig, buffer, size);
5681 }
5682 #endif
5683 
5684 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
5685 // @deprecated - please use l2cap_cbm_register_service
5686 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
5687     log_error("deprecated - please use l2cap_cbm_register_service");
5688     return l2cap_cbm_register_service(packet_handler, psm, security_level);
5689 }
5690 
5691 // @deprecated - please use l2cap_cbm_unregister_service
5692 uint8_t l2cap_le_unregister_service(uint16_t psm){
5693     log_error("deprecated - please use l2cap_cbm_unregister_service");
5694     return l2cap_cbm_unregister_service(psm);
5695 }
5696 
5697 // @deprecated - please use l2cap_cbm_accept_connection
5698 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
5699     log_error("deprecated - please use l2cap_cbm_accept_connection");
5700     return l2cap_cbm_accept_connection(local_cid, receive_sdu_buffer, mtu, initial_credits);
5701 }
5702 
5703 // @deprecated - please use l2cap_cbm_decline_connection
5704 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
5705     log_error("deprecated - please use l2cap_cbm_decline_connection");
5706     return l2cap_cbm_decline_connection(local_cid, L2CAP_CBM_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE);
5707 }
5708 
5709 // @deprecated - please use l2cap_cbm_create_channel
5710 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5711                                 uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
5712                                 uint16_t * out_local_cid){
5713     log_error("deprecated - please use l2cap_cbm_create_channel");
5714     return l2cap_cbm_create_channel(packet_handler, con_handle, psm, receive_sdu_buffer, mtu, initial_credits, security_level, out_local_cid);
5715 }
5716 
5717 // @deprecated - please use l2cap_cbm_provide_credits
5718 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
5719     log_error("deprecated - please use l2cap_cbm_provide_credits");
5720     return l2cap_cbm_provide_credits(local_cid, credits);
5721 }
5722 
5723 // @deprecated - please use l2cap_can_send_packet_now
5724 bool l2cap_le_can_send_now(uint16_t local_cid){
5725     log_error("deprecated - please use l2cap_can_send_packet_now");
5726     return l2cap_can_send_packet_now(local_cid);
5727 }
5728 
5729 // @deprecated - please use l2cap_request_can_send_now_event
5730 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
5731     log_error("deprecated - please use l2cap_request_can_send_now_event");
5732     return l2cap_request_can_send_now_event(local_cid);
5733 }
5734 
5735 // @deprecated - please use l2cap_cbm_send_data
5736 uint8_t l2cap_le_send_data(uint16_t local_cid, const uint8_t * data, uint16_t size){
5737     log_error("deprecated - please use l2cap_cbm_send_data");
5738     return l2cap_send(local_cid, data, size);
5739 }
5740 
5741 // @deprecated - please use l2cap_disconnect
5742 uint8_t l2cap_le_disconnect(uint16_t local_cid){
5743     log_error("deprecated - please use l2cap_disconnect");
5744     return l2cap_disconnect(local_cid);
5745 }
5746 #endif
5747