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