xref: /btstack/src/l2cap.c (revision bb1f325522e89d56162c04aa699e03379b4c8308)
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 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1643     features |= 0x0400;
1644 #endif
1645     return features;
1646 }
1647 #endif
1648 
1649 //
1650 #ifdef ENABLE_CLASSIC
1651 
1652 // returns true if channel was finalized
1653 static bool l2cap_run_for_classic_channel(l2cap_channel_t * channel){
1654 
1655 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1656     uint8_t  config_options[18];
1657 #else
1658     uint8_t  config_options[10];
1659 #endif
1660 
1661     switch (channel->state){
1662 
1663         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1664         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
1665             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1666             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
1667                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
1668                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONN_RESP_PEND);
1669                 l2cap_send_classic_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id,
1670                                                     channel->local_cid, channel->remote_cid, 1, 0);
1671             }
1672             break;
1673 
1674         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1675             if (!hci_can_send_command_packet_now()) break;
1676             // send connection request - set state first
1677             channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
1678             // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
1679             (void)memcpy(l2cap_outgoing_classic_addr, channel->address, 6);
1680             hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_get_allow_role_switch());
1681             break;
1682 
1683         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
1684             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1685             channel->state = L2CAP_STATE_INVALID;
1686             l2cap_send_classic_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id,
1687                                                 channel->local_cid, channel->remote_cid, channel->reason, 0);
1688             // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1689             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1690             l2cap_free_channel_entry(channel);
1691             channel = NULL;
1692             break;
1693 
1694         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
1695             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1696             channel->state = L2CAP_STATE_CONFIG;
1697             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1698             l2cap_send_classic_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id,
1699                                                 channel->local_cid, channel->remote_cid, 0, 0);
1700             break;
1701 
1702         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
1703             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1704             // success, start l2cap handshake
1705             channel->local_sig_id = l2cap_next_sig_id();
1706             channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
1707             l2cap_send_classic_signaling_packet(channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id,
1708                                                 channel->psm, channel->local_cid);
1709             l2cap_start_rtx(channel);
1710             break;
1711 
1712         case L2CAP_STATE_CONFIG:
1713             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1714 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1715             // fallback to basic mode if ERTM requested but not not supported by remote
1716             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1717                 if (!l2cap_ertm_mode(channel)){
1718                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1719                     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
1720                 }
1721             }
1722 #endif
1723             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
1724                 uint16_t flags = 0;
1725                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1726                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
1727                     flags = 1;
1728                 } else {
1729                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1730                 }
1731                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
1732                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1733                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1734                                                         channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS,
1735                                                         1, &channel->unknown_option);
1736 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1737                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
1738                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1739                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1740                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1741                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1742                                                         channel->remote_cid, flags,
1743                                                         L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS, options_size,
1744                                                         &config_options);
1745                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM){
1746                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
1747                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1748                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1749                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1750                                                         channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS,
1751                                                         options_size, &config_options);
1752 #endif
1753                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
1754                     channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1755                     uint16_t options_size = l2cap_setup_options_mtu_response(channel, config_options);
1756                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1757                                                         channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS,
1758                                                         options_size, &config_options);
1759                 } else {
1760                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1761                                                         channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
1762                 }
1763                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1764             }
1765             else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
1766                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1767                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
1768                 channel->local_sig_id = l2cap_next_sig_id();
1769                 uint16_t options_size = l2cap_setup_options_request(channel, config_options);
1770                 l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id,
1771                                                     channel->remote_cid, 0, options_size, &config_options);
1772                 l2cap_start_rtx(channel);
1773             }
1774             if (l2cap_channel_ready_for_open(channel)){
1775                 channel->state = L2CAP_STATE_OPEN;
1776                 l2cap_emit_channel_opened(channel, 0);  // success
1777             }
1778             break;
1779 
1780         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1781             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1782             channel->state = L2CAP_STATE_INVALID;
1783             l2cap_send_classic_signaling_packet(channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id,
1784                                                 channel->local_cid, channel->remote_cid);
1785             // 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 :)
1786             l2cap_finalize_channel_close(channel);  // -- remove from list
1787             channel = NULL;
1788             break;
1789 
1790         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1791             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1792             channel->local_sig_id = l2cap_next_sig_id();
1793             channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1794             l2cap_send_classic_signaling_packet(channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id,
1795                                                 channel->remote_cid, channel->local_cid);
1796             break;
1797         default:
1798             break;
1799     }
1800 
1801     // handle channel finalize on L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE and L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE
1802     return channel == NULL;
1803 }
1804 
1805 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1806 static void l2cap_run_for_classic_channel_ertm(l2cap_channel_t * channel){
1807 
1808     // ERTM mode
1809     if (channel->mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) return;
1810 
1811     // check if we can still send
1812     if (channel->con_handle == HCI_CON_HANDLE_INVALID) return;
1813     if (!hci_can_send_acl_packet_now(channel->con_handle)) return;
1814 
1815     if (channel->send_supervisor_frame_receiver_ready){
1816         channel->send_supervisor_frame_receiver_ready = 0;
1817         log_info("Send S-Frame: RR %u, final %u", channel->req_seq, channel->set_final_bit_after_packet_with_poll_bit_set);
1818         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);
1819         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1820         l2cap_ertm_send_supervisor_frame(channel, control);
1821         return;
1822     }
1823     if (channel->send_supervisor_frame_receiver_ready_poll){
1824         channel->send_supervisor_frame_receiver_ready_poll = 0;
1825         log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
1826         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
1827         l2cap_ertm_send_supervisor_frame(channel, control);
1828         return;
1829     }
1830     if (channel->send_supervisor_frame_receiver_not_ready){
1831         channel->send_supervisor_frame_receiver_not_ready = 0;
1832         log_info("Send S-Frame: RNR %u", channel->req_seq);
1833         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
1834         l2cap_ertm_send_supervisor_frame(channel, control);
1835         return;
1836     }
1837     if (channel->send_supervisor_frame_reject){
1838         channel->send_supervisor_frame_reject = 0;
1839         log_info("Send S-Frame: REJ %u", channel->req_seq);
1840         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 0, 0, channel->req_seq);
1841         l2cap_ertm_send_supervisor_frame(channel, control);
1842         return;
1843     }
1844     if (channel->send_supervisor_frame_selective_reject){
1845         channel->send_supervisor_frame_selective_reject = 0;
1846         log_info("Send S-Frame: SREJ %u", channel->expected_tx_seq);
1847         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);
1848         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1849         l2cap_ertm_send_supervisor_frame(channel, control);
1850         return;
1851     }
1852 
1853     if (channel->srej_active){
1854         int i;
1855         for (i=0;i<channel->num_tx_buffers;i++){
1856             l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
1857             if (tx_state->retransmission_requested) {
1858                 tx_state->retransmission_requested = 0;
1859                 uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set;
1860                 channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1861                 l2cap_ertm_send_information_frame(channel, i, final);
1862                 break;
1863             }
1864         }
1865         if (i == channel->num_tx_buffers){
1866             // no retransmission request found
1867             channel->srej_active = 0;
1868         } else {
1869             // packet was sent
1870             return;
1871         }
1872     }
1873 }
1874 #endif /* ERTM */
1875 #endif /* Classic */
1876 
1877 static void l2cap_run_signaling_response(void) {
1878 
1879     // check pending signaling responses
1880     while (l2cap_signaling_responses_pending){
1881 
1882         hci_con_handle_t handle = l2cap_signaling_responses[0].handle;
1883 
1884         if (!hci_can_send_acl_packet_now(handle)) break;
1885 
1886         uint8_t  sig_id        = l2cap_signaling_responses[0].sig_id;
1887         uint8_t  response_code = l2cap_signaling_responses[0].code;
1888         uint16_t result        = l2cap_signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT, REJECT_SM_PAIRING, L2CAP_CREDIT_BASED_CONNECTION_REQUEST
1889         uint8_t  buffer[4];                                          // REJECT_SM_PAIRING, CONFIGURE_REQUEST
1890         uint16_t source_cid    = l2cap_signaling_responses[0].cid;   // CONNECTION_REQUEST, REJECT_SM_PAIRING, DISCONNECT_REQUEST, CONFIGURE_REQUEST, DISCONNECT_REQUEST
1891 #ifdef ENABLE_CLASSIC
1892         uint16_t dest_cid      = l2cap_signaling_responses[0].data;  // DISCONNECT_REQUEST
1893         uint16_t info_type     = l2cap_signaling_responses[0].data;  // INFORMATION_REQUEST
1894 #endif
1895 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1896         uint8_t num_channels = l2cap_signaling_responses[0].cid >> 8;                 // L2CAP_CREDIT_BASED_CONNECTION_REQUEST
1897         uint16_t signaling_cid = (uint16_t) l2cap_signaling_responses[0].cid & 0xff;  // L2CAP_CREDIT_BASED_CONNECTION_REQUEST, L2CAP_CREDIT_BASED_CONNECTION_REQUEST
1898 #endif
1899 
1900         // remove first item before sending (to avoid sending response mutliple times)
1901         l2cap_signaling_responses_pending--;
1902         int i;
1903         for (i=0; i < l2cap_signaling_responses_pending; i++){
1904             (void)memcpy(&l2cap_signaling_responses[i],
1905                          &l2cap_signaling_responses[i + 1],
1906                          sizeof(l2cap_signaling_response_t));
1907         }
1908 
1909         switch (response_code){
1910 #ifdef ENABLE_CLASSIC
1911             case CONNECTION_REQUEST:
1912                 l2cap_send_classic_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
1913                 break;
1914             case CONFIGURE_REQUEST:
1915                 little_endian_store_16(buffer, 0, source_cid);
1916                 little_endian_store_16(buffer, 2, 0);
1917                 l2cap_send_classic_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 4, buffer);
1918                 break;
1919             case DISCONNECTION_RESPONSE:
1920                 l2cap_send_classic_signaling_packet(handle, DISCONNECTION_RESPONSE, sig_id, dest_cid, source_cid);
1921                 break;
1922             case ECHO_REQUEST:
1923                 l2cap_send_classic_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
1924                 break;
1925             case INFORMATION_REQUEST:
1926                 switch (info_type){
1927                     case L2CAP_INFO_TYPE_CONNECTIONLESS_MTU: {
1928                         uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
1929                         l2cap_send_classic_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0,
1930                                                             sizeof(connectionless_mtu), &connectionless_mtu);
1931                         }
1932                         break;
1933                     case L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED: {
1934                         uint32_t features = l2cap_extended_features_mask();
1935                         l2cap_send_classic_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0,
1936                                                             sizeof(features), &features);
1937                         }
1938                         break;
1939                     case L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED: {
1940                             uint8_t map[8];
1941                             memset(map, 0, 8);
1942                             // L2CAP Signaling Channel + Connectionless reception
1943                             map[0] = (1 << L2CAP_CID_SIGNALING) | (1 << L2CAP_CID_CONNECTIONLESS_CHANNEL);
1944 #if defined (ENABLE_EXPLICIT_BR_EDR_SECURITY_MANAGER) || (defined(ENABLE_BLE) && defined(ENABLE_CROSS_TRANSPORT_KEY_DERIVATION))
1945                             // BR/EDR Security Manager (bit 7) if BR/EDR Secure Connections possible
1946                             if (gap_secure_connections_active()){
1947                                 map[0] |= (1 << L2CAP_CID_BR_EDR_SECURITY_MANAGER);
1948                             }
1949 #endif
1950                             l2cap_send_classic_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0,
1951                                                             sizeof(map), &map);
1952                         }
1953                         break;
1954                     default:
1955                         // all other types are not supported
1956                         l2cap_send_classic_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 1, 0, NULL);
1957                         break;
1958                 }
1959                 break;
1960             case COMMAND_REJECT:
1961                 l2cap_send_classic_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
1962                 break;
1963 #endif
1964 #ifdef ENABLE_BLE
1965             case LE_CREDIT_BASED_CONNECTION_REQUEST:
1966                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
1967                 break;
1968             case DISCONNECTION_REQUEST:
1969                 // Invalid CID, local cid, remote cid
1970                 little_endian_store_16(buffer, 0, result);
1971                 little_endian_store_16(buffer, 2, source_cid);
1972                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, 0x0002, 4, buffer);
1973                 break;
1974             case COMMAND_REJECT_LE:
1975                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
1976                 break;
1977 #endif
1978 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1979             case L2CAP_CREDIT_BASED_CONNECTION_REQUEST: {
1980                 // send variable size array or cids with each cid being zero
1981                 uint16_t cids[6];
1982                 (void) memset(cids, 0xff, sizeof(cids));
1983                 (void) memset(cids, 0x00, num_channels * sizeof(uint16_t));
1984                 l2cap_send_general_signaling_packet(handle, signaling_cid, L2CAP_CREDIT_BASED_CONNECTION_RESPONSE,
1985                                                     sig_id, 0, 0, 0, result, cids);
1986                 break;
1987             }
1988 
1989             case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
1990                 l2cap_send_general_signaling_packet(handle, signaling_cid, L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE,
1991                                                     sig_id, result);
1992                 break;
1993 #endif
1994             case SM_PAIRING_FAILED:
1995                 buffer[0] = SM_CODE_PAIRING_FAILED;
1996                 buffer[1] = (uint8_t) result;
1997                 l2cap_send_connectionless(handle, source_cid, buffer, 2);
1998                 break;
1999             default:
2000                 // should not happen
2001                 break;
2002         }
2003     }
2004 }
2005 
2006 #ifdef ENABLE_CLASSIC
2007 static bool l2ap_run_information_requests(void){
2008     // send l2cap information request if requested
2009     btstack_linked_list_iterator_t it;
2010     hci_connections_get_iterator(&it);
2011     uint8_t info_type;
2012     l2cap_information_state_t new_state;
2013     while(btstack_linked_list_iterator_has_next(&it)){
2014         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
2015         switch (connection->l2cap_state.information_state){
2016             case L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST:
2017                 info_type = L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED;
2018                 new_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
2019                 break;
2020             case L2CAP_INFORMATION_STATE_W2_SEND_FIXED_CHANNELS_REQUEST:
2021                 info_type = L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED;
2022                 new_state = L2CAP_INFORMATION_STATE_W4_FIXED_CHANNELS_RESPONSE;
2023                 break;
2024             default:
2025                 continue;
2026         }
2027         if (!hci_can_send_acl_packet_now(connection->con_handle)) break;
2028 
2029         connection->l2cap_state.information_state = new_state;
2030         uint8_t sig_id = l2cap_next_sig_id();
2031         l2cap_send_classic_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
2032     }
2033     return false;
2034 }
2035 #endif
2036 
2037 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2038 // returns true if channel has been closed
2039 static bool l2cap_cbm_run_channel(l2cap_channel_t * channel) {
2040     uint16_t mps;
2041     bool channel_closed = false;
2042     // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
2043     switch (channel->state){
2044         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
2045             channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
2046             // le psm, source cid, mtu, mps, initial credits
2047             channel->local_sig_id = l2cap_next_sig_id();
2048             channel->credits_incoming =  channel->new_credits_incoming;
2049             channel->new_credits_incoming = 0;
2050             channel->local_mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
2051             l2cap_send_le_signaling_packet( channel->con_handle, LE_CREDIT_BASED_CONNECTION_REQUEST,
2052                                             channel->local_sig_id, channel->psm, channel->local_cid, channel->local_mtu,
2053                                             channel->local_mps, channel->credits_incoming);
2054             break;
2055         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
2056             // TODO: support larger MPS
2057             channel->state = L2CAP_STATE_OPEN;
2058             channel->credits_incoming =  channel->new_credits_incoming;
2059             channel->new_credits_incoming = 0;
2060             mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
2061             channel->local_mps = mps;
2062             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);
2063             // notify client
2064             l2cap_cbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
2065             break;
2066         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
2067             channel->state = L2CAP_STATE_INVALID;
2068             l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
2069             channel_closed = true;
2070             break;
2071         case L2CAP_STATE_OPEN:
2072             if (channel->new_credits_incoming){
2073                 l2cap_credit_based_send_credits(channel);
2074             }
2075             break;
2076         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2077             channel->local_sig_id = l2cap_next_sig_id();
2078             channel->state = L2CAP_STATE_WAIT_DISCONNECT;
2079             l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
2080             break;
2081         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
2082             channel->state = L2CAP_STATE_INVALID;
2083             l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
2084             l2cap_cbm_finialize_channel_close(channel);  // -- remove from list
2085             break;
2086         default:
2087             break;
2088     }
2089     return channel_closed;
2090 }
2091 
2092 static void l2cap_cbm_run_channels(void){
2093     btstack_linked_list_iterator_t it;
2094     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2095     while (btstack_linked_list_iterator_has_next(&it)){
2096         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2097 
2098         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CHANNEL_CBM) continue;
2099         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2100 
2101         bool channel_closed = l2cap_cbm_run_channel(channel);
2102         if (channel_closed) {
2103             // discard channel - l2cap_finialize_channel_close without sending l2cap close event
2104             btstack_linked_list_iterator_remove(&it);
2105             l2cap_free_channel_entry(channel);
2106         }
2107     }
2108 }
2109 
2110 static inline uint8_t l2cap_cbm_status_for_result(uint16_t result) {
2111     switch (result) {
2112         case L2CAP_CBM_CONNECTION_RESULT_SUCCESS:
2113             return ERROR_CODE_SUCCESS;
2114         case L2CAP_CBM_CONNECTION_RESULT_SPSM_NOT_SUPPORTED:
2115             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_PSM;
2116         case L2CAP_CBM_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE:
2117             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_RESOURCES;
2118         case L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHENTICATION:
2119         case L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHORIZATION:
2120         case L2CAP_CBM_CONNECTION_RESULT_ENCYRPTION_KEY_SIZE_TOO_SHORT:
2121         case L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_ENCRYPTION:
2122             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY;
2123         default:
2124             // invalid Source CID, Source CID already allocated, unacceptable parameters
2125             return L2CAP_CONNECTION_RESPONSE_UNKNOWN_ERROR;
2126     }
2127 }
2128 
2129 #endif
2130 
2131 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2132 
2133 static void l2cap_run_trigger_callback(void * context){
2134     UNUSED(context);
2135     l2cap_run();
2136 }
2137 
2138 static void l2cap_run_trigger(void){
2139     btstack_run_loop_execute_on_main_thread(&l2cap_trigger_run_registration);
2140 }
2141 
2142 // 11BH22222
2143 static void l2cap_ecbm_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
2144     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",
2145             status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
2146             channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
2147     uint8_t event[23];
2148     event[0] = L2CAP_EVENT_ECBM_CHANNEL_OPENED;
2149     event[1] = sizeof(event) - 2u;
2150     event[2] = status;
2151     event[3] = channel->address_type;
2152     reverse_bd_addr(channel->address, &event[4]);
2153     little_endian_store_16(event, 10, channel->con_handle);
2154     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
2155     little_endian_store_16(event, 13, channel->psm);
2156     little_endian_store_16(event, 15, channel->local_cid);
2157     little_endian_store_16(event, 17, channel->remote_cid);
2158     little_endian_store_16(event, 19, channel->local_mtu);
2159     little_endian_store_16(event, 21, channel->remote_mtu);
2160     hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
2161     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
2162 }
2163 
2164 static void l2cap_ecbm_emit_reconfigure_complete(l2cap_channel_t *channel, uint16_t result) {
2165     // emit event
2166     uint8_t event[6];
2167     event[0] = L2CAP_EVENT_ECBM_RECONFIGURATION_COMPLETE;
2168     event[1] = sizeof(event) - 2;
2169     little_endian_store_16(event, 2, channel->local_cid);
2170     little_endian_store_16(event, 4, result);
2171     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
2172 }
2173 
2174 static void l2cap_ecbm_run_channels(void) {
2175     hci_con_handle_t con_handle = HCI_CON_HANDLE_INVALID;
2176     // num max channels + 1 for signaling pdu generator
2177     uint16_t cids[L2CAP_ECBM_MAX_CID_ARRAY_SIZE + 1];
2178     uint8_t num_cids = 0;
2179     uint8_t sig_id;
2180     uint16_t spsm;
2181     L2CAP_STATE matching_state;
2182     bool match_remote_sig_cid;
2183     uint8_t result = 0;
2184     uint16_t local_mtu;
2185     uint16_t initial_credits;
2186     uint16_t signaling_cid;
2187     L2CAP_STATE new_state;
2188     uint16_t local_mps;
2189 
2190     // pick first channel that needs to send a combined signaling pdu and setup collection via break
2191     // then collect all others that belong to the same pdu
2192     btstack_linked_list_iterator_t it;
2193     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2194     while (btstack_linked_list_iterator_has_next(&it)) {
2195         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2196         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CHANNEL_ECBM) continue;
2197         if (con_handle == HCI_CON_HANDLE_INVALID) {
2198             switch (channel->state) {
2199                 case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST:
2200                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2201                     local_mtu = channel->local_mtu;
2202                     local_mps = channel->local_mps;
2203                     spsm = channel->psm;
2204                     result = channel->reason;
2205                     initial_credits = channel->credits_incoming;
2206                     sig_id = channel->local_sig_id;
2207                     new_state = L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE;
2208                     match_remote_sig_cid = false;
2209                     break;
2210                 case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE:
2211                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2212                     local_mtu = channel->local_mtu;
2213                     local_mps = channel->local_mps;
2214                     initial_credits = channel->credits_incoming;
2215                     sig_id = channel->remote_sig_id;
2216                     new_state = L2CAP_STATE_OPEN;
2217                     match_remote_sig_cid = true;
2218                     break;
2219                 case L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST:
2220                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2221                     sig_id = channel->local_sig_id;
2222                     local_mtu = channel->renegotiate_mtu;
2223                     local_mps = channel->local_mps;
2224                     new_state = L2CAP_STATE_WAIT_ENHANCED_RENEGOTIATION_RESPONSE;
2225                     match_remote_sig_cid = false;
2226                     break;
2227                 case L2CAP_STATE_OPEN:
2228                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2229                     if (channel->new_credits_incoming) {
2230                         l2cap_credit_based_send_credits(channel);
2231                     }
2232                     continue;
2233                 case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2234                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2235                     channel->local_sig_id = l2cap_next_sig_id();
2236                     channel->state = L2CAP_STATE_WAIT_DISCONNECT;
2237                     signaling_cid = channel->address_type == BD_ADDR_TYPE_ACL ? L2CAP_CID_SIGNALING : L2CAP_CID_SIGNALING_LE;
2238                     l2cap_send_general_signaling_packet(channel->con_handle, signaling_cid, DISCONNECTION_REQUEST,
2239                                                         channel->local_sig_id, channel->remote_cid, channel->local_cid);
2240                     continue;
2241                 case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
2242                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2243                     channel->state = L2CAP_STATE_INVALID;
2244                     signaling_cid = channel->address_type == BD_ADDR_TYPE_ACL ? L2CAP_CID_SIGNALING : L2CAP_CID_SIGNALING_LE;
2245                     l2cap_send_general_signaling_packet(channel->con_handle, signaling_cid, DISCONNECTION_RESPONSE,
2246                                                         channel->remote_sig_id, channel->local_cid,
2247                                                         channel->remote_cid);
2248                     l2cap_cbm_finialize_channel_close(channel);  // -- remove from list
2249                     continue;
2250                 default:
2251                     continue;
2252             }
2253 
2254             // channel picked - setup cid array and collect info
2255             (void) memset(cids, 0xff, sizeof(cids));
2256             (void) memset(cids, 0, channel->num_cids * sizeof(uint16_t));
2257             matching_state = channel->state;
2258             con_handle = channel->con_handle;
2259             signaling_cid = channel->address_type == BD_ADDR_TYPE_ACL ? L2CAP_CID_SIGNALING : L2CAP_CID_SIGNALING_LE;
2260             num_cids = channel->num_cids;
2261 
2262         } else {
2263             // check if it matches first channel by state, con_handle, and signaling id
2264             if (matching_state != channel->state) continue;
2265             if (channel->con_handle != con_handle) continue;
2266             if (match_remote_sig_cid) {
2267                 if (channel->remote_sig_id != sig_id) continue;
2268             } else {
2269                 if (channel->local_sig_id != sig_id) continue;
2270             }
2271         }
2272 
2273         // add this cid
2274         cids[channel->cid_index] = channel->local_cid;
2275 
2276         // set new state
2277         channel->state = new_state;
2278 
2279         // handle open for L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE
2280         if (matching_state == L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE) {
2281             if (channel->reason == L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS) {
2282                 l2cap_ecbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
2283             } else {
2284                 result = channel->reason;
2285                 btstack_linked_list_iterator_remove(&it);
2286                 btstack_memory_l2cap_channel_free(channel);
2287             }
2288         }
2289     }
2290 
2291     if (con_handle != HCI_CON_HANDLE_INVALID) {
2292         switch (matching_state) {
2293             case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST:
2294                 log_info("send combined connection request for %u cids", num_cids);
2295                 l2cap_send_general_signaling_packet(con_handle, signaling_cid, L2CAP_CREDIT_BASED_CONNECTION_REQUEST,
2296                                                     sig_id, spsm, local_mtu, local_mps, initial_credits, cids);
2297                 break;
2298             case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE:
2299                 log_info("send combined connection response for %u cids", num_cids);
2300                 l2cap_send_general_signaling_packet(con_handle, signaling_cid, L2CAP_CREDIT_BASED_CONNECTION_RESPONSE,
2301                                                     sig_id, local_mtu, local_mps, initial_credits, result, cids);
2302                 break;
2303             case L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST:
2304                 log_info("send combined renegotiation request for %u cids", num_cids);
2305                 l2cap_send_general_signaling_packet(con_handle, signaling_cid, L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST,
2306                                                     sig_id, local_mtu, local_mps, cids);
2307                 break;
2308             default:
2309                 break;
2310         }
2311     }
2312 }
2313 #endif
2314 
2315 // MARK: L2CAP_RUN
2316 // process outstanding signaling tasks
2317 static void l2cap_run(void){
2318 
2319     // log_info("l2cap_run: entered");
2320     l2cap_run_signaling_response();
2321 
2322 #ifdef ENABLE_CLASSIC
2323     bool done = l2ap_run_information_requests();
2324     if (done) return;
2325 #endif
2326 
2327 #if defined(ENABLE_CLASSIC) || defined(ENABLE_BLE)
2328     btstack_linked_list_iterator_t it;
2329 #endif
2330 
2331 #ifdef ENABLE_CLASSIC
2332     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2333     while (btstack_linked_list_iterator_has_next(&it)){
2334 
2335         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2336 
2337         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CLASSIC) continue;
2338 
2339         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
2340         bool finalized = l2cap_run_for_classic_channel(channel);
2341 
2342         if (!finalized) {
2343 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2344             l2cap_run_for_classic_channel_ertm(channel);
2345 #endif
2346         }
2347     }
2348 #endif
2349 
2350 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2351     l2cap_cbm_run_channels();
2352 #endif
2353 
2354 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2355     l2cap_ecbm_run_channels();
2356 #endif
2357 
2358 #ifdef ENABLE_BLE
2359     // send l2cap con paramter update if necessary
2360     hci_connections_get_iterator(&it);
2361     while(btstack_linked_list_iterator_has_next(&it)){
2362         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
2363         if (!hci_is_le_connection_type(connection->address_type)) continue;
2364         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
2365         switch (connection->le_con_parameter_update_state){
2366             case CON_PARAMETER_UPDATE_SEND_REQUEST:
2367                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2368                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, l2cap_next_sig_id(),
2369                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
2370                 break;
2371             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
2372                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
2373                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
2374                 break;
2375             case CON_PARAMETER_UPDATE_DENY:
2376                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2377                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
2378                 break;
2379             default:
2380                 break;
2381         }
2382     }
2383 #endif
2384 
2385     if (l2cap_call_notify_channel_in_run){
2386         l2cap_call_notify_channel_in_run = false;
2387         l2cap_notify_channel_can_send();
2388     }
2389 
2390     // log_info("l2cap_run: exit");
2391 }
2392 
2393 #ifdef ENABLE_CLASSIC
2394 static void l2cap_ready_to_connect(l2cap_channel_t * channel){
2395 
2396 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2397     // assumption: outgoing connection
2398     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
2399         // ERTM requested: trigger information request if not already started then wait for response
2400         hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
2401         switch (connection->l2cap_state.information_state){
2402             case L2CAP_INFORMATION_STATE_DONE:
2403                 break;
2404             case L2CAP_INFORMATION_STATE_IDLE:
2405                 connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2406                 /* fall through */
2407             default:
2408                 channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
2409                 return;
2410         }
2411     }
2412 #endif
2413 
2414     // fine, go ahead
2415     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
2416 }
2417 
2418 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
2419     if ((channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE) || (channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION)) {
2420         log_info("connection complete con_handle %04x - for channel %p cid 0x%04x", (int) con_handle, channel, channel->local_cid);
2421         channel->con_handle = con_handle;
2422         // query remote features if pairing is required
2423         if (channel->required_security_level > LEVEL_0){
2424             channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
2425             hci_remote_features_query(con_handle);
2426         } else {
2427             l2cap_ready_to_connect(channel);
2428         }
2429     }
2430 }
2431 
2432 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
2433     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
2434 
2435     bool security_required = channel->required_security_level > LEVEL_0;
2436 
2437     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) != 0){
2438 
2439         // Core V5.2, Vol 3, Part C, 5.2.2.2 - Security Mode 4
2440         //   When a remote device attempts to access a service offered by a Bluetooth device that is in security mode 4
2441         //   and a sufficient link key exists and authentication has not been performed the local device shall authenticate
2442         //   the remote device and enable encryption after the channel establishment request is received but before a channel
2443         //   establishment confirmation (L2CAP_ConnectRsp with result code of 0x0000 or a higher-level channel establishment
2444         //   confirmation such as that of RFCOMM) is sent.
2445 
2446         //   If the remote device has indicated support for Secure Simple Pairing, a channel establishment request is
2447         //   received for a service other than SDP, and encryption has not yet been enabled, then the local device shall
2448         //   disconnect the ACL link with error code 0x05 - Authentication Failure.
2449 
2450         // => Disconnect if l2cap request received in mode 4 and ssp supported, non-sdp psm, not encrypted, no link key available
2451         if ((gap_get_security_mode() == GAP_SECURITY_MODE_4)
2452         && gap_ssp_supported_on_both_sides(channel->con_handle)
2453         && (channel->psm != PSM_SDP)
2454         && (gap_encryption_key_size(channel->con_handle) == 0)){
2455             hci_disconnect_security_block(channel->con_handle);
2456             return;
2457         }
2458 
2459         // incoming: assert security requirements
2460         channel->state = L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
2461         if (channel->required_security_level <= gap_security_level(channel->con_handle)){
2462             l2cap_handle_security_level_incoming_sufficient(channel);
2463         } else {
2464             // send connection pending if not already done
2465             if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONN_RESP_PEND) == 0){
2466                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND;
2467             }
2468             gap_request_security_level(channel->con_handle, channel->required_security_level);
2469         }
2470     } else {
2471         // outgoing: we have been waiting for remote supported features
2472         if (security_required){
2473             // request security level
2474             channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
2475             gap_request_security_level(channel->con_handle, channel->required_security_level);
2476         } else {
2477             l2cap_ready_to_connect(channel);
2478         }
2479     }
2480 }
2481 #endif
2482 
2483 #ifdef L2CAP_USES_CHANNELS
2484 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,
2485     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
2486 
2487     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
2488     if (!channel) {
2489         return NULL;
2490     }
2491 
2492     // fill in
2493     channel->packet_handler = packet_handler;
2494     channel->channel_type   = channel_type;
2495     bd_addr_copy(channel->address, address);
2496     channel->address_type = address_type;
2497     channel->psm = psm;
2498     channel->local_mtu  = local_mtu;
2499     channel->remote_mtu = L2CAP_DEFAULT_MTU;
2500     channel->required_security_level = security_level;
2501 
2502     //
2503     channel->local_cid = l2cap_next_local_cid();
2504     channel->con_handle = HCI_CON_HANDLE_INVALID;
2505 
2506     // set initial state
2507     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
2508     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
2509     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
2510     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
2511 
2512     log_info("create channel %p, local_cid 0x%04x", (void*)channel, channel->local_cid);
2513 
2514     return channel;
2515 }
2516 
2517 static void l2cap_free_channel_entry(l2cap_channel_t * channel){
2518     log_info("free channel %p, local_cid 0x%04x", (void*)channel, channel->local_cid);
2519     // assert all timers are stopped
2520     l2cap_stop_rtx(channel);
2521 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2522     l2cap_ertm_stop_retransmission_timer(channel);
2523     l2cap_ertm_stop_monitor_timer(channel);
2524 #endif
2525     // free  memory
2526     btstack_memory_l2cap_channel_free(channel);
2527 }
2528 #endif
2529 
2530 #ifdef ENABLE_CLASSIC
2531 
2532 /**
2533  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
2534  * @param packet_handler
2535  * @param address
2536  * @param psm
2537  * @param mtu
2538  * @param local_cid
2539  */
2540 
2541 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){
2542     // limit MTU to the size of our outgoing HCI buffer
2543     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
2544 
2545 	// determine security level based on psm
2546 	const gap_security_level_t security_level = l2cap_security_level_0_allowed_for_PSM(psm) ? LEVEL_0 : gap_get_security_level();
2547 	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);
2548 
2549     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);
2550     if (!channel) {
2551         return BTSTACK_MEMORY_ALLOC_FAILED;
2552     }
2553 
2554 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2555     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2556 #endif
2557 
2558     // add to connections list
2559     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2560 
2561     // store local_cid
2562     if (out_local_cid){
2563        *out_local_cid = channel->local_cid;
2564     }
2565 
2566 	// state: L2CAP_STATE_WILL_SEND_CREATE_CONNECTION
2567 
2568     // check if hci connection is already usable,
2569     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
2570     if (conn && conn->state == OPEN){
2571     	// simulate connection complete
2572 	    l2cap_handle_connection_complete(conn->con_handle, channel);
2573 
2574 	    // state: L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES or L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST
2575 
2576         // simulate if remote supported features if requested and already received
2577         if ((channel->state == L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) && hci_remote_features_available(conn->con_handle)) {
2578         	// simulate remote features received
2579             l2cap_handle_remote_supported_features_received(channel);
2580         }
2581     }
2582 
2583     l2cap_run();
2584 
2585     return ERROR_CODE_SUCCESS;
2586 }
2587 
2588 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
2589     // mark all channels before emitting open events as these could trigger new connetion requests to the same device
2590     btstack_linked_list_iterator_t it;
2591     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2592     while (btstack_linked_list_iterator_has_next(&it)){
2593         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2594         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2595         if (bd_addr_cmp( channel->address, address) != 0) continue;
2596         // channel for this address found
2597         switch (channel->state){
2598             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2599             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2600                 channel->state = L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD;
2601                 break;
2602             default:
2603                 break;
2604         }
2605     }
2606     // emit and free marked entries. restart loop to deal with list changes
2607     int done = 0;
2608     while (!done) {
2609         done = 1;
2610         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2611         while (btstack_linked_list_iterator_has_next(&it)){
2612             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2613             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2614             if (channel->state == L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD){
2615                 done = 0;
2616                 // failure, forward error code
2617                 l2cap_handle_channel_open_failed(channel, status);
2618                 // discard channel
2619                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2620                 l2cap_free_channel_entry(channel);
2621                 break;
2622             }
2623         }
2624     }
2625 
2626 }
2627 
2628 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
2629     btstack_linked_list_iterator_t it;
2630     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2631     while (btstack_linked_list_iterator_has_next(&it)){
2632         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2633         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2634         if ( ! bd_addr_cmp( channel->address, address) ){
2635             l2cap_handle_connection_complete(handle, channel);
2636         }
2637     }
2638 
2639 #ifdef ENABLE_L2CAP_INFORMATION_REQUESTS_ON_CONNECT
2640     // trigger query of extended features and fixed channels right away (instead of later)
2641     hci_connection_t * hci_connection = hci_connection_for_handle(handle);
2642     btstack_assert(hci_connection != NULL);
2643     hci_connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2644 #endif
2645 
2646     // process
2647     l2cap_run();
2648 }
2649 #endif
2650 
2651 static bool l2cap_channel_ready_to_send(l2cap_channel_t * channel){
2652     switch (channel->channel_type){
2653 #ifdef ENABLE_CLASSIC
2654         case L2CAP_CHANNEL_TYPE_CLASSIC:
2655             if (channel->state != L2CAP_STATE_OPEN) return false;
2656 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2657             // send if we have more data and remote windows isn't full yet
2658             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2659                 if (channel->unacked_frames >= btstack_min(channel->num_stored_tx_frames, channel->remote_tx_window_size)) return false;
2660                 return hci_can_send_acl_packet_now(channel->con_handle);
2661             }
2662 #endif
2663             if (!channel->waiting_for_can_send_now) return false;
2664             return hci_can_send_acl_packet_now(channel->con_handle);
2665         case L2CAP_CHANNEL_TYPE_FIXED_CLASSIC:
2666         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2667             if (!channel->waiting_for_can_send_now) return false;
2668             return hci_can_send_acl_classic_packet_now();
2669 #endif
2670 #ifdef ENABLE_BLE
2671         case L2CAP_CHANNEL_TYPE_FIXED_LE:
2672             if (!channel->waiting_for_can_send_now) return false;
2673             return hci_can_send_acl_le_packet_now();
2674 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2675         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
2676             if (channel->state != L2CAP_STATE_OPEN) return false;
2677             if (channel->send_sdu_buffer == NULL) return false;
2678             if (channel->credits_outgoing == 0u) return false;
2679             return hci_can_send_acl_packet_now(channel->con_handle);
2680 #endif
2681 #endif
2682 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2683         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
2684             if (channel->state != L2CAP_STATE_OPEN) return false;
2685             if (channel->send_sdu_buffer == NULL) return false;
2686             if (channel->credits_outgoing == 0u) return false;
2687             return hci_can_send_acl_packet_now(channel->con_handle);
2688 #endif
2689         default:
2690             return false;
2691     }
2692 }
2693 
2694 static void l2cap_channel_trigger_send(l2cap_channel_t * channel){
2695     switch (channel->channel_type){
2696 #ifdef ENABLE_CLASSIC
2697         case L2CAP_CHANNEL_TYPE_CLASSIC:
2698 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2699             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2700                 l2cap_ertm_channel_send_information_frame(channel);
2701                 return;
2702             }
2703 #endif
2704             channel->waiting_for_can_send_now = 0;
2705             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2706             break;
2707         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2708         case L2CAP_CHANNEL_TYPE_FIXED_CLASSIC:
2709             channel->waiting_for_can_send_now = 0;
2710             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2711             break;
2712 #endif
2713 #ifdef ENABLE_BLE
2714         case L2CAP_CHANNEL_TYPE_FIXED_LE:
2715             channel->waiting_for_can_send_now = 0;
2716             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2717             break;
2718 #endif
2719 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2720         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
2721             l2cap_credit_based_send_pdu(channel);
2722             break;
2723 #endif
2724 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2725         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
2726             l2cap_credit_based_send_pdu(channel);
2727             break;
2728 #endif
2729         default:
2730             btstack_unreachable();
2731             break;
2732     }
2733 }
2734 
2735 static void l2cap_notify_channel_can_send(void){
2736     bool done = false;
2737     while (!done){
2738         done = true;
2739         btstack_linked_list_iterator_t it;
2740         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2741         while (btstack_linked_list_iterator_has_next(&it)){
2742             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2743             bool ready = l2cap_channel_ready_to_send(channel);
2744             if (!ready) continue;
2745 
2746             // requeue channel for fairness
2747             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2748             btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2749 
2750             // trigger sending
2751             l2cap_channel_trigger_send(channel);
2752 
2753             // exit inner loop as we just broke the iterator, but try again
2754             done = false;
2755             break;
2756         }
2757     }
2758 }
2759 
2760 #ifdef L2CAP_USES_CHANNELS
2761 
2762 uint8_t l2cap_disconnect(uint16_t local_cid){
2763     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2764     if (!channel) {
2765         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2766     }
2767     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2768     l2cap_run();
2769     return ERROR_CODE_SUCCESS;
2770 }
2771 
2772 static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){
2773     // open cannot fail for for incoming connections
2774     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0;
2775 
2776     // check state
2777     switch (channel->state){
2778         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2779         case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2780         case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES:
2781         case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2782         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
2783         case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES:
2784         case L2CAP_STATE_WAIT_CONNECT_RSP:
2785         case L2CAP_STATE_CONFIG:
2786         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
2787         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
2788         case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE:
2789         case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD:
2790             return 1;
2791 
2792         case L2CAP_STATE_OPEN:
2793         case L2CAP_STATE_CLOSED:
2794         case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES:
2795         case L2CAP_STATE_WAIT_DISCONNECT:
2796         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY:
2797         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
2798         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
2799         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2800         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
2801         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
2802         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
2803         case L2CAP_STATE_INVALID:
2804         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2805             return 0;
2806 
2807         default:
2808             // get a "warning" about new states
2809             btstack_assert(false);
2810             return 0;
2811     }
2812 }
2813 #endif
2814 
2815 #ifdef ENABLE_CLASSIC
2816 static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){
2817     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2818         l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2819     } else {
2820         l2cap_handle_channel_closed(channel);
2821     }
2822     l2cap_free_channel_entry(channel);
2823 }
2824 #endif
2825 
2826 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2827 static void l2cap_handle_hci_le_disconnect_event(l2cap_channel_t * channel){
2828     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2829         l2cap_cbm_emit_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2830     } else {
2831         l2cap_emit_channel_closed(channel);
2832     }
2833     l2cap_free_channel_entry(channel);
2834 }
2835 #endif
2836 
2837 #ifdef ENABLE_CLASSIC
2838 static void l2cap_check_classic_timeout(hci_con_handle_t handle){
2839     if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) {
2840         return;
2841     }
2842     if (hci_authentication_active_for_handle(handle)) {
2843         return;
2844     }
2845     bool hci_con_used = false;
2846     btstack_linked_list_iterator_t it;
2847     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2848     while (btstack_linked_list_iterator_has_next(&it)){
2849         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2850         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2851         if (channel->con_handle != handle) continue;
2852         hci_con_used = true;
2853         break;
2854     }
2855     if (hci_con_used) {
2856         return;
2857     }
2858     if (!hci_can_send_command_packet_now()) {
2859         return;
2860     }
2861     hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
2862 }
2863 
2864 static void l2cap_handle_features_complete(hci_con_handle_t handle){
2865     if (hci_remote_features_available(handle) == false){
2866         return;
2867     }
2868     btstack_linked_list_iterator_t it;
2869     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2870     while (btstack_linked_list_iterator_has_next(&it)){
2871         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2872         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2873         if (channel->con_handle != handle) continue;
2874         log_info("remote supported features, channel %p, cid %04x - state %u", channel, channel->local_cid, channel->state);
2875         l2cap_handle_remote_supported_features_received(channel);
2876     }
2877 }
2878 
2879 static void l2cap_handle_security_level_incoming_sufficient(l2cap_channel_t * channel){
2880     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2881     l2cap_emit_incoming_connection(channel);
2882 }
2883 
2884 static void l2cap_handle_security_level(hci_con_handle_t handle, gap_security_level_t actual_level){
2885     log_info("security level update for handle 0x%04x", handle);
2886 
2887     // trigger l2cap information requests
2888     if (actual_level > LEVEL_0){
2889         hci_connection_t * hci_connection = hci_connection_for_handle(handle);
2890         btstack_assert(hci_connection != NULL);
2891         if (hci_connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
2892             hci_connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2893         }
2894     }
2895 
2896     bool done = false;
2897     while (!done){
2898         done = true;
2899         btstack_linked_list_iterator_t it;
2900         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2901         while (btstack_linked_list_iterator_has_next(&it)){
2902             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2903             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2904             if (channel->con_handle != handle) continue;
2905 
2906             gap_security_level_t required_level = channel->required_security_level;
2907 
2908             log_info("channel %p, cid %04x - state %u: actual %u >= required %u?", channel, channel->local_cid, channel->state, actual_level, required_level);
2909 
2910             switch (channel->state){
2911                 case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2912                     if (actual_level >= required_level){
2913                         l2cap_handle_security_level_incoming_sufficient(channel);
2914                     } else {
2915                         channel->reason = L2CAP_CONNECTION_RESULT_SECURITY_BLOCK;
2916                         channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2917                     }
2918                     break;
2919 
2920                 case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2921                     if (actual_level >= required_level){
2922                         l2cap_ready_to_connect(channel);
2923                     } else {
2924                         // security level insufficient, report error and free channel
2925                         l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY);
2926                         btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t  *) channel);
2927                         l2cap_free_channel_entry(channel);
2928                     }
2929                     break;
2930 
2931                 default:
2932                     break;
2933             }
2934         }
2935     }
2936 }
2937 #endif
2938 
2939 #ifdef L2CAP_USES_CHANNELS
2940 static void l2cap_handle_disconnection_complete(hci_con_handle_t handle){
2941     // collect channels to close
2942     btstack_linked_list_t channels_to_close = NULL;
2943     btstack_linked_list_iterator_t it;
2944     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2945     while (btstack_linked_list_iterator_has_next(&it)) {
2946         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2947         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2948         if (channel->con_handle != handle) continue;
2949         btstack_linked_list_iterator_remove(&it);
2950         btstack_linked_list_add(&channels_to_close, (btstack_linked_item_t *) channel);
2951     }
2952     // send l2cap open failed or closed events for all channels on this handle and free them
2953     btstack_linked_list_iterator_init(&it, &channels_to_close);
2954     while (btstack_linked_list_iterator_has_next(&it)) {
2955         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2956         btstack_linked_list_iterator_remove(&it);
2957         switch(channel->channel_type){
2958 #ifdef ENABLE_CLASSIC
2959             case L2CAP_CHANNEL_TYPE_CLASSIC:
2960                 l2cap_handle_hci_disconnect_event(channel);
2961                 break;
2962 #endif
2963 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2964             case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
2965                 l2cap_handle_hci_le_disconnect_event(channel);
2966                 break;
2967 #endif
2968 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2969             case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
2970                 switch (channel->state) {
2971                     case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST:
2972                     case L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE:
2973                         // emit open failed if disconnected before connection complete
2974                         l2cap_ecbm_emit_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2975                         break;
2976                     case L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST:
2977                     case L2CAP_STATE_WAIT_ENHANCED_RENEGOTIATION_RESPONSE:
2978                         // emit reconfigure failure - result = 0xffff
2979                         l2cap_ecbm_emit_reconfigure_complete(channel, 0xffff);
2980                         break;
2981                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2982                         // no incoming event has been sent to higher layer, no need to follow up
2983                         break;
2984                     default:
2985                         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
2986                         break;
2987                 }
2988                 l2cap_free_channel_entry(channel);
2989                 break;
2990 #endif
2991             default:
2992                 break;
2993         }
2994     }
2995 }
2996 #endif
2997 
2998 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
2999 
3000     UNUSED(packet_type); // ok: registered with hci_event_callback_registration
3001     UNUSED(cid);         // ok: there is no channel
3002     UNUSED(size);        // ok: fixed format events read from HCI buffer
3003 
3004 #ifdef ENABLE_CLASSIC
3005     bd_addr_t address;
3006     gap_security_level_t security_level;
3007 #endif
3008 #ifdef L2CAP_USES_CHANNELS
3009     hci_con_handle_t handle;
3010 #endif
3011 
3012     switch(hci_event_packet_get_type(packet)){
3013 
3014         // Notify channel packet handler if they can send now
3015         case HCI_EVENT_TRANSPORT_PACKET_SENT:
3016         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
3017         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
3018 #ifdef ENABLE_TESTING_SUPPORT
3019         case HCI_EVENT_NOP:
3020 #endif
3021             l2cap_call_notify_channel_in_run = true;
3022             break;
3023 
3024         case HCI_EVENT_COMMAND_STATUS:
3025 #ifdef ENABLE_CLASSIC
3026             // check command status for create connection for errors
3027             if (hci_event_command_status_get_command_opcode(packet) == HCI_OPCODE_HCI_CREATE_CONNECTION){
3028                 // cache outgoing address and reset
3029                 (void)memcpy(address, l2cap_outgoing_classic_addr, 6);
3030                 memset(l2cap_outgoing_classic_addr, 0, 6);
3031                 // error => outgoing connection failed
3032                 uint8_t status = hci_event_command_status_get_status(packet);
3033                 if (status){
3034                     l2cap_handle_connection_failed_for_addr(address, status);
3035                 }
3036             }
3037 #endif
3038             l2cap_run();    // try sending signaling packets first
3039             break;
3040 
3041 #ifdef ENABLE_CLASSIC
3042         // handle connection complete events
3043         case HCI_EVENT_CONNECTION_COMPLETE:
3044             reverse_bd_addr(&packet[5], address);
3045             if (packet[2] == 0){
3046                 handle = little_endian_read_16(packet, 3);
3047                 l2cap_handle_connection_success_for_addr(address, handle);
3048             } else {
3049                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
3050             }
3051             break;
3052 
3053         // handle successful create connection cancel command
3054         case HCI_EVENT_COMMAND_COMPLETE:
3055             if (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_CREATE_CONNECTION_CANCEL) {
3056                 if (packet[5] == 0){
3057                     reverse_bd_addr(&packet[6], address);
3058                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
3059                     l2cap_handle_connection_failed_for_addr(address, 0x16);
3060                 }
3061             }
3062             l2cap_run();    // try sending signaling packets first
3063             break;
3064 #endif
3065 
3066 #ifdef L2CAP_USES_CHANNELS
3067         // handle disconnection complete events
3068         case HCI_EVENT_DISCONNECTION_COMPLETE:
3069             handle = little_endian_read_16(packet, 3);
3070             l2cap_handle_disconnection_complete(handle);
3071             break;
3072 #endif
3073 
3074         // HCI Connection Timeouts
3075 #ifdef ENABLE_CLASSIC
3076         case L2CAP_EVENT_TIMEOUT_CHECK:
3077             handle = little_endian_read_16(packet, 2);
3078             l2cap_check_classic_timeout(handle);
3079             break;
3080 
3081         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
3082         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
3083             handle = little_endian_read_16(packet, 3);
3084             l2cap_handle_features_complete(handle);
3085             break;
3086 
3087         case GAP_EVENT_SECURITY_LEVEL:
3088             handle = little_endian_read_16(packet, 2);
3089             security_level = (gap_security_level_t) packet[4];
3090             l2cap_handle_security_level(handle, security_level);
3091             break;
3092 #endif
3093         default:
3094             break;
3095     }
3096 
3097     l2cap_run();
3098 }
3099 
3100 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t cid, uint16_t data){
3101     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indicates the connection was refused."
3102     if (l2cap_signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
3103         l2cap_signaling_responses[l2cap_signaling_responses_pending].handle = handle;
3104         l2cap_signaling_responses[l2cap_signaling_responses_pending].code = code;
3105         l2cap_signaling_responses[l2cap_signaling_responses_pending].sig_id = sig_id;
3106         l2cap_signaling_responses[l2cap_signaling_responses_pending].cid = cid;
3107         l2cap_signaling_responses[l2cap_signaling_responses_pending].data = data;
3108         l2cap_signaling_responses_pending++;
3109         l2cap_run();
3110     }
3111 }
3112 
3113 #ifdef ENABLE_CLASSIC
3114 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint8_t identifier){
3115     switch (channel->state){
3116         case L2CAP_STATE_CONFIG:
3117         case L2CAP_STATE_OPEN:
3118         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
3119         case L2CAP_STATE_WAIT_DISCONNECT:
3120             break;
3121         default:
3122             // ignore in other states
3123             return;
3124     }
3125 
3126     channel->remote_sig_id = identifier;
3127     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
3128     l2cap_run();
3129 }
3130 
3131 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
3132 
3133     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
3134     l2cap_service_t *service = l2cap_get_service(psm);
3135     if (!service) {
3136         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CONNECTION_RESULT_PSM_NOT_SUPPORTED);
3137         return;
3138     }
3139 
3140     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
3141     if (!hci_connection) {
3142         //
3143         log_error("no hci_connection for handle %u", handle);
3144         return;
3145     }
3146 
3147     // if SC only mode is active and service requires encryption, reject connection if SC not active or use security level
3148     gap_security_level_t required_level = service->required_security_level;
3149     if (gap_get_secure_connections_only_mode() && (required_level != LEVEL_0)){
3150         if (gap_secure_connection(handle)){
3151             required_level = LEVEL_4;
3152         } else {
3153             l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CONNECTION_RESULT_SECURITY_BLOCK);
3154             return;
3155         }
3156     }
3157 
3158     // alloc structure
3159     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, hci_connection->address, BD_ADDR_TYPE_ACL,
3160     psm, service->mtu, required_level);
3161     if (!channel){
3162         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE);
3163         return;
3164     }
3165 
3166     channel->con_handle = handle;
3167     channel->remote_cid = source_cid;
3168     channel->remote_sig_id = sig_id;
3169 
3170     // limit local mtu to max acl packet length - l2cap header
3171     if (channel->local_mtu > l2cap_max_mtu()) {
3172         channel->local_mtu = l2cap_max_mtu();
3173     }
3174 
3175     // set initial state
3176     channel->state =     L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
3177     channel->state_var = L2CAP_CHANNEL_STATE_VAR_INCOMING;
3178 
3179     // add to connections list
3180     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
3181 
3182     //
3183     if (required_level > LEVEL_0){
3184         // send conn resp pending if remote supported features have not been received yet
3185         if (hci_remote_features_available(handle)) {
3186             l2cap_handle_remote_supported_features_received(channel);
3187         } else {
3188             channel->state_var |= L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND;
3189             hci_remote_features_query(handle);
3190         }
3191     } else {
3192         l2cap_handle_security_level_incoming_sufficient(channel);
3193     }
3194 }
3195 
3196 void l2cap_accept_connection(uint16_t local_cid){
3197     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
3198     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3199     if (!channel) {
3200         log_error("accept called but local_cid 0x%x not found", local_cid);
3201         return;
3202     }
3203 
3204 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3205     // configure L2CAP Basic mode
3206     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
3207 #endif
3208 
3209     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
3210 
3211     // process
3212     l2cap_run();
3213 }
3214 
3215 void l2cap_decline_connection(uint16_t local_cid){
3216     log_info("decline local_cid 0x%x", local_cid);
3217     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
3218     if (!channel) {
3219         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
3220         return;
3221     }
3222     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
3223     channel->reason = L2CAP_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE;
3224     l2cap_run();
3225 }
3226 
3227 // @pre command len is valid, see check in l2cap_signaling_handler_channel
3228 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
3229 
3230 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3231     uint8_t use_fcs = 1;
3232 #endif
3233 
3234     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
3235 
3236     uint16_t flags = little_endian_read_16(command, 6);
3237     if (flags & 1) {
3238         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
3239     }
3240 
3241     // accept the other's configuration options
3242     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3243     uint16_t pos     = 8;
3244     while (pos < end_pos){
3245         uint8_t option_hint = command[pos] >> 7;
3246         uint8_t option_type = command[pos] & 0x7f;
3247         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
3248         pos++;
3249         uint8_t length = command[pos++];
3250         // MTU { type(8): 1, len(8):2, MTU(16) }
3251         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) && (length == 2)){
3252             channel->remote_mtu = little_endian_read_16(command, pos);
3253             log_info("Remote MTU %u", channel->remote_mtu);
3254             if (channel->remote_mtu > l2cap_max_mtu()){
3255                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
3256                 channel->remote_mtu = l2cap_max_mtu();
3257             }
3258             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
3259         }
3260         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
3261         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT) && (length == 2)){
3262             channel->flush_timeout = little_endian_read_16(command, pos);
3263             log_info("Flush timeout: %u ms", channel->flush_timeout);
3264         }
3265 
3266 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3267         // Retransmission and Flow Control Option
3268         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
3269             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
3270             switch(channel->mode){
3271                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
3272                     // Store remote config
3273                     channel->remote_tx_window_size = command[pos+1];
3274                     channel->remote_max_transmit   = command[pos+2];
3275                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
3276                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
3277                     {
3278                         uint16_t remote_mps = little_endian_read_16(command, pos + 7);
3279                         // optimize our tx buffer configuration based on actual remote mps if remote mps is smaller than planned
3280                         if (remote_mps < channel->remote_mps){
3281                             // get current tx storage
3282                             uint16_t num_bytes_per_tx_buffer_before = sizeof(l2cap_ertm_tx_packet_state_t) + channel->remote_mps;
3283                             uint16_t tx_storage = channel->num_tx_buffers * num_bytes_per_tx_buffer_before;
3284 
3285                             channel->remote_mps = remote_mps;
3286                             uint16_t num_bytes_per_tx_buffer_now = sizeof(l2cap_ertm_tx_packet_state_t) + channel->remote_mps;
3287                             channel->num_tx_buffers = tx_storage / num_bytes_per_tx_buffer_now;
3288                             uint32_t total_storage = (sizeof(l2cap_ertm_rx_packet_state_t) + channel->local_mps) * channel->num_rx_buffers + tx_storage + channel->local_mtu;
3289                             l2cap_ertm_setup_buffers(channel, (uint8_t *) channel->rx_packets_state, total_storage);
3290                         }
3291                         // limit remote mtu by our tx buffers. Include 2 bytes SDU Length
3292                         uint16_t effective_mtu = channel->remote_mps * channel->num_tx_buffers - 2;
3293                         channel->remote_mtu    = btstack_min( effective_mtu, channel->remote_mtu);
3294                     }
3295                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
3296                         channel->remote_tx_window_size,
3297                         channel->remote_max_transmit,
3298                         channel->remote_retransmission_timeout_ms,
3299                         channel->remote_monitor_timeout_ms,
3300                         channel->remote_mps);
3301                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
3302                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3303                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3304                     } else {
3305                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
3306                     }
3307                     break;
3308                 case L2CAP_CHANNEL_MODE_BASIC:
3309                     switch (mode){
3310                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
3311                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
3312                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
3313                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3314                             }
3315                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
3316                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
3317                             break;
3318                         default: // case L2CAP_CHANNEL_MODE_BASIC:
3319                             // TODO store and evaluate configuration
3320                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
3321                             break;
3322                     }
3323                     break;
3324                 default:
3325                     break;
3326             }
3327         }
3328         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
3329             use_fcs = command[pos];
3330         }
3331 #endif
3332         // check for unknown options
3333         if ((option_hint == 0) && ((option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) || (option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE))){
3334             log_info("l2cap cid %u, unknown option 0x%02x", channel->local_cid, option_type);
3335             channel->unknown_option = option_type;
3336             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
3337         }
3338         pos += length;
3339     }
3340 
3341 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3342         // "FCS" has precedence over "No FCS"
3343         uint8_t update = channel->fcs_option || use_fcs;
3344         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
3345         channel->fcs_option = update;
3346         // If ERTM mandatory, but remote didn't send Retransmission and Flowcontrol options -> disconnect
3347         if (((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM) == 0) & (channel->ertm_mandatory)){
3348             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3349         }
3350 #endif
3351 }
3352 
3353 // @pre command len is valid, see check in l2cap_signaling_handler_channel
3354 static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint16_t result, uint8_t *command){
3355     log_info("l2cap_signaling_handle_configure_response");
3356 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3357     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3358     uint16_t pos     = 10;
3359     while (pos < end_pos){
3360         uint8_t option_hint = command[pos] >> 7;
3361         uint8_t option_type = command[pos] & 0x7f;
3362         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
3363         pos++;
3364         uint8_t length = command[pos++];
3365 
3366         // Retransmission and Flow Control Option
3367         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
3368             switch (channel->mode){
3369                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
3370                     if (channel->ertm_mandatory){
3371                         // ??
3372                     } else {
3373                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
3374                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
3375                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3376                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3377                         }
3378                     }
3379                     break;
3380                 case L2CAP_CHANNEL_MODE_BASIC:
3381                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
3382                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
3383                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3384                     }
3385                     break;
3386                 default:
3387                     break;
3388             }
3389         }
3390 
3391         // check for unknown options
3392         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
3393             log_info("l2cap cid %u, unknown option 0x%02x", channel->local_cid, option_type);
3394             channel->unknown_option = option_type;
3395             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
3396         }
3397 
3398         pos += length;
3399     }
3400 #else
3401     UNUSED(channel);  // ok: no code
3402     UNUSED(result);   // ok: no code
3403     UNUSED(command);  // ok: no code
3404 #endif
3405 }
3406 
3407 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
3408     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
3409     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
3410     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
3411     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
3412     if (channel->state == L2CAP_STATE_OPEN) return 0;
3413     return 1;
3414 }
3415 
3416 
3417 // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
3418 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
3419 
3420     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3421     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
3422     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3423     uint16_t result = 0;
3424 
3425     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
3426 
3427     // handle DISCONNECT REQUESTS seperately
3428     if (code == DISCONNECTION_REQUEST){
3429         l2cap_handle_disconnect_request(channel, identifier);
3430         return;
3431     }
3432 
3433     // @STATEMACHINE(l2cap)
3434     switch (channel->state) {
3435 
3436         case L2CAP_STATE_WAIT_CONNECT_RSP:
3437             switch (code){
3438                 case CONNECTION_RESPONSE:
3439                     if (cmd_len < 8){
3440                         // command imcomplete
3441                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3442                         break;
3443                     }
3444                     l2cap_stop_rtx(channel);
3445                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3446                     switch (result) {
3447                         case 0:
3448                             // successful connection
3449                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3450                             channel->state = L2CAP_STATE_CONFIG;
3451                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
3452                             break;
3453                         case 1:
3454                             // connection pending. get some coffee, but start the ERTX
3455                             l2cap_start_ertx(channel);
3456                             break;
3457                         default:
3458                             // channel closed
3459                             channel->state = L2CAP_STATE_CLOSED;
3460                             // map l2cap connection response result to BTstack status enumeration
3461                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
3462 
3463                             // drop link key if security block
3464                             if ((L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result) == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
3465                                 gap_drop_link_key_for_bd_addr(channel->address);
3466                             }
3467 
3468                             // discard channel
3469                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3470                             l2cap_free_channel_entry(channel);
3471                             break;
3472                     }
3473                     break;
3474 
3475                 default:
3476                     //@TODO: implement other signaling packets
3477                     break;
3478             }
3479             break;
3480 
3481         case L2CAP_STATE_CONFIG:
3482             switch (code) {
3483                 case CONFIGURE_REQUEST:
3484                     if (cmd_len < 4){
3485                         // command incomplete
3486                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3487                         break;
3488                     }
3489                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
3490                     l2cap_signaling_handle_configure_request(channel, command);
3491                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
3492                         // only done if continuation not set
3493                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
3494                     }
3495                     break;
3496                 case CONFIGURE_RESPONSE:
3497                     if (cmd_len < 6){
3498                         // command incomplete
3499                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3500                         break;
3501                     }
3502                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3503                     l2cap_stop_rtx(channel);
3504                     l2cap_signaling_handle_configure_response(channel, result, command);
3505                     switch (result){
3506                         case 0: // success
3507                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
3508                             break;
3509                         case 4: // pending
3510                             l2cap_start_ertx(channel);
3511                             break;
3512                         default:
3513 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3514                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
3515                                 // remote does not offer ertm but it's required
3516                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3517                                 break;
3518                             }
3519 #endif
3520                             // retry on negative result
3521                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
3522                             break;
3523                     }
3524                     break;
3525                 default:
3526                     break;
3527             }
3528             if (l2cap_channel_ready_for_open(channel)){
3529 
3530 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3531                 // assert that packet can be stored in fragment buffers in ertm
3532                 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3533                     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
3534                     uint16_t usable_mtu = channel->num_tx_buffers == 1 ? effective_mps : channel->num_tx_buffers * effective_mps - 2;
3535                     if (usable_mtu < channel->remote_mtu){
3536                         log_info("Remote MTU %u > max storable ERTM packet, only using MTU = %u", channel->remote_mtu, usable_mtu);
3537                         channel->remote_mtu = usable_mtu;
3538                     }
3539                 }
3540 #endif
3541                 // for open:
3542                 channel->state = L2CAP_STATE_OPEN;
3543                 l2cap_emit_channel_opened(channel, 0);
3544             }
3545             break;
3546 
3547         case L2CAP_STATE_WAIT_DISCONNECT:
3548             switch (code) {
3549                 case DISCONNECTION_RESPONSE:
3550                     l2cap_finalize_channel_close(channel);
3551                     break;
3552                 default:
3553                     //@TODO: implement other signaling packets
3554                     break;
3555             }
3556             break;
3557 
3558         case L2CAP_STATE_CLOSED:
3559             // @TODO handle incoming requests
3560             break;
3561 
3562         case L2CAP_STATE_OPEN:
3563             //@TODO: implement other signaling packets, e.g. re-configure
3564             break;
3565         default:
3566             break;
3567     }
3568     // log_info("new state %u", channel->state);
3569 }
3570 
3571 #ifdef ENABLE_CLASSIC
3572 static void l2cap_handle_information_request_complete(hci_connection_t * connection){
3573 
3574     connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
3575 
3576     // emit event
3577     uint8_t event[8];
3578     event[0] = L2CAP_EVENT_INFORMATION_RESPONSE;
3579     event[1] = sizeof(event) - 2;
3580     little_endian_store_16(event, 2, connection->con_handle);
3581     little_endian_store_16(event, 4, connection->l2cap_state.extended_feature_mask);
3582     little_endian_store_16(event, 6, connection->l2cap_state.fixed_channels_supported);
3583     l2cap_emit_event(event, sizeof(event));
3584 
3585     // trigger connection request
3586     btstack_linked_list_iterator_t it;
3587     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3588     while (btstack_linked_list_iterator_has_next(&it)){
3589         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3590         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3591         if (channel->con_handle != connection->con_handle) continue;
3592 
3593         // incoming connection: information request was triggered after user has accepted connection,
3594         // now: verify channel configuration, esp. if ertm will be mandatory
3595         if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
3596             // default: continue
3597             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
3598 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3599             if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
3600                 // ERTM not possible, select basic mode and release buffer
3601                 channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3602                 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3603 
3604                 // bail if ERTM is mandatory
3605                 if (channel->ertm_mandatory){
3606                     // We chose 'no resources available' for "ERTM mandatory but you don't even know ERTM exists"
3607                     log_info("ERTM mandatory -> reject connection");
3608                     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
3609                     channel->reason = L2CAP_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE;
3610                 }  else {
3611                     log_info("ERTM not supported by remote -> use Basic mode");
3612                 }
3613             }
3614 #endif
3615             continue;
3616         }
3617 
3618         // outgoing connection: information request is triggered before connection request
3619         if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
3620 
3621 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3622             // if ERTM was requested, but is not listed in extended feature mask:
3623             if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
3624 
3625                 if (channel->ertm_mandatory){
3626                     // bail if ERTM is mandatory
3627                     channel->state = L2CAP_STATE_CLOSED;
3628                     // map l2cap connection response result to BTstack status enumeration
3629                     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
3630                     // discard channel
3631                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3632                     l2cap_free_channel_entry(channel);
3633                     continue;
3634 
3635                 } else {
3636                     // fallback to Basic mode
3637                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3638                     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3639                 }
3640             }
3641 #endif
3642 
3643             // respond to connection request
3644             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
3645             continue;
3646         }
3647     }
3648 }
3649 #endif
3650 
3651 // @pre command len is valid, see check in l2cap_acl_classic_handler
3652 static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
3653 
3654     hci_connection_t * connection;
3655     btstack_linked_list_iterator_t it;
3656 
3657     // get code, signal identifier and command len
3658     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3659     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
3660     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3661 
3662     // general commands without an assigned channel
3663     switch(code) {
3664 
3665         case CONNECTION_REQUEST:
3666             if (cmd_len == 4){
3667                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3668                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3669                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
3670             } else {
3671                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3672             }
3673             return;
3674 
3675         case ECHO_REQUEST:
3676             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
3677             return;
3678 
3679         case INFORMATION_REQUEST:
3680             if (cmd_len == 2) {
3681                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3682                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
3683                 return;
3684             }
3685             break;
3686 
3687         case INFORMATION_RESPONSE:
3688             connection = hci_connection_for_handle(handle);
3689             if (!connection) return;
3690             switch (connection->l2cap_state.information_state){
3691                 case L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE:
3692                     // get extended features from response if valid
3693                     if (cmd_len >= 6) {
3694                         uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3695                         uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3696                         if (result == 0 && info_type == L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) {
3697                             connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3698                         }
3699                         log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
3700                         if ((connection->l2cap_state.extended_feature_mask & 0x80) != 0){
3701                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_FIXED_CHANNELS_REQUEST;
3702                         } else {
3703                             // information request complete
3704                             l2cap_handle_information_request_complete(connection);
3705                         }
3706                     }
3707                     break;
3708                 case L2CAP_INFORMATION_STATE_W4_FIXED_CHANNELS_RESPONSE:
3709                     if (cmd_len >= 12) {
3710                         uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3711                         uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3712                         if (result == 0 && info_type == L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED) {
3713                             connection->l2cap_state.fixed_channels_supported = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3714                         }
3715                         log_info("fixed channels mask 0x%02x", connection->l2cap_state.fixed_channels_supported);
3716                         // information request complete
3717                         l2cap_handle_information_request_complete(connection);
3718                     }
3719                     break;
3720                 default:
3721                     break;
3722             }
3723             return;
3724 
3725 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
3726         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
3727         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
3728         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
3729         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
3730             l2cap_ecbm_signaling_handler_dispatch(handle, L2CAP_CID_SIGNALING, command, sig_id);
3731             return;
3732         case L2CAP_FLOW_CONTROL_CREDIT_INDICATION:
3733             // return if valid
3734             if (l2cap_credit_based_handle_credit_indication(handle, command, cmd_len)) return;
3735             break;
3736 
3737         case COMMAND_REJECT:
3738             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3739             while (btstack_linked_list_iterator_has_next(&it)) {
3740                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3741                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3742                 if (channel->con_handle != handle) continue;
3743                 if (channel->local_sig_id != sig_id) continue;
3744                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE) continue;
3745 
3746                 // open failed
3747                 channel->state = L2CAP_STATE_CLOSED;
3748                 l2cap_ecbm_emit_channel_opened(channel,
3749                                                ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES);
3750                 // drop failed channel
3751                 btstack_linked_list_iterator_remove(&it);
3752                 l2cap_free_channel_entry(channel);
3753             }
3754             break;
3755 #endif
3756 
3757         default:
3758             break;
3759     }
3760 
3761     if (cmd_len >= 2){
3762         // Get potential destination CID
3763         uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3764 
3765         // Find channel for this sig_id and connection handle
3766         btstack_linked_list_iterator_init(&it, &l2cap_channels);
3767         while (btstack_linked_list_iterator_has_next(&it)){
3768             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3769             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3770             if (channel->con_handle != handle) continue;
3771             if (code & 1) {
3772                 // match odd commands (responses) by previous signaling identifier
3773                 if (channel->local_sig_id == sig_id) {
3774                     l2cap_signaling_handler_channel(channel, command);
3775                     return;
3776                 }
3777             } else {
3778                 // match even commands (requests) by local channel id
3779                 if (channel->local_cid == dest_cid) {
3780                     l2cap_signaling_handler_channel(channel, command);
3781                     return;
3782                 }
3783             }
3784         }
3785     }
3786 
3787     // If dynamic channel cannot be found, either never set-up or already finalized, assume state CLOSED
3788     // Handle events as described in Core 5.4, Vol 3. Host, 6.1.1 CLOSED state
3789     switch (code){
3790         case CONNECTION_RESPONSE:
3791         case CONFIGURE_RESPONSE:
3792         case DISCONNECTION_RESPONSE:
3793             // Ignore request
3794             return;
3795         case DISCONNECTION_REQUEST:
3796             if (cmd_len == 4){
3797                 // send disconnect response for received dest and source cids
3798                 uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3799                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3800                 l2cap_register_signaling_response(handle, DISCONNECTION_RESPONSE, sig_id, source_cid, dest_cid);
3801                 return;
3802             }
3803             break;
3804         case CONFIGURE_REQUEST:
3805             if (cmd_len >= 2){
3806                 // send command reject with reason invalid cid
3807                 uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3808                 l2cap_register_signaling_response(handle, CONFIGURE_REQUEST, sig_id, dest_cid, L2CAP_REJ_INVALID_CID);
3809                 return;
3810             }
3811             break;
3812         default:
3813             break;
3814     }
3815     // otherwise send command reject with reason unknown command
3816     l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3817 }
3818 #endif
3819 
3820 #ifdef L2CAP_USES_CHANNELS
3821 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3822     btstack_linked_list_iterator_t it;
3823     btstack_linked_list_iterator_init(&it, services);
3824     while (btstack_linked_list_iterator_has_next(&it)){
3825         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
3826         if ( service->psm == psm){
3827             return service;
3828         };
3829     }
3830     return NULL;
3831 }
3832 #endif
3833 
3834 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
3835 
3836 static uint8_t l2cap_ecbm_setup_channels(btstack_linked_list_t * channels,
3837                                          btstack_packet_handler_t packet_handler, uint8_t num_channels,
3838                                          hci_connection_t * connection, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
3839     uint8_t i;
3840     uint8_t status = ERROR_CODE_SUCCESS;
3841     for (i=0;i<num_channels;i++){
3842         l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_ECBM, connection->address, connection->address_type, psm, mtu, security_level);
3843         if (!channel) {
3844             status = BTSTACK_MEMORY_ALLOC_FAILED;
3845             break;
3846         }
3847         channel->con_handle = connection->con_handle;
3848         btstack_linked_list_add_tail(channels, (btstack_linked_item_t *) channel);
3849     }
3850 
3851     // free channels if not all allocated
3852     if (status != ERROR_CODE_SUCCESS){
3853         while (true) {
3854             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_pop(channels);
3855             if (channel == NULL) break;
3856             l2cap_free_channel_entry(channel);
3857         }
3858     }
3859 
3860     return status;
3861 }
3862 
3863 static inline l2cap_service_t * l2cap_ecbm_get_service(uint16_t spsm){
3864     return l2cap_get_service_internal(&l2cap_enhanced_services, spsm);
3865 }
3866 
3867 static inline uint8_t l2cap_ecbm_status_for_result(uint16_t result) {
3868     switch (result) {
3869         case L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS:
3870             return ERROR_CODE_SUCCESS;
3871         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_SPSM_NOT_SUPPORTED:
3872             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_PSM;
3873         case L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INSUFFICIENT_RESOURCES_AVAILABLE:
3874             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_RESOURCES;
3875         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHENTICATION:
3876         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHORIZATION:
3877         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_ENCYRPTION_KEY_SIZE_TOO_SHORT:
3878         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_ENCRYPTION:
3879             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY;
3880         default:
3881             // invalid Source CID, Source CID already allocated, unacceptable parameters
3882             return L2CAP_CONNECTION_RESPONSE_UNKNOWN_ERROR;
3883     }
3884 }
3885 
3886 static void
3887 l2cap_ecbm_emit_incoming_connection(l2cap_channel_t *channel, uint8_t num_channels) {
3888     uint8_t event[16];
3889     event[0] = L2CAP_EVENT_ECBM_INCOMING_CONNECTION;
3890     event[1] = sizeof(event) - 2;
3891     event[2] = channel->address_type;
3892     reverse_bd_addr(channel->address, &event[3]);
3893     little_endian_store_16(event, 9, channel->con_handle);
3894     little_endian_store_16(event, 11, channel->psm);
3895     event[13] = num_channels;
3896     little_endian_store_16(event, 14, channel->local_cid);
3897     hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
3898     (*channel->packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
3899 }
3900 
3901 static uint8_t
3902 l2cap_ecbm_security_status_for_connection_request(hci_con_handle_t handle, gap_security_level_t required_security_level,
3903                                                   bool requires_authorization) {
3904     // check security in increasing error priority
3905     uint8_t security_status = L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS;
3906 
3907     // security: check encryption
3908     if (required_security_level >= LEVEL_2) {
3909         if (gap_encryption_key_size(handle) < 16) {
3910             security_status = L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_ENCYRPTION_KEY_SIZE_TOO_SHORT;
3911         }
3912         if (gap_encryption_key_size(handle) == 0){
3913             security_status = L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_ENCRYPTION;
3914         }
3915     }
3916 
3917     // security: check authentication
3918     if (required_security_level >= LEVEL_3) {
3919         if (!gap_authenticated(handle)) {
3920             security_status = requires_authorization ?
3921                     L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHORIZATION :
3922                     L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHENTICATION;
3923         }
3924     }
3925     return security_status;
3926 }
3927 
3928 static void l2cap_ecbm_handle_security_level_incoming(l2cap_channel_t * channel){
3929     // count number of l2cap_channels in state L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE with same remote_sig_id
3930     uint8_t sig_id = channel->remote_sig_id;
3931     hci_con_handle_t con_handle = channel->con_handle;
3932 
3933     uint8_t security_status = l2cap_ecbm_security_status_for_connection_request(channel->con_handle,
3934                                                                                 channel->required_security_level,
3935                                                                                 false);
3936     bool security_sufficient = security_status == L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS;
3937 
3938     uint8_t num_channels = 0;
3939     btstack_linked_list_iterator_t it;
3940     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3941     while (btstack_linked_list_iterator_has_next(&it)) {
3942         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3943         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3944         if (channel->con_handle != con_handle) continue;
3945         if (channel->remote_sig_id != sig_id) continue;
3946         if (channel->state != L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE) continue;
3947         num_channels++;
3948 
3949         if (security_sufficient){
3950             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
3951         } else {
3952             btstack_linked_list_iterator_remove(&it);
3953             btstack_memory_l2cap_channel_free(channel);
3954         }
3955     }
3956 
3957     if (security_sufficient){
3958         l2cap_ecbm_emit_incoming_connection(channel, num_channels);
3959     } else {
3960         // combine signaling cid and number channels for l2cap_register_signaling_response
3961         uint16_t signaling_cid = L2CAP_CID_SIGNALING;
3962         uint16_t num_channels_and_signaling_cid = (num_channels << 8) | signaling_cid;
3963         l2cap_register_signaling_response(con_handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3964                                           num_channels_and_signaling_cid, security_status);
3965     }
3966 }
3967 
3968 void l2cap_ecbm_trigger_pending_connection_responses(hci_con_handle_t con_handle){
3969     bool done = false;
3970     while (!done) {
3971         done = true;
3972         btstack_linked_list_iterator_t it;
3973         btstack_linked_list_iterator_init(&it, &l2cap_channels);
3974         while (btstack_linked_list_iterator_has_next(&it)) {
3975             l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3976             if (channel->channel_type != L2CAP_CHANNEL_TYPE_CHANNEL_ECBM) continue;
3977             if (channel->con_handle != con_handle) continue;
3978             if  (channel->state == L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE) {
3979                 l2cap_ecbm_handle_security_level_incoming(channel);
3980                 done = false;
3981             };
3982         }
3983     }
3984 }
3985 
3986 static int l2cap_ecbm_signaling_handler_dispatch(hci_con_handle_t handle, uint16_t signaling_cid, uint8_t *command,
3987                                                  uint8_t sig_id) {
3988 
3989     hci_connection_t *connection;
3990     btstack_linked_list_iterator_t it;
3991     l2cap_service_t *service;
3992     uint16_t spsm;
3993     uint8_t num_channels;
3994     uint16_t num_channels_and_signaling_cid;
3995     uint8_t i;
3996     uint16_t new_mtu;
3997     uint16_t new_mps;
3998     uint16_t initial_credits;
3999     uint16_t result;
4000     uint8_t status;
4001 
4002     uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
4003     uint16_t len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
4004     log_info("enhanced dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
4005 
4006     switch (code) {
4007         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
4008             // check size
4009             if (len < 10u) return 0u;
4010 
4011             // get hci connection, bail if not found (must not happen)
4012             connection = hci_connection_for_handle(handle);
4013             btstack_assert(connection != NULL);
4014 
4015             // get num channels to establish
4016             num_channels = (len - 8) / sizeof(uint16_t);
4017 
4018             // combine signaling cid and number channels for l2cap_register_signaling_response
4019             num_channels_and_signaling_cid = (num_channels << 8) | signaling_cid;
4020 
4021             // check if service registered
4022             spsm = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
4023             service = l2cap_ecbm_get_service(spsm);
4024 
4025             if (service) {
4026 
4027                 uint16_t remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
4028                 uint16_t remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
4029                 uint16_t credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
4030 
4031                 // param: check remote mtu
4032                 if (service->mtu > remote_mtu) {
4033                     l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
4034                                                       num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INVALID_PARAMETERS);
4035                     return 1;
4036                 }
4037 
4038                 // check if authentication is required and possible
4039                 bool send_pending = false;
4040                 uint8_t security_status = l2cap_ecbm_security_status_for_connection_request(handle,
4041                                                                                             service->required_security_level,
4042                                                                                             service->requires_authorization);
4043                 if (security_status != L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS) {
4044                     if (gap_get_bondable_mode() != 0) {
4045                         // if possible, send pending and continue
4046                         send_pending = true;
4047                     } else {
4048                         // otherwise, send refused and abort
4049                         l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
4050                                                           num_channels_and_signaling_cid, security_status);
4051                         return 1;
4052                     }
4053                 }
4054 
4055                 // report the last result code != 0
4056                 result = 0;
4057                 // store one of the local channels for the event
4058                 l2cap_channel_t * a_channel = NULL;
4059                 for (i = 0; i < num_channels; i++) {
4060 
4061                     // check source cids
4062                     uint16_t source_cid = little_endian_read_16(command, 12 + (i * 2));
4063                     if (source_cid < 0x40u) {
4064                         result = L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INVALID_SOURCE_CID;
4065                         continue;
4066                     }
4067 
4068                     // go through list of channels for this ACL connection and check if we get a match
4069                     btstack_linked_list_iterator_init(&it, &l2cap_channels);
4070                     bool source_cid_allocated = false;
4071                     while (btstack_linked_list_iterator_has_next(&it)) {
4072                         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4073                         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4074                         if (channel->con_handle != handle) continue;
4075                         if (channel->remote_cid != source_cid) continue;
4076                         source_cid_allocated = true;
4077                         break;
4078                     }
4079                     if (source_cid_allocated) {
4080                         result = 0x00a;
4081                         continue;
4082                     }
4083 
4084                     // setup channel
4085                     l2cap_channel_t *channel = l2cap_create_channel_entry(service->packet_handler,
4086                                                                           L2CAP_CHANNEL_TYPE_CHANNEL_ECBM,
4087                                                                           connection->address,
4088                                                                           connection->address_type, spsm,
4089                                                                           service->mtu,
4090                                                                           service->required_security_level);
4091 
4092                     if (channel == NULL) {
4093                         // Some connections refused – insufficient resources available
4094                         result = 0x004;
4095                         continue;
4096                     }
4097 
4098                     // setup state
4099                     channel->state = L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
4100                     channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
4101                     channel->con_handle = connection->con_handle;
4102                     channel->remote_sig_id = sig_id;
4103                     channel->remote_cid = source_cid;
4104                     channel->remote_mtu = remote_mtu;
4105                     channel->remote_mps = remote_mps;
4106                     channel->credits_outgoing = credits_outgoing;
4107                     channel->cid_index = i;
4108                     channel->num_cids = num_channels;
4109 
4110                     // if more than one error, we can report any of them
4111                     channel->reason = result;
4112 
4113                     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
4114 
4115                     a_channel = channel;
4116                 }
4117 
4118                 // if no channels have been created, all have been refused, and we can respond right away
4119                 if (a_channel == NULL) {
4120                     l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
4121                                                       num_channels_and_signaling_cid, result);
4122                     return 1;
4123                 }
4124 
4125                 // if security is pending, send intermediate response, otherwise, ask user
4126                 if (send_pending){
4127                     l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
4128                                                       num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_PENDING_AUTHENTICATION);
4129                 } else {
4130                     // if security is ok but authorization is required, send intermediate response and ask user
4131                     if (service->requires_authorization){
4132                         l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
4133                                                           num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_PENDING_AUTHORIZATION);
4134                     }
4135                     l2cap_ecbm_handle_security_level_incoming(a_channel);
4136                 }
4137 
4138             } else {
4139                 l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
4140                                                   num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_SPSM_NOT_SUPPORTED);
4141             }
4142             return 1;
4143 
4144         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
4145             // check size
4146             if (len < 10u) return 0u;
4147 
4148             // get hci connection, ignore if not found
4149             connection = hci_connection_for_handle(handle);
4150             if (connection == NULL) return 0;
4151 
4152             // get channel config: mtu, mps, initial credits, result
4153             new_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4154             new_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
4155             initial_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
4156             result = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
4157             status = l2cap_ecbm_status_for_result(result);
4158 
4159             // get num channels to modify
4160             num_channels = (len - 8) / sizeof(uint16_t);
4161             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4162             while (btstack_linked_list_iterator_has_next(&it)) {
4163                 uint8_t channel_status = status;
4164                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4165                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4166                 if (channel->con_handle != handle) continue;
4167                 if (channel->local_sig_id != sig_id) continue;
4168                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE) continue;
4169                 if (channel->cid_index < num_channels) {
4170                     uint16_t remote_cid = little_endian_read_16(command, 12 + channel->cid_index * sizeof(uint16_t));
4171                     if (remote_cid != 0) {
4172                         // check for duplicate remote CIDs
4173                         l2cap_channel_t * original_channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
4174                         if (original_channel == NULL){
4175                             channel->state = L2CAP_STATE_OPEN;
4176                             channel->remote_cid = remote_cid;
4177                             channel->remote_mtu = new_mtu;
4178                             channel->remote_mps = new_mps;
4179                             channel->credits_outgoing = initial_credits;
4180                             l2cap_ecbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
4181                             continue;
4182                         }
4183                         // close original channel
4184                         original_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4185                         channel_status = ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
4186                     }
4187                 }
4188                 // open failed
4189                 l2cap_ecbm_emit_channel_opened(channel, channel_status);
4190                 // drop failed channel
4191                 btstack_linked_list_iterator_remove(&it);
4192                 btstack_memory_l2cap_channel_free(channel);
4193             }
4194             return 1;
4195 
4196         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
4197             // check minimal size
4198             if (len < 6) return 0u;
4199 
4200             // get hci connection, bail if not found (must not happen)
4201             connection = hci_connection_for_handle(handle);
4202             btstack_assert(connection != NULL);
4203 
4204             // get num channels to modify
4205             num_channels = (len - 4) / sizeof(uint16_t);
4206 
4207             // get new mtu and mps
4208             new_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4209             new_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
4210 
4211             // validate request
4212             result = 0;
4213             for (i = 0; i < num_channels; i++) {
4214                 // check cid
4215                 uint16_t remote_cid = little_endian_read_16(command, 8 + (i * sizeof(uint16_t)));
4216                 l2cap_channel_t *channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
4217                 if (channel == NULL) {
4218                     result = L2CAP_ECBM_RECONFIGURE_FAILED_DESTINATION_CID_INVALID;
4219                     break;
4220                 }
4221                 // check MTU is not reduced
4222                 if (channel->remote_mtu > new_mtu) {
4223                     result = L2CAP_ECBM_RECONFIGURE_FAILED_MTU_REDUCTION_NOT_ALLOWED;
4224                     break;
4225                 }
4226                 // check MPS reduction
4227                 if ((num_channels > 1) && (channel->remote_mps > new_mps)) {
4228                     result = L2CAP_ECBM_RECONFIGURE_FAILED_MPS_REDUCTION_MULTIPLE_CHANNELS;
4229                     break;
4230                 }
4231                 // check MPS valid
4232                 if (new_mps < l2cap_enhanced_mps_min) {
4233                     result = L2CAP_ECBM_RECONFIGURE_FAILED_UNACCEPTABLE_PARAMETERS;
4234                     break;
4235                 }
4236             }
4237 
4238             // send reject
4239             if (result != 0) {
4240                 l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST, sig_id, signaling_cid,
4241                                                   result);
4242                 return 1;
4243             }
4244 
4245             // update channels
4246             for (i = 0; i < num_channels; i++) {
4247                 uint16_t remote_cid = little_endian_read_16(command, 8 + (i * sizeof(uint16_t)));
4248                 l2cap_channel_t *channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
4249                 channel->remote_mps = new_mps;
4250                 channel->remote_mtu = new_mtu;
4251                 // emit event
4252                 uint8_t event[8];
4253                 event[0] = L2CAP_EVENT_ECBM_RECONFIGURED;
4254                 event[1] = sizeof(event) - 2;
4255                 little_endian_store_16(event, 2, channel->local_cid);
4256                 little_endian_store_16(event, 4, new_mtu);
4257                 little_endian_store_16(event, 6, new_mps);
4258                 l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
4259             }
4260 
4261             // send accept
4262             l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST, sig_id, signaling_cid, 0);
4263             return 1;
4264 
4265         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
4266             // check size
4267             if (len < 2u) return 0u;
4268 
4269             result = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4270             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4271             while (btstack_linked_list_iterator_has_next(&it)) {
4272                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4273                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4274                 if (channel->con_handle != handle) continue;
4275                 if (channel->local_sig_id != sig_id) continue;
4276                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_RENEGOTIATION_RESPONSE) continue;
4277                 // complete request
4278                 if (result == 0) {
4279                     channel->receive_sdu_buffer = channel->renegotiate_sdu_buffer;
4280                     channel->local_mtu = channel->renegotiate_mtu;
4281                 }
4282                 channel->state = L2CAP_STATE_OPEN;
4283                 // emit event
4284                 l2cap_ecbm_emit_reconfigure_complete(channel, result);
4285             }
4286             break;
4287 
4288         default:
4289             btstack_unreachable();
4290             break;
4291     }
4292     return 0;
4293 }
4294 
4295 #endif
4296 
4297 #ifdef ENABLE_BLE
4298 
4299 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
4300     uint8_t event[6];
4301     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
4302     event[1] = 4;
4303     little_endian_store_16(event, 2, con_handle);
4304     little_endian_store_16(event, 4, result);
4305     l2cap_emit_event(event, sizeof(event));
4306 }
4307 
4308 // @return valid
4309 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
4310     hci_connection_t * connection;
4311     uint16_t result;
4312     uint8_t  event[12];
4313 
4314 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4315     l2cap_channel_t * channel;
4316     btstack_linked_list_iterator_t it;
4317 #endif
4318 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4319     uint16_t local_cid;
4320     uint16_t le_psm;
4321     l2cap_service_t * service;
4322     uint16_t source_cid;
4323 #endif
4324 
4325     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
4326     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
4327     log_info("le dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
4328 
4329     switch (code){
4330 
4331         case CONNECTION_PARAMETER_UPDATE_REQUEST:
4332             // check size
4333             if (len < 8u) return 0u;
4334             connection = hci_connection_for_handle(handle);
4335             if (connection != NULL){
4336                 if (connection->role != HCI_ROLE_MASTER){
4337                     // reject command without notifying upper layer when not in master role
4338                     return 0;
4339                 }
4340                 le_connection_parameter_range_t existing_range;
4341                 gap_get_connection_parameter_range(&existing_range);
4342                 uint16_t le_conn_interval_min   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
4343                 uint16_t le_conn_interval_max   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
4344                 uint16_t le_conn_latency        = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
4345                 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
4346 
4347                 int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
4348                 if (update_parameter){
4349                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
4350                     connection->le_conn_interval_min = le_conn_interval_min;
4351                     connection->le_conn_interval_max = le_conn_interval_max;
4352                     connection->le_conn_latency = le_conn_latency;
4353                     connection->le_supervision_timeout = le_supervision_timeout;
4354                 } else {
4355                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
4356                 }
4357                 connection->le_con_param_update_identifier = sig_id;
4358             }
4359 
4360             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
4361             event[1] = 10;
4362             little_endian_store_16(event, 2, handle);
4363             (void)memcpy(&event[4], &command[4], 8);
4364             l2cap_emit_event(event, sizeof(event));
4365             break;
4366 
4367         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
4368             // check size
4369             if (len < 2u) return 0u;
4370             result = little_endian_read_16(command, 4);
4371             l2cap_emit_connection_parameter_update_response(handle, result);
4372             break;
4373 
4374 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
4375         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
4376         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
4377         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
4378         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
4379             return l2cap_ecbm_signaling_handler_dispatch(handle, L2CAP_CID_SIGNALING_LE, command, sig_id);
4380 #endif
4381 
4382 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4383         case COMMAND_REJECT:
4384             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4385             while (btstack_linked_list_iterator_has_next(&it)){
4386                 channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4387                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4388                 if (channel->con_handle   != handle) continue;
4389                 if (channel->local_sig_id != sig_id) continue;
4390 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4391                 // if received while waiting for le connection response, assume legacy device
4392                 if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
4393                     channel->state = L2CAP_STATE_CLOSED;
4394                     // no official value for this, use: Connection refused – LE_PSM not supported
4395                     l2cap_cbm_emit_channel_opened(channel, L2CAP_CBM_CONNECTION_RESULT_SPSM_NOT_SUPPORTED);
4396 
4397                     // discard channel
4398                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4399                     l2cap_free_channel_entry(channel);
4400                     continue;
4401                 }
4402 #endif
4403 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
4404                 // if received while waiting for le connection response, assume legacy device
4405                 if (channel->state == L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE){
4406                     channel->state = L2CAP_STATE_CLOSED;
4407                     // treat as SPSM not supported
4408                     l2cap_ecbm_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_PSM);
4409 
4410                     // discard channel
4411                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4412                     l2cap_free_channel_entry(channel);
4413                     continue;
4414                 }
4415 #endif
4416             }
4417             break;
4418 #endif
4419 
4420 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4421         case LE_CREDIT_BASED_CONNECTION_REQUEST:
4422             // check size
4423             if (len < 10u) return 0u;
4424 
4425             // get hci connection, bail if not found (must not happen)
4426             connection = hci_connection_for_handle(handle);
4427             if (!connection) return 0;
4428 
4429             // check if service registered
4430             le_psm  = little_endian_read_16(command, 4);
4431             service = l2cap_cbm_get_service(le_psm);
4432             source_cid = little_endian_read_16(command, 6);
4433 
4434             if (service){
4435                 if (source_cid < 0x40u){
4436                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INVALID_SOURCE_CID);
4437                     return 1;
4438                 }
4439 
4440                 // go through list of channels for this ACL connection and check if we get a match
4441                 btstack_linked_list_iterator_init(&it, &l2cap_channels);
4442                 while (btstack_linked_list_iterator_has_next(&it)){
4443                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4444                     if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
4445                     if (a_channel->con_handle != handle) continue;
4446                     if (a_channel->remote_cid != source_cid) continue;
4447                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_SOURCE_CID_ALREADY_ALLOCATED);
4448                     return 1;
4449                 }
4450 
4451                 // security: check encryption
4452                 if (service->required_security_level >= LEVEL_2){
4453                     if (gap_encryption_key_size(handle) == 0){
4454                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_ENCRYPTION);
4455                         return 1;
4456                     }
4457                     // anything less than 16 byte key size is insufficient
4458                     if (gap_encryption_key_size(handle) < 16){
4459                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_ENCYRPTION_KEY_SIZE_TOO_SHORT);
4460                         return 1;
4461                     }
4462                 }
4463 
4464                 // security: check authentication
4465                 if (service->required_security_level >= LEVEL_3){
4466                     if (!gap_authenticated(handle)){
4467                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHENTICATION);
4468                         return 1;
4469                     }
4470                 }
4471 
4472                 // security: check authorization
4473                 if (service->required_security_level >= LEVEL_4){
4474                     if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
4475                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHORIZATION);
4476                         return 1;
4477                     }
4478                 }
4479 
4480                 // allocate channel
4481                 channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_CBM, connection->address,
4482                                                      connection->address_type, le_psm, service->mtu, service->required_security_level);
4483                 if (!channel){
4484                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE);
4485                     return 1;
4486                 }
4487 
4488                 channel->con_handle = handle;
4489                 channel->remote_cid = source_cid;
4490                 channel->remote_sig_id = sig_id;
4491                 channel->remote_mtu = little_endian_read_16(command, 8);
4492                 channel->remote_mps = little_endian_read_16(command, 10);
4493                 channel->credits_outgoing = little_endian_read_16(command, 12);
4494 
4495                 // set initial state
4496                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
4497                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
4498 
4499                 // add to connections list
4500                 btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
4501 
4502                 // post connection request event
4503                 l2cap_cbm_emit_incoming_connection(channel);
4504 
4505             } else {
4506                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_SPSM_NOT_SUPPORTED);
4507             }
4508             break;
4509 
4510         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
4511             // check size
4512             if (len < 10u) return 0u;
4513 
4514             // Find channel for this sig_id and connection handle
4515             channel = NULL;
4516             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4517             while (btstack_linked_list_iterator_has_next(&it)){
4518                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4519                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
4520                 if (a_channel->con_handle   != handle) continue;
4521                 if (a_channel->local_sig_id != sig_id) continue;
4522                 channel = a_channel;
4523                 break;
4524             }
4525             if (!channel) break;
4526 
4527             // cid + 0
4528             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
4529             if (result){
4530                 channel->state = L2CAP_STATE_CLOSED;
4531                 uint8_t status = l2cap_cbm_status_for_result(result);
4532                 l2cap_cbm_emit_channel_opened(channel, status);
4533 
4534                 // discard channel
4535                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4536                 l2cap_free_channel_entry(channel);
4537                 break;
4538             }
4539 
4540             // success
4541             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4542             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
4543             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
4544             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
4545             channel->state = L2CAP_STATE_OPEN;
4546             l2cap_cbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
4547             break;
4548 #endif
4549 
4550 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4551         case L2CAP_FLOW_CONTROL_CREDIT_INDICATION:
4552             return l2cap_credit_based_handle_credit_indication(handle, command, len) ? 1 : 0;
4553 
4554         case DISCONNECTION_REQUEST:
4555             // check size
4556             if (len < 4u) return 0u;
4557 
4558             // find channel
4559             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4560             channel = l2cap_get_channel_for_local_cid_and_handle(local_cid, handle);
4561             if (!channel) {
4562                 l2cap_register_signaling_response(handle, DISCONNECTION_REQUEST, sig_id,
4563                                                   little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2), local_cid);
4564                 break;
4565             }
4566             channel->remote_sig_id = sig_id;
4567             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
4568             break;
4569 
4570         case DISCONNECTION_RESPONSE:
4571             // check size
4572             if (len < 4u) return 0u;
4573 
4574             // find channel
4575             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4576             channel = l2cap_get_channel_for_local_cid_and_handle(local_cid, handle);
4577             if (!channel) break;
4578             if (channel->local_sig_id == sig_id) {
4579                 if (channel->state == L2CAP_STATE_WAIT_DISCONNECT){
4580                     l2cap_finalize_channel_close(channel);
4581                 }
4582             }
4583             break;
4584 #endif
4585 
4586         default:
4587             // command unknown -> reject command
4588             return 0;
4589     }
4590     return 1;
4591 }
4592 #endif
4593 
4594 #ifdef ENABLE_CLASSIC
4595 static void l2cap_acl_classic_handler_for_channel(l2cap_channel_t * l2cap_channel, uint8_t * packet, uint16_t size){
4596 
4597     // forward data only in OPEN state
4598     if (l2cap_channel->state != L2CAP_STATE_OPEN) return;
4599 
4600 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4601     if (l2cap_channel->channel_type == L2CAP_CHANNEL_TYPE_CHANNEL_ECBM){
4602         l2cap_credit_based_handle_pdu(l2cap_channel, packet, size);
4603         return;
4604     }
4605 #endif
4606 
4607 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
4608     if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
4609 
4610         int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
4611 
4612         // assert control + FCS fields are inside
4613         if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) return;
4614 
4615         if (l2cap_channel->fcs_option){
4616             // verify FCS (required if one side requested it)
4617             uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
4618             uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
4619 
4620 #ifdef L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL
4621             // simulate fcs error
4622             static int counter = 0;
4623             if (++counter == L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL) {
4624                 log_info("Simulate fcs error");
4625                 fcs_calculated++;
4626                 counter = 0;
4627             }
4628 #endif
4629 
4630             if (fcs_calculated == fcs_packet){
4631                 log_info("Packet FCS 0x%04x verified", fcs_packet);
4632             } else {
4633                 log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
4634                 // ERTM State Machine in Bluetooth Spec does not handle 'I-Frame with invalid FCS'
4635                 return;
4636             }
4637         }
4638 
4639         // switch on packet type
4640         uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
4641         uint8_t  req_seq = (control >> 8) & 0x3f;
4642         int final = (control >> 7) & 0x01;
4643         if (control & 1){
4644             // S-Frame
4645             int poll  = (control >> 4) & 0x01;
4646             l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
4647             log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
4648             l2cap_ertm_tx_packet_state_t * tx_state;
4649             switch (s){
4650                 case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
4651                     log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
4652                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4653                     if (poll && final){
4654                         // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
4655                         log_error("P=F=1 in S-Frame");
4656                         break;
4657                     }
4658                     if (poll){
4659                         // check if we did request selective retransmission before <==> we have stored SDU segments
4660                         int i;
4661                         int num_stored_out_of_order_packets = 0;
4662                         for (i=0;i<l2cap_channel->num_rx_buffers;i++){
4663                             int index = l2cap_channel->rx_store_index + i;
4664                             if (index >= l2cap_channel->num_rx_buffers){
4665                                 index -= l2cap_channel->num_rx_buffers;
4666                             }
4667                             l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
4668                             if (!rx_state->valid) continue;
4669                             num_stored_out_of_order_packets++;
4670                         }
4671                         if (num_stored_out_of_order_packets){
4672                             l2cap_channel->send_supervisor_frame_selective_reject = 1;
4673                         } else {
4674                             l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
4675                         }
4676                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
4677                     }
4678                     if (final){
4679                         // Stop-MonitorTimer
4680                         l2cap_ertm_stop_monitor_timer(l2cap_channel);
4681                         // If UnackedFrames > 0 then Start-RetransTimer
4682                         if (l2cap_channel->unacked_frames){
4683                             l2cap_ertm_start_retransmission_timer(l2cap_channel);
4684                         }
4685                         // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
4686                         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4687                     }
4688                     break;
4689                 case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
4690                     log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
4691                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4692                     // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
4693                     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4694                     break;
4695                 case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
4696                     log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
4697                     break;
4698                 case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
4699                     log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
4700                     if (poll){
4701                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4702                     }
4703                     // find requested i-frame
4704                     tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
4705                     if (tx_state){
4706                         log_info("Retransmission for tx_seq %u requested", req_seq);
4707                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
4708                         tx_state->retransmission_requested = 1;
4709                         l2cap_channel->srej_active = 1;
4710                     }
4711                     break;
4712                 default:
4713                     break;
4714             }
4715         } else {
4716             // I-Frame
4717             // get control
4718             l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
4719             uint8_t tx_seq = (control >> 1) & 0x3f;
4720             log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
4721             log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
4722             log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
4723             l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4724             if (final){
4725                 // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
4726                 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4727             }
4728 
4729             // get SDU
4730             const uint8_t * payload_data = &packet[COMPLETE_L2CAP_HEADER+2];
4731             uint16_t        payload_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
4732 
4733             // assert SDU size is smaller or equal to our buffers
4734             uint16_t max_payload_size = 0;
4735             switch (sar){
4736                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
4737                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
4738                     // SDU Length + MPS
4739                     max_payload_size = l2cap_channel->local_mps + 2;
4740                     break;
4741                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
4742                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
4743                     max_payload_size = l2cap_channel->local_mps;
4744                     break;
4745                 default:
4746                     btstack_assert(false);
4747                     break;
4748             }
4749             if (payload_len > max_payload_size){
4750                 log_info("payload len %u > max payload %u -> drop packet", payload_len, max_payload_size);
4751                 return;
4752             }
4753 
4754             // check ordering
4755             if (l2cap_channel->expected_tx_seq == tx_seq){
4756                 log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
4757                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
4758                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
4759 
4760                 // process SDU
4761                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, payload_data, payload_len);
4762 
4763                 // process stored segments
4764                 while (true){
4765                     int index = l2cap_channel->rx_store_index;
4766                     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
4767                     if (!rx_state->valid) break;
4768 
4769                     log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
4770                     l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
4771                     l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
4772 
4773                     rx_state->valid = 0;
4774                     l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
4775 
4776                     // update rx store index
4777                     index++;
4778                     if (index >= l2cap_channel->num_rx_buffers){
4779                         index = 0;
4780                     }
4781                     l2cap_channel->rx_store_index = index;
4782                 }
4783 
4784                 //
4785                 l2cap_channel->send_supervisor_frame_receiver_ready = 1;
4786 
4787             } else {
4788                 int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
4789                 if (delta < 2){
4790                     // store segment
4791                     l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, payload_data, payload_len);
4792 
4793                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
4794                     l2cap_channel->send_supervisor_frame_selective_reject = 1;
4795                 } else {
4796                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
4797                     l2cap_channel->send_supervisor_frame_reject = 1;
4798                 }
4799             }
4800         }
4801         return;
4802     }
4803 #endif
4804 
4805     // check size
4806     uint16_t payload_size = size - COMPLETE_L2CAP_HEADER;
4807     if (l2cap_channel->local_mtu < payload_size) return;
4808 
4809     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], payload_size);
4810 }
4811 #endif
4812 
4813 static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
4814 #ifdef ENABLE_CLASSIC
4815     l2cap_channel_t * l2cap_channel;
4816     l2cap_fixed_channel_t * l2cap_fixed_channel;
4817 
4818     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
4819     uint8_t  broadcast_flag = READ_ACL_FLAGS(packet) >> 2;
4820     switch (channel_id) {
4821 
4822         case L2CAP_CID_SIGNALING: {
4823             if (broadcast_flag != 0) break;
4824             uint32_t command_offset = 8;
4825             while ((command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET) <= size) {
4826                 // assert signaling command is fully inside packet
4827                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
4828                 uint32_t next_command_offset = command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
4829                 if (next_command_offset > size){
4830                     log_error("signaling command incomplete -> drop");
4831                     break;
4832                 }
4833                 // handle signaling command
4834                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
4835                 // go to next command
4836                 command_offset = next_command_offset;
4837             }
4838             // handle incomplete packet
4839             if (command_offset < size) {
4840                 log_error("signaling command incomplete -> reject");
4841                 l2cap_register_signaling_response(handle, COMMAND_REJECT, 0, 0, L2CAP_REJ_CMD_UNKNOWN);
4842             }
4843             break;
4844         }
4845 
4846         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
4847             if (broadcast_flag == 0) break;
4848             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL);
4849             if (!l2cap_fixed_channel) break;
4850             if (!l2cap_fixed_channel->packet_handler) break;
4851             (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4852             break;
4853 
4854 #ifdef ENABLE_BLE
4855         case L2CAP_CID_BR_EDR_SECURITY_MANAGER:
4856             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_BR_EDR_SECURITY_MANAGER);
4857             if ((l2cap_fixed_channel == NULL) || (l2cap_fixed_channel->packet_handler == NULL)){
4858                 // Pairing Failed
4859                 l2cap_register_signaling_response(handle, (uint8_t) SM_PAIRING_FAILED, 0, L2CAP_CID_BR_EDR_SECURITY_MANAGER, SM_REASON_PAIRING_NOT_SUPPORTED);
4860             } else {
4861                 (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4862             }
4863             break;
4864 #endif
4865 
4866         default:
4867             if (broadcast_flag != 0) break;
4868             // Find channel for this channel_id and connection handle
4869             l2cap_channel = l2cap_get_channel_for_local_cid_and_handle(channel_id, handle);
4870             if (l2cap_channel != NULL){
4871                 l2cap_acl_classic_handler_for_channel(l2cap_channel, packet, size);
4872             }
4873             break;
4874     }
4875 #else
4876     UNUSED(handle); // ok: no code
4877     UNUSED(packet); // ok: no code
4878     UNUSED(size);   // ok: no code
4879 #endif
4880 }
4881 
4882 static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
4883 #ifdef ENABLE_BLE
4884 
4885     l2cap_fixed_channel_t * l2cap_fixed_channel;
4886 
4887 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4888     l2cap_channel_t * l2cap_channel;
4889 #endif
4890     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
4891     switch (channel_id) {
4892 
4893         case L2CAP_CID_SIGNALING_LE: {
4894             uint8_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
4895             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
4896             if ((COMPLETE_L2CAP_HEADER + 4u + len) > size) break;
4897             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
4898             if (!valid){
4899                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
4900             }
4901             break;
4902         }
4903 
4904         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
4905             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL);
4906             if (!l2cap_fixed_channel) break;
4907             if (!l2cap_fixed_channel->packet_handler) break;
4908             (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4909             break;
4910 
4911         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
4912             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
4913             if ((l2cap_fixed_channel == NULL) || (l2cap_fixed_channel->packet_handler == NULL)){
4914                 // Pairing Failed
4915                 l2cap_register_signaling_response(handle, (uint8_t) SM_PAIRING_FAILED, 0, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, SM_REASON_PAIRING_NOT_SUPPORTED);
4916             } else {
4917                 (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4918             }
4919             break;
4920 
4921         default:
4922 
4923 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4924             l2cap_channel = l2cap_get_channel_for_local_cid_and_handle(channel_id, handle);
4925             if (l2cap_channel != NULL) {
4926                 l2cap_credit_based_handle_pdu(l2cap_channel, packet, size);
4927             }
4928 #endif
4929             break;
4930     }
4931 #else
4932     UNUSED(handle); // ok: no code
4933     UNUSED(packet); // ok: no code
4934     UNUSED(size);   // ok: no code
4935 #endif
4936 }
4937 
4938 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
4939     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
4940     UNUSED(channel);        // ok: there is no channel
4941 
4942     // Assert full L2CAP header present
4943     if (size < COMPLETE_L2CAP_HEADER) return;
4944 
4945     // Dispatch to Classic or LE handler (SCO packets are not dispatched to L2CAP)
4946     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
4947     hci_connection_t *conn = hci_connection_for_handle(handle);
4948     if (!conn) return;
4949     if (conn->address_type == BD_ADDR_TYPE_ACL){
4950         l2cap_acl_classic_handler(handle, packet, size);
4951     } else {
4952         l2cap_acl_le_handler(handle, packet, size);
4953     }
4954 
4955     l2cap_run();
4956 }
4957 
4958 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
4959 void l2cap_register_fixed_channel(btstack_packet_handler_t packet_handler, uint16_t channel_id) {
4960     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
4961     if (!channel) return;
4962     channel->packet_handler = packet_handler;
4963 }
4964 
4965 #ifdef L2CAP_USES_CHANNELS
4966 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
4967 void l2cap_finalize_channel_close(l2cap_channel_t * channel){
4968     channel->state = L2CAP_STATE_CLOSED;
4969     l2cap_handle_channel_closed(channel);
4970     // discard channel
4971     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4972     l2cap_free_channel_entry(channel);
4973 }
4974 #endif
4975 
4976 #ifdef ENABLE_CLASSIC
4977 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
4978     return l2cap_get_service_internal(&l2cap_services, psm);
4979 }
4980 
4981 static void l2cap_update_minimal_security_level(void){
4982     // update minimal service security level
4983     gap_security_level_t minimal_level = LEVEL_1;
4984     btstack_linked_list_iterator_t it;
4985     btstack_linked_list_iterator_init(&it, &l2cap_services);
4986     while (btstack_linked_list_iterator_has_next(&it)){
4987         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
4988         if (service->required_security_level > minimal_level){
4989             minimal_level = service->required_security_level;
4990         };
4991     }
4992     gap_set_minimal_service_security_level(minimal_level);
4993 }
4994 
4995 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
4996 
4997     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
4998 
4999     // check for alread registered psm
5000     l2cap_service_t *service = l2cap_get_service(psm);
5001     if (service) {
5002         log_error("register: PSM %u already registered", psm);
5003         return L2CAP_SERVICE_ALREADY_REGISTERED;
5004     }
5005 
5006     // alloc structure
5007     service = btstack_memory_l2cap_service_get();
5008     if (!service) {
5009         log_error("register: no memory for l2cap_service_t");
5010         return BTSTACK_MEMORY_ALLOC_FAILED;
5011     }
5012 
5013     // fill in
5014     service->psm = psm;
5015     service->mtu = mtu;
5016     service->packet_handler = service_packet_handler;
5017     service->required_security_level = security_level;
5018 
5019     // add to services list
5020     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
5021 
5022     l2cap_update_minimal_security_level();
5023 
5024 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
5025     // enable page scan
5026     gap_connectable_control(1);
5027 #endif
5028 
5029 
5030     return ERROR_CODE_SUCCESS;
5031 }
5032 
5033 uint8_t l2cap_unregister_service(uint16_t psm){
5034 
5035     log_info("unregister psm 0x%x", psm);
5036 
5037     l2cap_service_t *service = l2cap_get_service(psm);
5038     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
5039     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
5040     btstack_memory_l2cap_service_free(service);
5041 
5042     l2cap_update_minimal_security_level();
5043 
5044 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
5045     // disable page scan when no services registered
5046     if (btstack_linked_list_empty(&l2cap_services)) {
5047         gap_connectable_control(0);
5048     }
5049 #endif
5050 
5051     return ERROR_CODE_SUCCESS;
5052 }
5053 #endif
5054 
5055 
5056 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
5057 
5058 static void l2cap_credit_based_send_pdu(l2cap_channel_t *channel) {
5059     btstack_assert(channel != NULL);
5060     btstack_assert(channel->send_sdu_buffer != NULL);
5061     btstack_assert(channel->credits_outgoing > 0);
5062 
5063     // send part of SDU
5064     hci_reserve_packet_buffer();
5065     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
5066     uint8_t *l2cap_payload = acl_buffer + 8;
5067     uint16_t pos = 0;
5068     if (!channel->send_sdu_pos) {
5069         // store SDU len
5070         channel->send_sdu_pos += 2u;
5071         little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
5072         pos += 2u;
5073     }
5074     uint16_t payload_size = btstack_min(channel->send_sdu_len + 2u - channel->send_sdu_pos, channel->remote_mps - pos);
5075     log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size,
5076              channel->credits_outgoing);
5077     (void) memcpy(&l2cap_payload[pos],
5078                   &channel->send_sdu_buffer[channel->send_sdu_pos - 2u],
5079                   payload_size); // -2 for virtual SDU len
5080     pos += payload_size;
5081     channel->send_sdu_pos += payload_size;
5082     l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
5083 
5084     channel->credits_outgoing--;
5085 
5086     // update state (mark SDU as done) before calling hci_send_acl_packet_buffer (trigger l2cap_le_send_pdu again)
5087     bool done = channel->send_sdu_pos >= (channel->send_sdu_len + 2u);
5088     if (done) {
5089         channel->send_sdu_buffer = NULL;
5090     }
5091 
5092     hci_send_acl_packet_buffer(8u + pos);
5093 
5094     if (done) {
5095         // send done event
5096         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_PACKET_SENT);
5097         // inform about can send now
5098         l2cap_credit_based_notify_channel_can_send(channel);
5099     }
5100 }
5101 
5102 static uint8_t l2cap_credit_based_send_data(l2cap_channel_t * channel, const uint8_t * data, uint16_t size){
5103 
5104     if (size > channel->remote_mtu){
5105         log_error("l2cap send, cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
5106         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
5107     }
5108 
5109     if (channel->send_sdu_buffer){
5110         log_info("l2cap send, cid 0x%02x, cannot send", channel->local_cid);
5111         return BTSTACK_ACL_BUFFERS_FULL;
5112     }
5113 
5114     channel->send_sdu_buffer = data;
5115     channel->send_sdu_len    = size;
5116     channel->send_sdu_pos    = 0;
5117 
5118     l2cap_notify_channel_can_send();
5119     return ERROR_CODE_SUCCESS;
5120 }
5121 
5122 static uint8_t l2cap_credit_based_provide_credits(uint16_t local_cid, uint16_t credits){
5123     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5124     if (!channel) {
5125         log_error("le credits no channel for cid 0x%02x", local_cid);
5126         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5127     }
5128 
5129     // check state
5130     if (channel->state != L2CAP_STATE_OPEN){
5131         log_error("le credits but channel 0x%02x not open yet", local_cid);
5132     }
5133 
5134     // ignore if set to automatic credits
5135     if (channel->automatic_credits) return ERROR_CODE_SUCCESS;
5136 
5137     // assert incoming credits + credits <= 0xffff
5138     uint32_t total_credits = channel->credits_incoming;
5139     total_credits += channel->new_credits_incoming;
5140     total_credits += credits;
5141     if (total_credits > 0xffffu){
5142         log_error("le credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
5143                   channel->new_credits_incoming, credits);
5144     }
5145 
5146     // set credits_granted
5147     channel->new_credits_incoming += credits;
5148 
5149     // go
5150     l2cap_run();
5151     return ERROR_CODE_SUCCESS;
5152 }
5153 
5154 static void l2cap_credit_based_send_credits(l2cap_channel_t *channel) {
5155     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
5156     channel->local_sig_id = l2cap_next_sig_id();
5157     uint16_t new_credits = channel->new_credits_incoming;
5158     channel->new_credits_incoming = 0;
5159     channel->credits_incoming += new_credits;
5160     uint16_t signaling_cid = channel->address_type == BD_ADDR_TYPE_ACL ? L2CAP_CID_SIGNALING : L2CAP_CID_SIGNALING_LE;
5161     l2cap_send_general_signaling_packet(channel->con_handle, signaling_cid, L2CAP_FLOW_CONTROL_CREDIT_INDICATION, channel->local_sig_id, channel->local_cid, new_credits);
5162 }
5163 
5164 // @return valid
5165 static bool l2cap_credit_based_handle_credit_indication(hci_con_handle_t handle, const uint8_t * command, uint16_t len){
5166     // check size
5167     if (len < 4u) return false;
5168 
5169     // find channel
5170     uint16_t remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
5171     l2cap_channel_t * channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
5172     if (!channel) {
5173         log_error("credit: no channel for handle 0x%04x/cid 0x%02x", handle, remote_cid);
5174         return true;
5175     }
5176     uint16_t new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
5177     uint16_t credits_before = channel->credits_outgoing;
5178     channel->credits_outgoing += new_credits;
5179     // check for credit overrun
5180     if (credits_before > channel->credits_outgoing) {
5181         log_error("credit: new credits caused overrrun for cid 0x%02x, disconnecting", channel->local_cid);
5182         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
5183         return true;
5184     }
5185     log_info("credit: %u credits for 0x%02x, now %u", new_credits, channel->local_cid, channel->credits_outgoing);
5186     l2cap_call_notify_channel_in_run = true;
5187     return true;
5188 }
5189 
5190 static void l2cap_credit_based_handle_pdu(l2cap_channel_t * l2cap_channel, const uint8_t * packet, uint16_t size){
5191     // ignore empty packets
5192     if (size == COMPLETE_L2CAP_HEADER) return;
5193 
5194     // credit counting
5195     if (l2cap_channel->credits_incoming == 0u){
5196         log_info("(e)CBM: packet received but no incoming credits");
5197         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
5198         return;
5199     }
5200     l2cap_channel->credits_incoming--;
5201 
5202     // automatic credits
5203     if ((l2cap_channel->credits_incoming < L2CAP_CREDIT_BASED_FLOW_CONTROL_MODE_AUTOMATIC_CREDITS_WATERMARK) && l2cap_channel->automatic_credits){
5204         l2cap_channel->new_credits_incoming = L2CAP_CREDIT_BASED_FLOW_CONTROL_MODE_AUTOMATIC_CREDITS_INCREMENT;
5205     }
5206 
5207     // first fragment
5208     uint16_t pos = 0;
5209     if (!l2cap_channel->receive_sdu_len){
5210         if (size < (COMPLETE_L2CAP_HEADER + 2)) return;
5211         uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
5212         if (sdu_len > l2cap_channel->local_mtu) {
5213             log_info("(e)CBM: packet received larger than MTU");
5214             l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
5215             return;
5216         }
5217         l2cap_channel->receive_sdu_len = sdu_len;
5218         l2cap_channel->receive_sdu_pos = 0;
5219         pos  += 2u;
5220         size -= 2u;
5221     }
5222 
5223     uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
5224 
5225     // check fragment_size
5226     if (fragment_size > l2cap_channel->local_mps) {
5227         log_info("(e)CBM: fragment larger than local MPS");
5228         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
5229         return;
5230     }
5231 
5232     // check sdu overrun
5233     if ((l2cap_channel->receive_sdu_pos + fragment_size) > l2cap_channel->receive_sdu_len){
5234         log_info("(e)CBM: fragments larger than SDU");
5235         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
5236         return;
5237     }
5238 
5239     (void)memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos],
5240                  &packet[COMPLETE_L2CAP_HEADER + pos],
5241                  fragment_size);
5242     l2cap_channel->receive_sdu_pos += fragment_size;
5243 
5244     // done?
5245     log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
5246     if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
5247         l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
5248         l2cap_channel->receive_sdu_len = 0;
5249     }
5250 }
5251 
5252 static void l2cap_credit_based_notify_channel_can_send(l2cap_channel_t *channel){
5253     if (!channel->waiting_for_can_send_now) return;
5254     if (channel->send_sdu_buffer) return;
5255     channel->waiting_for_can_send_now = 0;
5256     log_debug("le can send now, local_cid 0x%x", channel->local_cid);
5257     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CAN_SEND_NOW);
5258 }
5259 
5260 static uint16_t l2cap_credit_based_available_credits(uint16_t local_cid){
5261     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5262     if (channel != NULL) {
5263         return channel->credits_outgoing;
5264     }
5265     return 0;
5266 }
5267 
5268 #endif
5269 
5270 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
5271 // 1BH2222
5272 static void l2cap_cbm_emit_incoming_connection(l2cap_channel_t *channel) {
5273     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",
5274              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
5275     uint8_t event[19];
5276     event[0] = L2CAP_EVENT_CBM_INCOMING_CONNECTION;
5277     event[1] = sizeof(event) - 2u;
5278     event[2] = channel->address_type;
5279     reverse_bd_addr(channel->address, &event[3]);
5280     little_endian_store_16(event,  9, channel->con_handle);
5281     little_endian_store_16(event, 11, channel->psm);
5282     little_endian_store_16(event, 13, channel->local_cid);
5283     little_endian_store_16(event, 15, channel->remote_cid);
5284     little_endian_store_16(event, 17, channel->remote_mtu);
5285     hci_dump_btstack_event( event, sizeof(event));
5286     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
5287 }
5288 // 11BH22222
5289 static void l2cap_cbm_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
5290     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",
5291              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
5292              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
5293     uint8_t event[23];
5294     event[0] = L2CAP_EVENT_CBM_CHANNEL_OPENED;
5295     event[1] = sizeof(event) - 2u;
5296     event[2] = status;
5297     event[3] = channel->address_type;
5298     reverse_bd_addr(channel->address, &event[4]);
5299     little_endian_store_16(event, 10, channel->con_handle);
5300     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
5301     little_endian_store_16(event, 13, channel->psm);
5302     little_endian_store_16(event, 15, channel->local_cid);
5303     little_endian_store_16(event, 17, channel->remote_cid);
5304     little_endian_store_16(event, 19, channel->local_mtu);
5305     little_endian_store_16(event, 21, channel->remote_mtu);
5306     hci_dump_btstack_event(  event, sizeof(event));
5307     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
5308 }
5309 
5310 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
5311 void l2cap_cbm_finialize_channel_close(l2cap_channel_t * channel){
5312     channel->state = L2CAP_STATE_CLOSED;
5313     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
5314     // discard channel
5315     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
5316     l2cap_free_channel_entry(channel);
5317 }
5318 
5319 static inline l2cap_service_t * l2cap_cbm_get_service(uint16_t le_psm){
5320     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
5321 }
5322 
5323 uint8_t l2cap_cbm_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
5324 
5325     log_info("l2cap_cbm_register_service psm 0x%x", psm);
5326 
5327     // check for alread registered psm
5328     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5329     if (service) {
5330         return L2CAP_SERVICE_ALREADY_REGISTERED;
5331     }
5332 
5333     // alloc structure
5334     service = btstack_memory_l2cap_service_get();
5335     if (!service) {
5336         log_error("register: no memory for l2cap_service_t");
5337         return BTSTACK_MEMORY_ALLOC_FAILED;
5338     }
5339 
5340     // fill in
5341     service->psm = psm;
5342     service->mtu = 0;
5343     service->packet_handler = packet_handler;
5344     service->required_security_level = security_level;
5345     service->requires_authorization = false;
5346 
5347     // add to services list
5348     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
5349 
5350     // done
5351     return ERROR_CODE_SUCCESS;
5352 }
5353 
5354 uint8_t l2cap_cbm_unregister_service(uint16_t psm) {
5355     log_info("l2cap_cbm_unregister_service psm 0x%x", psm);
5356     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5357     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
5358 
5359     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
5360     btstack_memory_l2cap_service_free(service);
5361     return ERROR_CODE_SUCCESS;
5362 }
5363 
5364 uint8_t l2cap_cbm_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
5365     // get channel
5366     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5367     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5368 
5369     // validate state
5370     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
5371         return ERROR_CODE_COMMAND_DISALLOWED;
5372     }
5373 
5374     // set state accept connection
5375     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
5376     channel->receive_sdu_buffer = receive_sdu_buffer;
5377     channel->local_mtu = mtu;
5378     channel->new_credits_incoming = initial_credits;
5379     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5380 
5381     // go
5382     l2cap_run();
5383     return ERROR_CODE_SUCCESS;
5384 }
5385 
5386 uint8_t l2cap_cbm_decline_connection(uint16_t local_cid, uint16_t result) {
5387     // get channel
5388     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5389     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5390 
5391     // validate state
5392     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
5393         return ERROR_CODE_COMMAND_DISALLOWED;
5394     }
5395 
5396     // set state decline connection
5397     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
5398     channel->reason = result;
5399     l2cap_run();
5400     return ERROR_CODE_SUCCESS;
5401 }
5402 
5403 static gap_security_level_t l2cap_cbm_security_level_for_connection(hci_con_handle_t con_handle){
5404     uint8_t encryption_key_size = gap_encryption_key_size(con_handle);
5405     if (encryption_key_size == 0) return LEVEL_0;
5406 
5407     bool authenticated = gap_authenticated(con_handle);
5408     if (!authenticated) return LEVEL_2;
5409 
5410     return encryption_key_size == 16 ? LEVEL_4 : LEVEL_3;
5411 }
5412 
5413 // used to handle pairing complete after triggering to increase
5414 static void l2cap_cbm_sm_packet_handler(uint8_t packet_type, uint16_t channel_nr, uint8_t *packet, uint16_t size) {
5415     UNUSED(channel_nr);
5416     UNUSED(size);
5417     UNUSED(packet_type);
5418     btstack_assert(packet_type == HCI_EVENT_PACKET);
5419     if (hci_event_packet_get_type(packet) != SM_EVENT_PAIRING_COMPLETE) return;
5420     hci_con_handle_t con_handle = sm_event_pairing_complete_get_handle(packet);
5421     btstack_linked_list_iterator_t it;
5422     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5423     while (btstack_linked_list_iterator_has_next(&it)) {
5424         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5425         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5426         if (channel->con_handle != con_handle) continue;
5427         if (channel->state != L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE) continue;
5428 
5429         // found channel, check security level
5430         if (l2cap_cbm_security_level_for_connection(con_handle) < channel->required_security_level){
5431             // pairing failed or wasn't good enough, inform user
5432             l2cap_cbm_emit_channel_opened(channel, ERROR_CODE_INSUFFICIENT_SECURITY);
5433             // discard channel
5434             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
5435             l2cap_free_channel_entry(channel);
5436         } else {
5437             // send conn request now
5438             channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5439             l2cap_run();
5440         }
5441     }
5442 }
5443 
5444 uint8_t l2cap_cbm_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5445     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
5446     uint16_t * out_local_cid) {
5447 
5448     static btstack_packet_callback_registration_t sm_event_callback_registration;
5449     static bool sm_callback_registered = false;
5450 
5451     log_info("create, handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
5452 
5453     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5454     if (!connection) {
5455         log_error("no hci_connection for handle 0x%04x", con_handle);
5456         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5457     }
5458 
5459     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_CBM, connection->address, connection->address_type, psm, mtu, security_level);
5460     if (!channel) {
5461         return BTSTACK_MEMORY_ALLOC_FAILED;
5462     }
5463     log_info("created %p", (void*)channel);
5464 
5465     // store local_cid
5466     if (out_local_cid){
5467        *out_local_cid = channel->local_cid;
5468     }
5469 
5470     // setup channel entry
5471     channel->con_handle = con_handle;
5472     channel->receive_sdu_buffer = receive_sdu_buffer;
5473     channel->new_credits_incoming = initial_credits;
5474     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5475 
5476     // add to connections list
5477     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
5478 
5479     // check security level
5480     if (l2cap_cbm_security_level_for_connection(con_handle) < channel->required_security_level){
5481         if (!sm_callback_registered){
5482             sm_callback_registered = true;
5483             // lazy registration for SM events
5484             sm_event_callback_registration.callback = &l2cap_cbm_sm_packet_handler;
5485             sm_add_event_handler(&sm_event_callback_registration);
5486         }
5487 
5488         // start pairing
5489         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
5490         sm_request_pairing(con_handle);
5491     } else {
5492         // send conn request right away
5493         channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5494         l2cap_run();
5495     }
5496 
5497     return ERROR_CODE_SUCCESS;
5498 }
5499 
5500 uint8_t l2cap_cbm_provide_credits(uint16_t local_cid, uint16_t credits){
5501     return l2cap_credit_based_provide_credits(local_cid, credits);
5502 }
5503 
5504 uint16_t l2cap_cbm_available_credits(uint16_t local_cid){
5505     return l2cap_credit_based_available_credits(local_cid);
5506 }
5507 #endif
5508 
5509 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
5510 
5511 uint8_t l2cap_ecbm_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, uint16_t min_remote_mtu,
5512                                     gap_security_level_t security_level, bool authorization_required) {
5513 
5514     // check for already registered psm
5515     l2cap_service_t *service = l2cap_ecbm_get_service(psm);
5516     if (service) {
5517         return L2CAP_SERVICE_ALREADY_REGISTERED;
5518     }
5519 
5520     // alloc structure
5521     service = btstack_memory_l2cap_service_get();
5522     if (!service) {
5523         log_error("register: no memory for l2cap_service_t");
5524         return BTSTACK_MEMORY_ALLOC_FAILED;
5525     }
5526 
5527     // fill in
5528     service->psm = psm;
5529     service->mtu = min_remote_mtu;
5530     service->packet_handler = packet_handler;
5531     service->required_security_level = security_level;
5532     service->requires_authorization = authorization_required;
5533 
5534     // add to services list
5535     btstack_linked_list_add(&l2cap_enhanced_services, (btstack_linked_item_t *) service);
5536 
5537     // done
5538     return ERROR_CODE_SUCCESS;
5539 }
5540 
5541 uint8_t l2cap_ecbm_unregister_service(uint16_t psm) {
5542     l2cap_service_t *service = l2cap_ecbm_get_service(psm);
5543     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
5544 
5545     btstack_linked_list_remove(&l2cap_enhanced_services, (btstack_linked_item_t *) service);
5546     btstack_memory_l2cap_service_free(service);
5547     return ERROR_CODE_SUCCESS;
5548 }
5549 
5550 void l2cap_ecbm_mps_set_min(uint16_t mps_min){
5551     l2cap_enhanced_mps_min = mps_min;
5552 }
5553 
5554 void l2cap_ecbm_mps_set_max(uint16_t mps_max){
5555     l2cap_enhanced_mps_max = mps_max;
5556 }
5557 
5558 uint8_t l2cap_ecbm_create_channels(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5559                                        gap_security_level_t security_level,
5560                                        uint16_t psm, uint8_t num_channels, uint16_t initial_credits, uint16_t mtu,
5561                                        uint8_t ** receive_sdu_buffers, uint16_t * out_local_cid){
5562 
5563     log_info("create enhanced, handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
5564 
5565     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5566     if (!connection) {
5567         log_error("no hci_connection for handle 0x%04x", con_handle);
5568         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5569     }
5570 
5571     // setup all channels
5572     btstack_linked_list_t channels = NULL;
5573     uint8_t status = l2cap_ecbm_setup_channels(&channels, packet_handler, num_channels, connection, psm, mtu,
5574                                                security_level);
5575     uint16_t local_mps = btstack_min(l2cap_enhanced_mps_max, btstack_min(l2cap_max_le_mtu(), mtu));
5576 
5577     // add to connections list and set state + local_sig_id
5578     l2cap_channel_t * channel;
5579     uint8_t i = 0;
5580     uint8_t local_sig_id = l2cap_next_sig_id();
5581     while (true) {
5582         channel = (l2cap_channel_t *) btstack_linked_list_pop(&channels);
5583         if (channel == NULL) break;
5584         channel->state              = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST;
5585         channel->local_sig_id       = local_sig_id;
5586         channel->local_mps = local_mps;
5587         channel->cid_index = i;
5588         channel->num_cids = num_channels;
5589         channel->credits_incoming   = initial_credits;
5590         channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5591         channel->receive_sdu_buffer = receive_sdu_buffers[i];
5592         // store local_cid
5593         if (out_local_cid){
5594             out_local_cid[i] = channel->local_cid;
5595         }
5596         btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
5597         i++;
5598     }
5599 
5600 #if 0
5601     // check security level
5602     if (l2cap_le_security_level_for_connection(con_handle) < channel->required_security_level){
5603         if (!sm_callback_registered){
5604             sm_callback_registered = true;
5605             // lazy registration for SM events
5606             sm_event_callback_registration.callback = &l2cap_sm_packet_handler;
5607             sm_add_event_handler(&sm_event_callback_registration);
5608         }
5609 
5610         // start pairing
5611         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
5612         sm_request_pairing(con_handle);
5613     } else {
5614         // send conn request right away
5615         channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5616         l2cap_run();
5617     }
5618 #endif
5619 
5620     l2cap_run();
5621 
5622     return status;
5623 }
5624 
5625 uint8_t l2cap_ecbm_accept_channels(uint16_t local_cid, uint8_t num_channels, uint16_t initial_credits,
5626                                             uint16_t receive_buffer_size, uint8_t ** receive_buffers, uint16_t * out_local_cids){
5627 
5628     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5629     if (!channel) {
5630 
5631         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5632     }
5633 
5634     uint16_t local_mps = btstack_min(l2cap_enhanced_mps_max, btstack_min(l2cap_max_le_mtu(), receive_buffer_size));
5635 
5636     //
5637     hci_con_handle_t  con_handle    = channel->con_handle;
5638     uint8_t           local_sig_id  = channel->local_sig_id;
5639     uint8_t           channel_index = 0;
5640     btstack_linked_list_iterator_t it;
5641     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5642     while (btstack_linked_list_iterator_has_next(&it)) {
5643         channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5644         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5645         if (channel->con_handle != con_handle) continue;
5646         if (channel->local_sig_id != local_sig_id) continue;
5647         if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT) continue;
5648 
5649         if (channel_index < num_channels){
5650             // assign buffer and cid
5651             out_local_cids[channel_index] = channel->local_cid;
5652             channel->receive_sdu_buffer = receive_buffers[channel_index];
5653             channel->local_mtu = receive_buffer_size;
5654             channel->local_mps = local_mps;
5655             channel->credits_incoming   = initial_credits;
5656             channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5657             channel_index++;
5658         } else {
5659             // clear local cid for response packet
5660             channel->local_cid = 0;
5661             channel->reason = L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INSUFFICIENT_RESOURCES_AVAILABLE;
5662         }
5663         // update state
5664         channel->state = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE;
5665     }
5666     l2cap_run_trigger();
5667     return ERROR_CODE_SUCCESS;
5668 }
5669 
5670 uint8_t l2cap_ecbm_decline_channels(uint16_t local_cid, uint16_t result){
5671     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5672     if (!channel) {
5673         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5674     }
5675     //
5676     hci_con_handle_t  con_handle    = channel->con_handle;
5677     uint8_t           local_sig_id  = channel->local_sig_id;
5678     btstack_linked_list_iterator_t it;
5679     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5680     while (btstack_linked_list_iterator_has_next(&it)) {
5681         channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5682         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5683         if (channel->con_handle != con_handle) continue;
5684         if (channel->local_sig_id != local_sig_id) continue;
5685         if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT) continue;
5686 
5687         // prepare response
5688         channel->local_cid = 0;
5689         channel->reason = result;
5690         channel->state = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE;
5691     }
5692     l2cap_run_trigger();
5693     return ERROR_CODE_SUCCESS;
5694 }
5695 
5696 uint8_t l2cap_ecbm_reconfigure_channels(uint8_t num_cids, uint16_t * local_cids, int16_t receive_buffer_size, uint8_t ** receive_buffers){
5697     btstack_assert(receive_buffers != NULL);
5698     btstack_assert(local_cids != NULL);
5699 
5700     if (num_cids > L2CAP_ECBM_MAX_CID_ARRAY_SIZE){
5701         return ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS;
5702     }
5703 
5704     // check if all cids exist and have the same con handle
5705     uint8_t i;
5706     hci_con_handle_t con_handle = HCI_CON_HANDLE_INVALID;
5707     for (i = 0 ; i < num_cids ; i++){
5708         l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cids[i]);
5709         if (!channel) {
5710             return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5711         }
5712         if (channel->state != L2CAP_STATE_OPEN){
5713             return ERROR_CODE_COMMAND_DISALLOWED;
5714         }
5715         if (con_handle == HCI_CON_HANDLE_INVALID){
5716             con_handle = channel->con_handle;
5717         } else if (con_handle != channel->con_handle){
5718             return ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS;
5719         }
5720     }
5721     // set renegotiation data and state
5722     uint8_t sig_id = l2cap_next_sig_id();
5723     for (i = 0 ; i < num_cids ; i++){
5724         l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cids[i]);
5725         channel->cid_index = i;
5726         channel->num_cids = num_cids;
5727         channel->local_sig_id = sig_id;
5728         channel->renegotiate_mtu = receive_buffer_size;
5729         channel->renegotiate_sdu_buffer = receive_buffers[i];
5730         channel->state = L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST;
5731     }
5732 
5733 
5734     l2cap_run();
5735     return ERROR_CODE_SUCCESS;
5736 }
5737 
5738 uint8_t l2cap_ecbm_provide_credits(uint16_t local_cid, uint16_t credits){
5739     return l2cap_credit_based_provide_credits(local_cid, credits);
5740 }
5741 
5742 uint16_t l2cap_ecbm_available_credits(uint16_t local_cid){
5743     return l2cap_credit_based_available_credits(local_cid);
5744 }
5745 #endif
5746 
5747 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
5748 // @deprecated - please use l2cap_ertm_create_channel
5749 uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
5750                                   l2cap_ertm_config_t * ertm_contig, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
5751     log_error("deprecated - please use l2cap_ertm_create_channel");
5752     return l2cap_ertm_create_channel(packet_handler, address, psm, ertm_contig, buffer, size, out_local_cid);
5753 };
5754 
5755 // @deprecated - please use l2cap_ertm_accept_connection
5756 uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, l2cap_ertm_config_t * ertm_contig, uint8_t * buffer, uint32_t size){
5757     log_error("deprecated - please use l2cap_ertm_accept_connection");
5758     return l2cap_ertm_accept_connection(local_cid, ertm_contig, buffer, size);
5759 }
5760 #endif
5761 
5762 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
5763 // @deprecated - please use l2cap_cbm_register_service
5764 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
5765     log_error("deprecated - please use l2cap_cbm_register_service");
5766     return l2cap_cbm_register_service(packet_handler, psm, security_level);
5767 }
5768 
5769 // @deprecated - please use l2cap_cbm_unregister_service
5770 uint8_t l2cap_le_unregister_service(uint16_t psm){
5771     log_error("deprecated - please use l2cap_cbm_unregister_service");
5772     return l2cap_cbm_unregister_service(psm);
5773 }
5774 
5775 // @deprecated - please use l2cap_cbm_accept_connection
5776 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
5777     log_error("deprecated - please use l2cap_cbm_accept_connection");
5778     return l2cap_cbm_accept_connection(local_cid, receive_sdu_buffer, mtu, initial_credits);
5779 }
5780 
5781 // @deprecated - please use l2cap_cbm_decline_connection
5782 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
5783     log_error("deprecated - please use l2cap_cbm_decline_connection");
5784     return l2cap_cbm_decline_connection(local_cid, L2CAP_CBM_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE);
5785 }
5786 
5787 // @deprecated - please use l2cap_cbm_create_channel
5788 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5789                                 uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
5790                                 uint16_t * out_local_cid){
5791     log_error("deprecated - please use l2cap_cbm_create_channel");
5792     return l2cap_cbm_create_channel(packet_handler, con_handle, psm, receive_sdu_buffer, mtu, initial_credits, security_level, out_local_cid);
5793 }
5794 
5795 // @deprecated - please use l2cap_cbm_provide_credits
5796 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
5797     log_error("deprecated - please use l2cap_cbm_provide_credits");
5798     return l2cap_cbm_provide_credits(local_cid, credits);
5799 }
5800 
5801 // @deprecated - please use l2cap_can_send_packet_now
5802 bool l2cap_le_can_send_now(uint16_t local_cid){
5803     log_error("deprecated - please use l2cap_can_send_packet_now");
5804     return l2cap_can_send_packet_now(local_cid);
5805 }
5806 
5807 // @deprecated - please use l2cap_request_can_send_now_event
5808 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
5809     log_error("deprecated - please use l2cap_request_can_send_now_event");
5810     return l2cap_request_can_send_now_event(local_cid);
5811 }
5812 
5813 // @deprecated - please use l2cap_cbm_send_data
5814 uint8_t l2cap_le_send_data(uint16_t local_cid, const uint8_t * data, uint16_t size){
5815     log_error("deprecated - please use l2cap_cbm_send_data");
5816     return l2cap_send(local_cid, data, size);
5817 }
5818 
5819 // @deprecated - please use l2cap_disconnect
5820 uint8_t l2cap_le_disconnect(uint16_t local_cid){
5821     log_error("deprecated - please use l2cap_disconnect");
5822     return l2cap_disconnect(local_cid);
5823 }
5824 #endif
5825 
5826 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
5827 static void fuzz_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) {
5828 }
5829 void l2cap_setup_test_channels_fuzz(void) {
5830     bd_addr_t address;
5831     l2cap_channel_t * channel;
5832 
5833     // 0x41 1setup classic basic
5834     channel = l2cap_create_channel_entry(fuzz_packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, address,
5835         BD_ADDR_TYPE_ACL, 0x01, 100, LEVEL_4);
5836     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
5837 
5838     // 0x42 setup le cbm
5839     channel = l2cap_create_channel_entry(fuzz_packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_CBM, address,
5840         BD_ADDR_TYPE_LE_PUBLIC, 0x03, 100, LEVEL_4);
5841     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
5842 
5843     // 0x43 setup le ecbm
5844     channel = l2cap_create_channel_entry(fuzz_packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_ECBM,
5845         address, BD_ADDR_TYPE_LE_PUBLIC, 0x05, 100, LEVEL_4);
5846     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
5847 }
5848 
5849 void l2cap_free_channels_fuzz(void){
5850     btstack_linked_list_iterator_t it;
5851     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5852     while (btstack_linked_list_iterator_has_next(&it)){
5853         l2cap_channel_t * channel = (l2cap_channel_t*) btstack_linked_list_iterator_next(&it);
5854         bool fixed_channel = false;
5855         switch (channel->channel_type) {
5856             case L2CAP_CHANNEL_TYPE_FIXED_LE:
5857             case L2CAP_CHANNEL_TYPE_FIXED_CLASSIC:
5858             case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
5859                 fixed_channel = true;
5860                 break;
5861             default:
5862                 break;
5863         }
5864         if (fixed_channel == false) {
5865             btstack_linked_list_iterator_remove(&it);
5866             btstack_memory_l2cap_channel_free(channel);
5867         }
5868     }
5869 }
5870 
5871 l2cap_channel_t * l2cap_get_dynamic_channel_fuzz(void){
5872     btstack_linked_list_iterator_t it;
5873     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5874     while (btstack_linked_list_iterator_has_next(&it)){
5875         l2cap_channel_t * channel = (l2cap_channel_t*) btstack_linked_list_iterator_next(&it);
5876         switch (channel->channel_type) {
5877             case L2CAP_CHANNEL_TYPE_CLASSIC:
5878             case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
5879             case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
5880                 return channel;
5881             default:
5882                 break;
5883         }
5884     }
5885     return NULL;
5886 }
5887 #endif
5888