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