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