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