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