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