xref: /btstack/src/l2cap.c (revision 284d66bc610cd8551d4dce75d1f6cc77a02d16f0)
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 void l2cap_disconnect(uint16_t local_cid, uint8_t reason){
2463     log_info("disconnect local_cid 0x%x reason 0x%x", local_cid, reason);
2464     UNUSED(reason);
2465     // find channel for local_cid
2466     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2467     if (channel) {
2468         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2469     }
2470     // process
2471     l2cap_run();
2472 }
2473 
2474 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
2475     // mark all channels before emitting open events as these could trigger new connetion requests to the same device
2476     btstack_linked_list_iterator_t it;
2477     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2478     while (btstack_linked_list_iterator_has_next(&it)){
2479         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2480         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2481         if (bd_addr_cmp( channel->address, address) != 0) continue;
2482         // channel for this address found
2483         switch (channel->state){
2484             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2485             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2486                 channel->state = L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD;
2487                 break;
2488             default:
2489                 break;
2490         }
2491     }
2492     // emit and free marked entries. restart loop to deal with list changes
2493     int done = 0;
2494     while (!done) {
2495         done = 1;
2496         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2497         while (btstack_linked_list_iterator_has_next(&it)){
2498             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2499             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2500             if (channel->state == L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD){
2501                 done = 0;
2502                 // failure, forward error code
2503                 l2cap_handle_channel_open_failed(channel, status);
2504                 // discard channel
2505                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2506                 l2cap_free_channel_entry(channel);
2507                 break;
2508             }
2509         }
2510     }
2511 
2512 }
2513 
2514 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
2515     btstack_linked_list_iterator_t it;
2516     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2517     while (btstack_linked_list_iterator_has_next(&it)){
2518         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2519         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2520         if ( ! bd_addr_cmp( channel->address, address) ){
2521             l2cap_handle_connection_complete(handle, channel);
2522         }
2523     }
2524     // process
2525     l2cap_run();
2526 }
2527 #endif
2528 
2529 static bool l2cap_channel_ready_to_send(l2cap_channel_t * channel){
2530     switch (channel->channel_type){
2531 #ifdef ENABLE_CLASSIC
2532         case L2CAP_CHANNEL_TYPE_CLASSIC:
2533             if (channel->state != L2CAP_STATE_OPEN) return false;
2534 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2535             // send if we have more data and remote windows isn't full yet
2536             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2537                 if (channel->unacked_frames >= btstack_min(channel->num_stored_tx_frames, channel->remote_tx_window_size)) return false;
2538                 return hci_can_send_acl_classic_packet_now() != 0;
2539             }
2540 #endif
2541             if (!channel->waiting_for_can_send_now) return false;
2542             return (hci_can_send_acl_classic_packet_now() != 0);
2543         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2544             if (!channel->waiting_for_can_send_now) return false;
2545             return hci_can_send_acl_classic_packet_now() != 0;
2546 #endif
2547 #ifdef ENABLE_BLE
2548         case L2CAP_CHANNEL_TYPE_FIXED:
2549             if (!channel->waiting_for_can_send_now) return false;
2550             return hci_can_send_acl_le_packet_now() != 0;
2551 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2552         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
2553             if (channel->state != L2CAP_STATE_OPEN) return false;
2554             if (channel->send_sdu_buffer == NULL) return false;
2555             if (channel->credits_outgoing == 0u) return false;
2556             return hci_can_send_acl_le_packet_now() != 0;
2557 #endif
2558 #endif
2559 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2560         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
2561             if (channel->state != L2CAP_STATE_OPEN) return false;
2562             if (channel->send_sdu_buffer == NULL) return false;
2563             if (channel->credits_outgoing == 0u) return false;
2564             if (channel->address_type == BD_ADDR_TYPE_ACL) {
2565                 return hci_can_send_acl_classic_packet_now() != 0;
2566             } else {
2567                 return hci_can_send_acl_le_packet_now() != 0;
2568             }
2569 #endif
2570         default:
2571             return false;
2572     }
2573 }
2574 
2575 static void l2cap_channel_trigger_send(l2cap_channel_t * channel){
2576     switch (channel->channel_type){
2577 #ifdef ENABLE_CLASSIC
2578         case L2CAP_CHANNEL_TYPE_CLASSIC:
2579 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2580             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2581                 l2cap_ertm_channel_send_information_frame(channel);
2582                 return;
2583             }
2584 #endif
2585             channel->waiting_for_can_send_now = 0;
2586             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2587             break;
2588         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2589             channel->waiting_for_can_send_now = 0;
2590             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2591             break;
2592 #endif
2593 #ifdef ENABLE_BLE
2594         case L2CAP_CHANNEL_TYPE_FIXED:
2595             channel->waiting_for_can_send_now = 0;
2596             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2597             break;
2598 #endif
2599 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2600         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
2601             l2cap_credit_based_send_pdu(channel);
2602             break;
2603 #endif
2604 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2605         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
2606             l2cap_credit_based_send_pdu(channel);
2607             break;
2608 #endif
2609         default:
2610             break;
2611     }
2612 }
2613 
2614 static void l2cap_notify_channel_can_send(void){
2615     bool done = false;
2616     while (!done){
2617         done = true;
2618         btstack_linked_list_iterator_t it;
2619         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2620         while (btstack_linked_list_iterator_has_next(&it)){
2621             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2622             bool ready = l2cap_channel_ready_to_send(channel);
2623             if (!ready) continue;
2624 
2625             // requeue channel for fairness
2626             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2627             btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2628 
2629             // trigger sending
2630             l2cap_channel_trigger_send(channel);
2631 
2632             // exit inner loop as we just broke the iterator, but try again
2633             done = false;
2634             break;
2635         }
2636     }
2637 }
2638 
2639 #ifdef L2CAP_USES_CHANNELS
2640 
2641 static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){
2642     // open cannot fail for for incoming connections
2643     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0;
2644 
2645     // check state
2646     switch (channel->state){
2647         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2648         case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2649         case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES:
2650         case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2651         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
2652         case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES:
2653         case L2CAP_STATE_WAIT_CONNECT_RSP:
2654         case L2CAP_STATE_CONFIG:
2655         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
2656         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
2657         case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE:
2658         case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD:
2659             return 1;
2660 
2661         case L2CAP_STATE_OPEN:
2662         case L2CAP_STATE_CLOSED:
2663         case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES:
2664         case L2CAP_STATE_WAIT_DISCONNECT:
2665         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY:
2666         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
2667         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
2668         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2669         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
2670         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
2671         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
2672         case L2CAP_STATE_INVALID:
2673         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2674             return 0;
2675 
2676         default:
2677             // get a "warning" about new states
2678             btstack_assert(false);
2679             return 0;
2680     }
2681 }
2682 #endif
2683 
2684 #ifdef ENABLE_CLASSIC
2685 static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){
2686     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2687         l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2688     } else {
2689         l2cap_handle_channel_closed(channel);
2690     }
2691     l2cap_free_channel_entry(channel);
2692 }
2693 #endif
2694 
2695 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2696 static void l2cap_handle_hci_le_disconnect_event(l2cap_channel_t * channel){
2697     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2698         l2cap_cbm_emit_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2699     } else {
2700         l2cap_cbm_emit_channel_closed(channel);
2701     }
2702     l2cap_free_channel_entry(channel);
2703 }
2704 #endif
2705 
2706 #ifdef ENABLE_CLASSIC
2707 static void l2cap_check_classic_timeout(hci_con_handle_t handle){
2708     if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) {
2709         return;
2710     }
2711     if (hci_authentication_active_for_handle(handle)) {
2712         return;
2713     }
2714     bool hci_con_used = false;
2715     btstack_linked_list_iterator_t it;
2716     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2717     while (btstack_linked_list_iterator_has_next(&it)){
2718         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2719         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2720         if (channel->con_handle != handle) continue;
2721         hci_con_used = true;
2722         break;
2723     }
2724     if (hci_con_used) {
2725         return;
2726     }
2727     if (!hci_can_send_command_packet_now()) {
2728         return;
2729     }
2730     hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
2731 }
2732 
2733 static void l2cap_handle_features_complete(hci_con_handle_t handle){
2734     if (hci_remote_features_available(handle) == false){
2735         return;
2736     }
2737     btstack_linked_list_iterator_t it;
2738     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2739     while (btstack_linked_list_iterator_has_next(&it)){
2740         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2741         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2742         if (channel->con_handle != handle) continue;
2743         log_info("remote supported features, channel %p, cid %04x - state %u", channel, channel->local_cid, channel->state);
2744         l2cap_handle_remote_supported_features_received(channel);
2745     }
2746 }
2747 
2748 static void l2cap_handle_security_level_incoming_sufficient(l2cap_channel_t * channel){
2749     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2750     l2cap_emit_incoming_connection(channel);
2751 }
2752 
2753 static void l2cap_handle_security_level(hci_con_handle_t handle, gap_security_level_t actual_level){
2754     log_info("security level update for handle 0x%04x", handle);
2755 
2756     // trigger l2cap information requests
2757     if (actual_level > LEVEL_0){
2758         hci_connection_t * hci_connection = hci_connection_for_handle(handle);
2759         btstack_assert(hci_connection != NULL);
2760         if (hci_connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
2761             hci_connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2762         }
2763     }
2764 
2765     btstack_linked_list_iterator_t it;
2766     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2767     while (btstack_linked_list_iterator_has_next(&it)){
2768         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2769         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2770         if (channel->con_handle != handle) continue;
2771 
2772         gap_security_level_t required_level = channel->required_security_level;
2773 
2774         log_info("channel %p, cid %04x - state %u: actual %u >= required %u?", channel, channel->local_cid, channel->state, actual_level, required_level);
2775 
2776         switch (channel->state){
2777             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2778                 if (actual_level >= required_level){
2779                     l2cap_handle_security_level_incoming_sufficient(channel);
2780                 } else {
2781                     channel->reason = L2CAP_CONNECTION_RESULT_SECURITY_BLOCK;
2782                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2783                 }
2784                 break;
2785 
2786             case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2787                 if (actual_level >= required_level){
2788                     l2cap_ready_to_connect(channel);
2789                 } else {
2790                     // security level insufficient, report error and free channel
2791                     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY);
2792                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t  *) channel);
2793                     l2cap_free_channel_entry(channel);
2794                 }
2795                 break;
2796 
2797             default:
2798                 break;
2799         }
2800     }
2801 }
2802 #endif
2803 
2804 #ifdef L2CAP_USES_CHANNELS
2805 static void l2cap_handle_disconnection_complete(hci_con_handle_t handle){
2806     // collect channels to close
2807     btstack_linked_list_t channels_to_close = NULL;
2808     btstack_linked_list_iterator_t it;
2809     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2810     while (btstack_linked_list_iterator_has_next(&it)) {
2811         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2812         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2813         if (channel->con_handle != handle) continue;
2814         btstack_linked_list_iterator_remove(&it);
2815         btstack_linked_list_add(&channels_to_close, (btstack_linked_item_t *) channel);
2816     }
2817     // send l2cap open failed or closed events for all channels on this handle and free them
2818     btstack_linked_list_iterator_init(&it, &channels_to_close);
2819     while (btstack_linked_list_iterator_has_next(&it)) {
2820         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2821         btstack_linked_list_iterator_remove(&it);
2822         switch(channel->channel_type){
2823 #ifdef ENABLE_CLASSIC
2824             case L2CAP_CHANNEL_TYPE_CLASSIC:
2825                 l2cap_handle_hci_disconnect_event(channel);
2826                 break;
2827 #endif
2828 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2829             case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
2830                 l2cap_handle_hci_le_disconnect_event(channel);
2831                 break;
2832 #endif
2833 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2834             case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
2835                 switch (channel->state) {
2836                     case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST:
2837                     case L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE:
2838                         // emit open failed if disconnected before connection complete
2839                         l2cap_ecbm_emit_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2840                         break;
2841                     case L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST:
2842                     case L2CAP_STATE_WAIT_ENHANCED_RENEGOTIATION_RESPONSE:
2843                         // emit reconfigure failure - result = 0xffff
2844                         l2cap_ecbm_emit_reconfigure_complete(channel, 0xffff);
2845                         break;
2846                     default:
2847                         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ECBM_CHANNEL_OPENED);
2848                         break;
2849                 }
2850                 l2cap_free_channel_entry(channel);
2851                 break;
2852 #endif
2853             default:
2854                 break;
2855         }
2856     }
2857 }
2858 #endif
2859 
2860 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
2861 
2862     UNUSED(packet_type); // ok: registered with hci_event_callback_registration
2863     UNUSED(cid);         // ok: there is no channel
2864     UNUSED(size);        // ok: fixed format events read from HCI buffer
2865 
2866 #ifdef ENABLE_CLASSIC
2867     bd_addr_t address;
2868     gap_security_level_t security_level;
2869 #endif
2870 #ifdef L2CAP_USES_CHANNELS
2871     hci_con_handle_t handle;
2872 #endif
2873 
2874     switch(hci_event_packet_get_type(packet)){
2875 
2876         // Notify channel packet handler if they can send now
2877         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2878         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
2879         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
2880             l2cap_call_notify_channel_in_run = true;
2881             break;
2882 
2883         case HCI_EVENT_COMMAND_STATUS:
2884 #ifdef ENABLE_CLASSIC
2885             // check command status for create connection for errors
2886             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
2887                 // cache outgoing address and reset
2888                 (void)memcpy(address, l2cap_outgoing_classic_addr, 6);
2889                 memset(l2cap_outgoing_classic_addr, 0, 6);
2890                 // error => outgoing connection failed
2891                 uint8_t status = hci_event_command_status_get_status(packet);
2892                 if (status){
2893                     l2cap_handle_connection_failed_for_addr(address, status);
2894                 }
2895             }
2896 #endif
2897             l2cap_run();    // try sending signaling packets first
2898             break;
2899 
2900 #ifdef ENABLE_CLASSIC
2901         // handle connection complete events
2902         case HCI_EVENT_CONNECTION_COMPLETE:
2903             reverse_bd_addr(&packet[5], address);
2904             if (packet[2] == 0){
2905                 handle = little_endian_read_16(packet, 3);
2906                 l2cap_handle_connection_success_for_addr(address, handle);
2907             } else {
2908                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
2909             }
2910             break;
2911 
2912         // handle successful create connection cancel command
2913         case HCI_EVENT_COMMAND_COMPLETE:
2914             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
2915                 if (packet[5] == 0){
2916                     reverse_bd_addr(&packet[6], address);
2917                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
2918                     l2cap_handle_connection_failed_for_addr(address, 0x16);
2919                 }
2920             }
2921             l2cap_run();    // try sending signaling packets first
2922             break;
2923 #endif
2924 
2925 #ifdef L2CAP_USES_CHANNELS
2926         // handle disconnection complete events
2927         case HCI_EVENT_DISCONNECTION_COMPLETE:
2928             handle = little_endian_read_16(packet, 3);
2929             l2cap_handle_disconnection_complete(handle);
2930             break;
2931 #endif
2932 
2933         // HCI Connection Timeouts
2934 #ifdef ENABLE_CLASSIC
2935         case L2CAP_EVENT_TIMEOUT_CHECK:
2936             handle = little_endian_read_16(packet, 2);
2937             l2cap_check_classic_timeout(handle);
2938             break;
2939 
2940         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2941         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
2942             handle = little_endian_read_16(packet, 3);
2943             l2cap_handle_features_complete(handle);
2944             break;
2945 
2946         case GAP_EVENT_SECURITY_LEVEL:
2947             handle = little_endian_read_16(packet, 2);
2948             security_level = (gap_security_level_t) packet[4];
2949             l2cap_handle_security_level(handle, security_level);
2950             break;
2951 #endif
2952         default:
2953             break;
2954     }
2955 
2956     l2cap_run();
2957 }
2958 
2959 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t cid, uint16_t data){
2960     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indicates the connection was refused."
2961     if (l2cap_signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
2962         l2cap_signaling_responses[l2cap_signaling_responses_pending].handle = handle;
2963         l2cap_signaling_responses[l2cap_signaling_responses_pending].code = code;
2964         l2cap_signaling_responses[l2cap_signaling_responses_pending].sig_id = sig_id;
2965         l2cap_signaling_responses[l2cap_signaling_responses_pending].cid = cid;
2966         l2cap_signaling_responses[l2cap_signaling_responses_pending].data = data;
2967         l2cap_signaling_responses_pending++;
2968         l2cap_run();
2969     }
2970 }
2971 
2972 #ifdef ENABLE_CLASSIC
2973 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
2974     switch (channel->state){
2975         case L2CAP_STATE_CONFIG:
2976         case L2CAP_STATE_OPEN:
2977         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2978         case L2CAP_STATE_WAIT_DISCONNECT:
2979             break;
2980         default:
2981             // ignore in other states
2982             return;
2983     }
2984 
2985     channel->remote_sig_id = identifier;
2986     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
2987     l2cap_run();
2988 }
2989 
2990 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
2991 
2992     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
2993     l2cap_service_t *service = l2cap_get_service(psm);
2994     if (!service) {
2995         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CONNECTION_RESULT_PSM_NOT_SUPPORTED);
2996         return;
2997     }
2998 
2999     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
3000     if (!hci_connection) {
3001         //
3002         log_error("no hci_connection for handle %u", handle);
3003         return;
3004     }
3005 
3006     // alloc structure
3007     gap_security_level_t required_level = service->required_security_level;
3008     if (gap_get_secure_connections_only_mode() && (required_level != LEVEL_0)){
3009         required_level = LEVEL_4;
3010     }
3011     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, hci_connection->address, BD_ADDR_TYPE_ACL,
3012     psm, service->mtu, required_level);
3013     if (!channel){
3014         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE);
3015         return;
3016     }
3017 
3018     channel->con_handle = handle;
3019     channel->remote_cid = source_cid;
3020     channel->remote_sig_id = sig_id;
3021 
3022     // limit local mtu to max acl packet length - l2cap header
3023     if (channel->local_mtu > l2cap_max_mtu()) {
3024         channel->local_mtu = l2cap_max_mtu();
3025     }
3026 
3027     // set initial state
3028     channel->state =     L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
3029     channel->state_var = L2CAP_CHANNEL_STATE_VAR_INCOMING;
3030 
3031     // add to connections list
3032     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
3033 
3034     //
3035     if (required_level > LEVEL_0){
3036         // send conn resp pending if remote supported features have not been received yet
3037         if (hci_remote_features_available(handle)) {
3038             l2cap_handle_remote_supported_features_received(channel);
3039         } else {
3040             channel->state_var |= L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND;
3041             hci_remote_features_query(handle);
3042         }
3043     } else {
3044         l2cap_handle_security_level_incoming_sufficient(channel);
3045     }
3046 }
3047 
3048 void l2cap_accept_connection(uint16_t local_cid){
3049     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
3050     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3051     if (!channel) {
3052         log_error("accept called but local_cid 0x%x not found", local_cid);
3053         return;
3054     }
3055 
3056 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3057     // configure L2CAP Basic mode
3058     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
3059 #endif
3060 
3061     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
3062 
3063     // process
3064     l2cap_run();
3065 }
3066 
3067 void l2cap_decline_connection(uint16_t local_cid){
3068     log_info("decline local_cid 0x%x", local_cid);
3069     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
3070     if (!channel) {
3071         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
3072         return;
3073     }
3074     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
3075     channel->reason = L2CAP_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE;
3076     l2cap_run();
3077 }
3078 
3079 // @pre command len is valid, see check in l2cap_signaling_handler_channel
3080 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
3081 
3082 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3083     uint8_t use_fcs = 1;
3084 #endif
3085 
3086     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
3087 
3088     uint16_t flags = little_endian_read_16(command, 6);
3089     if (flags & 1) {
3090         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
3091     }
3092 
3093     // accept the other's configuration options
3094     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3095     uint16_t pos     = 8;
3096     while (pos < end_pos){
3097         uint8_t option_hint = command[pos] >> 7;
3098         uint8_t option_type = command[pos] & 0x7f;
3099         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
3100         pos++;
3101         uint8_t length = command[pos++];
3102         // MTU { type(8): 1, len(8):2, MTU(16) }
3103         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) && (length == 2)){
3104             channel->remote_mtu = little_endian_read_16(command, pos);
3105             log_info("Remote MTU %u", channel->remote_mtu);
3106             if (channel->remote_mtu > l2cap_max_mtu()){
3107                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
3108                 channel->remote_mtu = l2cap_max_mtu();
3109             }
3110             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
3111         }
3112         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
3113         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT) && (length == 2)){
3114             channel->flush_timeout = little_endian_read_16(command, pos);
3115             log_info("Flush timeout: %u ms", channel->flush_timeout);
3116         }
3117 
3118 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3119         // Retransmission and Flow Control Option
3120         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
3121             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
3122             switch(channel->mode){
3123                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
3124                     // Store remote config
3125                     channel->remote_tx_window_size = command[pos+1];
3126                     channel->remote_max_transmit   = command[pos+2];
3127                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
3128                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
3129                     channel->remote_mps = little_endian_read_16(command, pos + 7);
3130                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
3131                         channel->remote_tx_window_size,
3132                         channel->remote_max_transmit,
3133                         channel->remote_retransmission_timeout_ms,
3134                         channel->remote_monitor_timeout_ms,
3135                         channel->remote_mps);
3136                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
3137                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3138                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3139                     } else {
3140                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
3141                     }
3142                     break;
3143                 case L2CAP_CHANNEL_MODE_BASIC:
3144                     switch (mode){
3145                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
3146                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
3147                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
3148                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3149                             }
3150                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
3151                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
3152                             break;
3153                         default: // case L2CAP_CHANNEL_MODE_BASIC:
3154                             // TODO store and evaluate configuration
3155                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
3156                             break;
3157                     }
3158                     break;
3159                 default:
3160                     break;
3161             }
3162         }
3163         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
3164             use_fcs = command[pos];
3165         }
3166 #endif
3167         // check for unknown options
3168         if ((option_hint == 0) && ((option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) || (option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE))){
3169             log_info("l2cap cid %u, unknown option 0x%02x", channel->local_cid, option_type);
3170             channel->unknown_option = option_type;
3171             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
3172         }
3173         pos += length;
3174     }
3175 
3176 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3177         // "FCS" has precedence over "No FCS"
3178         uint8_t update = channel->fcs_option || use_fcs;
3179         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
3180         channel->fcs_option = update;
3181         // If ERTM mandatory, but remote didn't send Retransmission and Flowcontrol options -> disconnect
3182         if (((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM) == 0) & (channel->ertm_mandatory)){
3183             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3184         }
3185 #endif
3186 }
3187 
3188 // @pre command len is valid, see check in l2cap_signaling_handler_channel
3189 static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
3190     log_info("l2cap_signaling_handle_configure_response");
3191 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3192     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3193     uint16_t pos     = 10;
3194     while (pos < end_pos){
3195         uint8_t option_hint = command[pos] >> 7;
3196         uint8_t option_type = command[pos] & 0x7f;
3197         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
3198         pos++;
3199         uint8_t length = command[pos++];
3200 
3201         // Retransmission and Flow Control Option
3202         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
3203             switch (channel->mode){
3204                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
3205                     if (channel->ertm_mandatory){
3206                         // ??
3207                     } else {
3208                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
3209                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
3210                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3211                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3212                         }
3213                     }
3214                     break;
3215                 case L2CAP_CHANNEL_MODE_BASIC:
3216                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
3217                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
3218                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3219                     }
3220                     break;
3221                 default:
3222                     break;
3223             }
3224         }
3225 
3226         // check for unknown options
3227         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
3228             log_info("l2cap cid %u, unknown option 0x%02x", channel->local_cid, option_type);
3229             channel->unknown_option = option_type;
3230             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
3231         }
3232 
3233         pos += length;
3234     }
3235 #else
3236     UNUSED(channel);  // ok: no code
3237     UNUSED(result);   // ok: no code
3238     UNUSED(command);  // ok: no code
3239 #endif
3240 }
3241 
3242 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
3243     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
3244     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
3245     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
3246     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
3247     if (channel->state == L2CAP_STATE_OPEN) return 0;
3248     return 1;
3249 }
3250 
3251 
3252 // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
3253 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
3254 
3255     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3256     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
3257     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3258     uint16_t result = 0;
3259 
3260     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
3261 
3262     // handle DISCONNECT REQUESTS seperately
3263     if (code == DISCONNECTION_REQUEST){
3264         l2cap_handle_disconnect_request(channel, identifier);
3265         return;
3266     }
3267 
3268     // @STATEMACHINE(l2cap)
3269     switch (channel->state) {
3270 
3271         case L2CAP_STATE_WAIT_CONNECT_RSP:
3272             switch (code){
3273                 case CONNECTION_RESPONSE:
3274                     if (cmd_len < 8){
3275                         // command imcomplete
3276                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3277                         break;
3278                     }
3279                     l2cap_stop_rtx(channel);
3280                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3281                     switch (result) {
3282                         case 0:
3283                             // successful connection
3284                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3285                             channel->state = L2CAP_STATE_CONFIG;
3286                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
3287                             break;
3288                         case 1:
3289                             // connection pending. get some coffee, but start the ERTX
3290                             l2cap_start_ertx(channel);
3291                             break;
3292                         default:
3293                             // channel closed
3294                             channel->state = L2CAP_STATE_CLOSED;
3295                             // map l2cap connection response result to BTstack status enumeration
3296                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
3297 
3298                             // drop link key if security block
3299                             if ((L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result) == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
3300                                 gap_drop_link_key_for_bd_addr(channel->address);
3301                             }
3302 
3303                             // discard channel
3304                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3305                             l2cap_free_channel_entry(channel);
3306                             break;
3307                     }
3308                     break;
3309 
3310                 default:
3311                     //@TODO: implement other signaling packets
3312                     break;
3313             }
3314             break;
3315 
3316         case L2CAP_STATE_CONFIG:
3317             switch (code) {
3318                 case CONFIGURE_REQUEST:
3319                     if (cmd_len < 4){
3320                         // command incomplete
3321                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3322                         break;
3323                     }
3324                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
3325                     l2cap_signaling_handle_configure_request(channel, command);
3326                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
3327                         // only done if continuation not set
3328                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
3329                     }
3330                     break;
3331                 case CONFIGURE_RESPONSE:
3332                     if (cmd_len < 6){
3333                         // command incomplete
3334                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3335                         break;
3336                     }
3337                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3338                     l2cap_stop_rtx(channel);
3339                     l2cap_signaling_handle_configure_response(channel, result, command);
3340                     switch (result){
3341                         case 0: // success
3342                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
3343                             break;
3344                         case 4: // pending
3345                             l2cap_start_ertx(channel);
3346                             break;
3347                         default:
3348 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3349                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
3350                                 // remote does not offer ertm but it's required
3351                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3352                                 break;
3353                             }
3354 #endif
3355                             // retry on negative result
3356                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
3357                             break;
3358                     }
3359                     break;
3360                 default:
3361                     break;
3362             }
3363             if (l2cap_channel_ready_for_open(channel)){
3364 
3365 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3366                 // assert that packet can be stored in fragment buffers in ertm
3367                 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3368                     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
3369                     uint16_t usable_mtu = channel->num_tx_buffers == 1 ? effective_mps : channel->num_tx_buffers * effective_mps - 2;
3370                     if (usable_mtu < channel->remote_mtu){
3371                         log_info("Remote MTU %u > max storable ERTM packet, only using MTU = %u", channel->remote_mtu, usable_mtu);
3372                         channel->remote_mtu = usable_mtu;
3373                     }
3374                 }
3375 #endif
3376                 // for open:
3377                 channel->state = L2CAP_STATE_OPEN;
3378                 l2cap_emit_channel_opened(channel, 0);
3379             }
3380             break;
3381 
3382         case L2CAP_STATE_WAIT_DISCONNECT:
3383             switch (code) {
3384                 case DISCONNECTION_RESPONSE:
3385                     l2cap_finalize_channel_close(channel);
3386                     break;
3387                 default:
3388                     //@TODO: implement other signaling packets
3389                     break;
3390             }
3391             break;
3392 
3393         case L2CAP_STATE_CLOSED:
3394             // @TODO handle incoming requests
3395             break;
3396 
3397         case L2CAP_STATE_OPEN:
3398             //@TODO: implement other signaling packets, e.g. re-configure
3399             break;
3400         default:
3401             break;
3402     }
3403     // log_info("new state %u", channel->state);
3404 }
3405 
3406 #ifdef ENABLE_CLASSIC
3407 static void l2cap_handle_information_request_complete(hci_connection_t * connection){
3408 
3409     connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
3410 
3411     // emit event
3412     uint8_t event[8];
3413     event[0] = L2CAP_EVENT_INFORMATION_RESPONSE;
3414     event[1] = sizeof(event) - 2;
3415     little_endian_store_16(event, 2, connection->con_handle);
3416     little_endian_store_16(event, 4, connection->l2cap_state.extended_feature_mask);
3417     little_endian_store_16(event, 6, connection->l2cap_state.fixed_channels_supported);
3418     l2cap_emit_event(event, sizeof(event));
3419 
3420     // trigger connection request
3421     btstack_linked_list_iterator_t it;
3422     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3423     while (btstack_linked_list_iterator_has_next(&it)){
3424         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3425         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3426         if (channel->con_handle != connection->con_handle) continue;
3427 
3428         // incoming connection: information request was triggered after user has accepted connection,
3429         // now: verify channel configuration, esp. if ertm will be mandatory
3430         if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
3431             // default: continue
3432             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
3433 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3434             if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
3435                 // ERTM not possible, select basic mode and release buffer
3436                 channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3437                 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3438 
3439                 // bail if ERTM is mandatory
3440                 if (channel->ertm_mandatory){
3441                     // We chose 'no resources available' for "ERTM mandatory but you don't even know ERTM exists"
3442                     log_info("ERTM mandatory -> reject connection");
3443                     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
3444                     channel->reason = L2CAP_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE;
3445                 }  else {
3446                     log_info("ERTM not supported by remote -> use Basic mode");
3447                 }
3448             }
3449 #endif
3450             continue;
3451         }
3452 
3453         // outgoing connection: information request is triggered before connection request
3454         if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
3455 
3456 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3457             // if ERTM was requested, but is not listed in extended feature mask:
3458             if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
3459 
3460                 if (channel->ertm_mandatory){
3461                     // bail if ERTM is mandatory
3462                     channel->state = L2CAP_STATE_CLOSED;
3463                     // map l2cap connection response result to BTstack status enumeration
3464                     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
3465                     // discard channel
3466                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3467                     l2cap_free_channel_entry(channel);
3468                     continue;
3469 
3470                 } else {
3471                     // fallback to Basic mode
3472                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3473                     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3474                 }
3475             }
3476 #endif
3477 
3478             // respond to connection request
3479             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
3480             continue;
3481         }
3482     }
3483 }
3484 #endif
3485 
3486 // @pre command len is valid, see check in l2cap_acl_classic_handler
3487 static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
3488 
3489     hci_connection_t * connection;
3490     btstack_linked_list_iterator_t it;
3491 
3492     // get code, signal identifier and command len
3493     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3494     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
3495     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3496 
3497     // general commands without an assigned channel
3498     switch(code) {
3499 
3500         case CONNECTION_REQUEST:
3501             if (cmd_len == 4){
3502                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3503                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3504                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
3505             } else {
3506                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3507             }
3508             return;
3509 
3510         case ECHO_REQUEST:
3511             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
3512             return;
3513 
3514         case INFORMATION_REQUEST:
3515             if (cmd_len == 2) {
3516                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3517                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
3518                 return;
3519             }
3520             break;
3521 
3522         case INFORMATION_RESPONSE:
3523             connection = hci_connection_for_handle(handle);
3524             if (!connection) return;
3525             switch (connection->l2cap_state.information_state){
3526                 case L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE:
3527                     // get extended features from response if valid
3528                     if (cmd_len >= 6) {
3529                         uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3530                         uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3531                         if (result == 0 && info_type == L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) {
3532                             connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3533                         }
3534                         log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
3535                         if ((connection->l2cap_state.extended_feature_mask & 0x80) != 0){
3536                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_FIXED_CHANNELS_REQUEST;
3537                         } else {
3538                             // information request complete
3539                             l2cap_handle_information_request_complete(connection);
3540                         }
3541                     }
3542                     break;
3543                 case L2CAP_INFORMATION_STATE_W4_FIXED_CHANNELS_RESPONSE:
3544                     if (cmd_len >= 12) {
3545                         uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3546                         uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3547                         if (result == 0 && info_type == L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED) {
3548                             connection->l2cap_state.fixed_channels_supported = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3549                         }
3550                         log_info("fixed channels mask 0x%02x", connection->l2cap_state.fixed_channels_supported);
3551                         // information request complete
3552                         l2cap_handle_information_request_complete(connection);
3553                     }
3554                     break;
3555                 default:
3556                     break;
3557             }
3558             return;
3559 
3560 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
3561         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
3562         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
3563         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
3564         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
3565             l2cap_ecbm_signaling_handler_dispatch(handle, L2CAP_CID_SIGNALING, command, sig_id);
3566             return;
3567         case L2CAP_FLOW_CONTROL_CREDIT_INDICATION:
3568             // return if valid
3569             if (l2cap_credit_based_handle_credit_indication(handle, command, cmd_len)) return;
3570             break;
3571 
3572         case COMMAND_REJECT:
3573             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3574             while (btstack_linked_list_iterator_has_next(&it)) {
3575                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3576                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3577                 if (channel->con_handle != handle) continue;
3578                 if (channel->local_sig_id != sig_id) continue;
3579                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE) continue;
3580 
3581                 // open failed
3582                 channel->state = L2CAP_STATE_CLOSED;
3583                 l2cap_ecbm_emit_channel_opened(channel,
3584                                                ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES);
3585                 // drop failed channel
3586                 btstack_linked_list_iterator_remove(&it);
3587                 l2cap_free_channel_entry(channel);
3588             }
3589             break;
3590 #endif
3591 
3592         default:
3593             break;
3594     }
3595 
3596     // Get potential destination CID
3597     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3598 
3599     // Find channel for this sig_id and connection handle
3600     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3601     while (btstack_linked_list_iterator_has_next(&it)){
3602         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3603         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3604         if (channel->con_handle != handle) continue;
3605         if (code & 1) {
3606             // match odd commands (responses) by previous signaling identifier
3607             if (channel->local_sig_id == sig_id) {
3608                 l2cap_signaling_handler_channel(channel, command);
3609                 return;
3610             }
3611         } else {
3612             // match even commands (requests) by local channel id
3613             if (channel->local_cid == dest_cid) {
3614                 l2cap_signaling_handler_channel(channel, command);
3615                 return;
3616             }
3617         }
3618     }
3619 
3620     // send command reject
3621     l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3622 }
3623 #endif
3624 
3625 #ifdef L2CAP_USES_CHANNELS
3626 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3627     btstack_linked_list_iterator_t it;
3628     btstack_linked_list_iterator_init(&it, services);
3629     while (btstack_linked_list_iterator_has_next(&it)){
3630         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
3631         if ( service->psm == psm){
3632             return service;
3633         };
3634     }
3635     return NULL;
3636 }
3637 #endif
3638 
3639 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
3640 
3641 static uint8_t l2cap_ecbm_setup_channels(btstack_linked_list_t * channels,
3642                                          btstack_packet_handler_t packet_handler, uint8_t num_channels,
3643                                          hci_connection_t * connection, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
3644     uint8_t i;
3645     uint8_t status = ERROR_CODE_SUCCESS;
3646     for (i=0;i<num_channels;i++){
3647         l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_ECBM, connection->address, connection->address_type, psm, mtu, security_level);
3648         if (!channel) {
3649             status = BTSTACK_MEMORY_ALLOC_FAILED;
3650             break;
3651         }
3652         channel->con_handle = connection->con_handle;
3653         btstack_linked_list_add_tail(channels, (btstack_linked_item_t *) channel);
3654     }
3655 
3656     // free channels if not all allocated
3657     if (status != ERROR_CODE_SUCCESS){
3658         while (true) {
3659             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_pop(channels);
3660             if (channel == NULL) break;
3661             l2cap_free_channel_entry(channel);
3662         }
3663     }
3664 
3665     return status;
3666 }
3667 
3668 static inline l2cap_service_t * l2cap_ecbm_get_service(uint16_t spsm){
3669     return l2cap_get_service_internal(&l2cap_enhanced_services, spsm);
3670 }
3671 
3672 static inline uint8_t l2cap_ecbm_status_for_result(uint16_t result) {
3673     switch (result) {
3674         case L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS:
3675             return ERROR_CODE_SUCCESS;
3676         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_SPSM_NOT_SUPPORTED:
3677             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_PSM;
3678         case L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INSUFFICIENT_RESOURCES_AVAILABLE:
3679             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_RESOURCES;
3680         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHENTICATION:
3681         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHORIZATION:
3682         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_ENCYRPTION_KEY_SIZE_TOO_SHORT:
3683         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_ENCRYPTION:
3684             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY;
3685         default:
3686             // invalid Source CID, Source CID already allocated, unacceptable parameters
3687             return L2CAP_CONNECTION_RESPONSE_UNKNOWN_ERROR;
3688     }
3689 }
3690 
3691 static int l2cap_ecbm_signaling_handler_dispatch(hci_con_handle_t handle, uint16_t signaling_cid, uint8_t *command,
3692                                                  uint8_t sig_id) {
3693 
3694     hci_connection_t *connection;
3695     btstack_linked_list_iterator_t it;
3696     l2cap_service_t *service;
3697     uint16_t spsm;
3698     uint8_t num_channels;
3699     uint16_t num_channels_and_signaling_cid;
3700     uint8_t i;
3701     uint16_t new_mtu;
3702     uint16_t new_mps;
3703     uint16_t initial_credits;
3704     uint16_t result;
3705     uint8_t status;
3706 
3707     uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3708     uint16_t len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3709     log_info("enhanced dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
3710 
3711     switch (code) {
3712         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
3713             // check size
3714             if (len < 10u) return 0u;
3715 
3716             // get hci connection, bail if not found (must not happen)
3717             connection = hci_connection_for_handle(handle);
3718             btstack_assert(connection != NULL);
3719 
3720             // get num channels to establish
3721             num_channels = (len - 8) / sizeof(uint16_t);
3722 
3723             // combine signaling cid and number channels for l2cap_register_signaling_response
3724             num_channels_and_signaling_cid = (num_channels << 8) | signaling_cid;
3725 
3726             // check if service registered
3727             spsm = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3728             service = l2cap_ecbm_get_service(spsm);
3729 
3730             if (service) {
3731 
3732                 uint16_t remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3733                 uint16_t remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3734                 uint16_t credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
3735 
3736                 // param: check remote mtu
3737                 if (service->mtu > remote_mtu) {
3738                     l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3739                                                       num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INVALID_PARAMETERS);
3740                     return 1;
3741                 }
3742 
3743                 // security: check authentication
3744                 if (service->required_security_level >= LEVEL_3) {
3745                     if (!gap_authenticated(handle)) {
3746                         l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3747                                                           num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHENTICATION);
3748                         return 1;
3749                     }
3750                 }
3751 
3752                 // security: check encryption
3753                 // L2CAP.TS.p31 does not check for Connection refused - insufficient encryption which might be send for no encryption
3754                 if (service->required_security_level >= LEVEL_2) {
3755                     if (gap_encryption_key_size(handle) < 16) {
3756                         l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3757                                                           num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_ENCYRPTION_KEY_SIZE_TOO_SHORT);
3758                         return 1;
3759                     }
3760                 }
3761 
3762                 // report the last result code != 0
3763                 result = 0;
3764                 // store one of the local cids for the event
3765                 uint16_t a_local_cid = 0;
3766                 for (i = 0; i < num_channels; i++) {
3767 
3768                     // check source cids
3769                     uint16_t source_cid = little_endian_read_16(command, 12 + (i * 2));
3770                     if (source_cid < 0x40u) {
3771                         result = L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INVALID_SOURCE_CID;
3772                         continue;
3773                     }
3774 
3775                     // go through list of channels for this ACL connection and check if we get a match
3776                     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3777                     bool source_cid_allocated = false;
3778                     while (btstack_linked_list_iterator_has_next(&it)) {
3779                         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3780                         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3781                         if (channel->con_handle != handle) continue;
3782                         if (channel->remote_cid != source_cid) continue;
3783                         source_cid_allocated = true;
3784                         break;
3785                     }
3786                     if (source_cid_allocated) {
3787                         result = 0x00a;
3788                         continue;
3789                     }
3790 
3791                     // setup channel
3792                     l2cap_channel_t *channel = l2cap_create_channel_entry(service->packet_handler,
3793                                                                           L2CAP_CHANNEL_TYPE_CHANNEL_ECBM,
3794                                                                           connection->address,
3795                                                                           connection->address_type, spsm,
3796                                                                           service->mtu,
3797                                                                           service->required_security_level);
3798 
3799                     if (channel == NULL) {
3800                         // Some connections refused – insufficient resources available
3801                         result = 0x004;
3802                         continue;
3803                     }
3804 
3805                     // setup state
3806                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
3807                     channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
3808                     channel->con_handle = connection->con_handle;
3809                     channel->remote_sig_id = sig_id;
3810                     channel->remote_cid = source_cid;
3811                     channel->remote_mtu = remote_mtu;
3812                     channel->remote_mps = remote_mps;
3813                     channel->credits_outgoing = credits_outgoing;
3814                     channel->cid_index = i;
3815                     channel->num_cids = num_channels;
3816 
3817                     // if more than one error, we can report any of them
3818                     channel->reason = result;
3819 
3820                     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
3821 
3822                     a_local_cid = channel->local_cid;
3823                 }
3824 
3825                 // if no channels have been created, all have been refused, and we can respond right away
3826                 if (a_local_cid == 0) {
3827                     l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3828                                                       num_channels_and_signaling_cid, result);
3829                     return 1;
3830                 }
3831 
3832                 // emit incoming data connection event
3833                 uint8_t event[16];
3834                 event[0] = L2CAP_EVENT_ECBM_INCOMING_CONNECTION;
3835                 event[1] = sizeof(event) - 2;
3836                 event[2] = connection->address_type;
3837                 reverse_bd_addr(connection->address, &event[3]);
3838                 little_endian_store_16(event, 9, connection->con_handle);
3839                 little_endian_store_16(event, 11, spsm);
3840                 event[13] = num_channels;
3841                 little_endian_store_16(event, 14, a_local_cid);
3842                 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
3843                 (*service->packet_handler)(HCI_EVENT_PACKET, a_local_cid, event, sizeof(event));
3844 
3845             } else {
3846                 l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3847                                                   num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_SPSM_NOT_SUPPORTED);
3848             }
3849             return 1;
3850 
3851         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
3852             // check size
3853             if (len < 10u) return 0u;
3854 
3855             // get hci connection, ignore if not found
3856             connection = hci_connection_for_handle(handle);
3857             if (connection == NULL) return 0;
3858 
3859             // get channel config: mtu, mps, initial credits, result
3860             new_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3861             new_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3862             initial_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3863             result = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
3864             status = l2cap_ecbm_status_for_result(result);
3865 
3866             // get num channels to modify
3867             num_channels = (len - 8) / sizeof(uint16_t);
3868             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3869             while (btstack_linked_list_iterator_has_next(&it)) {
3870                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3871                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3872                 if (channel->con_handle != handle) continue;
3873                 if (channel->local_sig_id != sig_id) continue;
3874                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE) continue;
3875                 if (channel->cid_index < num_channels) {
3876                     uint16_t remote_cid = little_endian_read_16(command, 12 + channel->cid_index * sizeof(uint16_t));
3877                     if (remote_cid != 0) {
3878                         channel->state = L2CAP_STATE_OPEN;
3879                         channel->remote_cid = remote_cid;
3880                         channel->remote_mtu = new_mtu;
3881                         channel->remote_mps = new_mps;
3882                         channel->credits_outgoing = initial_credits;
3883                         l2cap_ecbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
3884                         continue;
3885                     }
3886                 }
3887                 // open failed
3888                 l2cap_ecbm_emit_channel_opened(channel, status);
3889                 // drop failed channel
3890                 btstack_linked_list_iterator_remove(&it);
3891                 btstack_memory_l2cap_channel_free(channel);
3892             }
3893             return 1;
3894 
3895         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
3896             // check minimal size
3897             if (len < 6) return 0u;
3898 
3899             // get hci connection, bail if not found (must not happen)
3900             connection = hci_connection_for_handle(handle);
3901             btstack_assert(connection != NULL);
3902 
3903             // get num channels to modify
3904             num_channels = (len - 4) / sizeof(uint16_t);
3905 
3906             // get new mtu and mps
3907             new_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3908             new_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3909 
3910             // validate request
3911             result = 0;
3912             for (i = 0; i < num_channels; i++) {
3913                 // check cid
3914                 uint16_t remote_cid = little_endian_read_16(command, 8 + (i * sizeof(uint16_t)));
3915                 l2cap_channel_t *channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
3916                 if (channel == NULL) {
3917                     result = L2CAP_ECBM_RECONFIGURE_FAILED_DESTINATION_CID_INVALID;
3918                     break;
3919                 }
3920                 // check MTU is not reduced
3921                 if (channel->remote_mtu > new_mtu) {
3922                     result = L2CAP_ECBM_RECONFIGURE_FAILED_MTU_REDUCTION_NOT_ALLOWED;
3923                     break;
3924                 }
3925                 // check MPS reduction
3926                 if ((num_channels > 1) && (channel->remote_mps > new_mps)) {
3927                     result = L2CAP_ECBM_RECONFIGURE_FAILED_MPS_REDUCTION_MULTIPLE_CHANNELS;
3928                     break;
3929                 }
3930                 // check MPS valid
3931                 if (new_mps < l2cap_enhanced_mps_min) {
3932                     result = L2CAP_ECBM_RECONFIGURE_FAILED_UNACCEPTABLE_PARAMETERS;
3933                     break;
3934                 }
3935             }
3936 
3937             // send reject
3938             if (result != 0) {
3939                 l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST, sig_id, signaling_cid,
3940                                                   result);
3941                 return 1;
3942             }
3943 
3944             // update channels
3945             for (i = 0; i < num_channels; i++) {
3946                 uint16_t remote_cid = little_endian_read_16(command, 8 + (i * sizeof(uint16_t)));
3947                 l2cap_channel_t *channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
3948                 channel->remote_mps = new_mps;
3949                 channel->remote_mtu = new_mtu;
3950                 // emit event
3951                 uint8_t event[8];
3952                 event[0] = L2CAP_EVENT_ECBM_RECONFIGURED;
3953                 event[1] = sizeof(event) - 2;
3954                 little_endian_store_16(event, 2, channel->local_cid);
3955                 little_endian_store_16(event, 4, new_mtu);
3956                 little_endian_store_16(event, 6, new_mps);
3957                 l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3958             }
3959 
3960             // send accept
3961             l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST, sig_id, signaling_cid, 0);
3962             return 1;
3963 
3964         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
3965             // check size
3966             if (len < 2u) return 0u;
3967 
3968             result = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3969             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3970             while (btstack_linked_list_iterator_has_next(&it)) {
3971                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3972                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3973                 if (channel->con_handle != handle) continue;
3974                 if (channel->local_sig_id != sig_id) continue;
3975                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_RENEGOTIATION_RESPONSE) continue;
3976                 // complete request
3977                 if (result == 0) {
3978                     channel->receive_sdu_buffer = channel->renegotiate_sdu_buffer;
3979                     channel->local_mtu = channel->renegotiate_mtu;
3980                 }
3981                 channel->state = L2CAP_STATE_OPEN;
3982                 // emit event
3983                 l2cap_ecbm_emit_reconfigure_complete(channel, result);
3984             }
3985             break;
3986 
3987         default:
3988             btstack_unreachable();
3989             break;
3990     }
3991     return 0;
3992 }
3993 
3994 #endif
3995 
3996 #ifdef ENABLE_BLE
3997 
3998 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
3999     uint8_t event[6];
4000     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
4001     event[1] = 4;
4002     little_endian_store_16(event, 2, con_handle);
4003     little_endian_store_16(event, 4, result);
4004     l2cap_emit_event(event, sizeof(event));
4005 }
4006 
4007 // @return valid
4008 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
4009     hci_connection_t * connection;
4010     uint16_t result;
4011     uint8_t  event[12];
4012 
4013 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4014     l2cap_channel_t * channel;
4015     btstack_linked_list_iterator_t it;
4016 #endif
4017 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4018     uint16_t local_cid;
4019     uint16_t le_psm;
4020     l2cap_service_t * service;
4021     uint16_t source_cid;
4022 #endif
4023 
4024     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
4025     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
4026     log_info("le dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
4027 
4028     switch (code){
4029 
4030         case CONNECTION_PARAMETER_UPDATE_REQUEST:
4031             // check size
4032             if (len < 8u) return 0u;
4033             connection = hci_connection_for_handle(handle);
4034             if (connection != NULL){
4035                 if (connection->role != HCI_ROLE_MASTER){
4036                     // reject command without notifying upper layer when not in master role
4037                     return 0;
4038                 }
4039                 le_connection_parameter_range_t existing_range;
4040                 gap_get_connection_parameter_range(&existing_range);
4041                 uint16_t le_conn_interval_min   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
4042                 uint16_t le_conn_interval_max   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
4043                 uint16_t le_conn_latency        = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
4044                 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
4045 
4046                 int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
4047                 if (update_parameter){
4048                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
4049                     connection->le_conn_interval_min = le_conn_interval_min;
4050                     connection->le_conn_interval_max = le_conn_interval_max;
4051                     connection->le_conn_latency = le_conn_latency;
4052                     connection->le_supervision_timeout = le_supervision_timeout;
4053                 } else {
4054                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
4055                 }
4056                 connection->le_con_param_update_identifier = sig_id;
4057             }
4058 
4059             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
4060             event[1] = 8;
4061             little_endian_store_16(event, 2, handle);
4062             (void)memcpy(&event[4], &command[4], 8);
4063             l2cap_emit_event(event, sizeof(event));
4064             break;
4065 
4066         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
4067             // check size
4068             if (len < 2u) return 0u;
4069             result = little_endian_read_16(command, 4);
4070             l2cap_emit_connection_parameter_update_response(handle, result);
4071             break;
4072 
4073 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
4074         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
4075         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
4076         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
4077         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
4078             return l2cap_ecbm_signaling_handler_dispatch(handle, L2CAP_CID_SIGNALING_LE, command, sig_id);
4079 #endif
4080 
4081 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4082         case COMMAND_REJECT:
4083             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4084             while (btstack_linked_list_iterator_has_next(&it)){
4085                 channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4086                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4087                 if (channel->con_handle   != handle) continue;
4088                 if (channel->local_sig_id != sig_id) continue;
4089 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4090                 // if received while waiting for le connection response, assume legacy device
4091                 if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
4092                     channel->state = L2CAP_STATE_CLOSED;
4093                     // no official value for this, use: Connection refused – LE_PSM not supported
4094                     l2cap_cbm_emit_channel_opened(channel, L2CAP_CBM_CONNECTION_RESULT_SPSM_NOT_SUPPORTED);
4095 
4096                     // discard channel
4097                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4098                     l2cap_free_channel_entry(channel);
4099                     continue;
4100                 }
4101 #endif
4102 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
4103                 // if received while waiting for le connection response, assume legacy device
4104                 if (channel->state == L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE){
4105                     channel->state = L2CAP_STATE_CLOSED;
4106                     // treat as SPSM not supported
4107                     l2cap_ecbm_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_PSM);
4108 
4109                     // discard channel
4110                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4111                     l2cap_free_channel_entry(channel);
4112                     continue;
4113                 }
4114 #endif
4115             }
4116             break;
4117 #endif
4118 
4119 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4120         case LE_CREDIT_BASED_CONNECTION_REQUEST:
4121             // check size
4122             if (len < 10u) return 0u;
4123 
4124             // get hci connection, bail if not found (must not happen)
4125             connection = hci_connection_for_handle(handle);
4126             if (!connection) return 0;
4127 
4128             // check if service registered
4129             le_psm  = little_endian_read_16(command, 4);
4130             service = l2cap_cbm_get_service(le_psm);
4131             source_cid = little_endian_read_16(command, 6);
4132 
4133             if (service){
4134                 if (source_cid < 0x40u){
4135                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INVALID_SOURCE_CID);
4136                     return 1;
4137                 }
4138 
4139                 // go through list of channels for this ACL connection and check if we get a match
4140                 btstack_linked_list_iterator_init(&it, &l2cap_channels);
4141                 while (btstack_linked_list_iterator_has_next(&it)){
4142                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4143                     if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
4144                     if (a_channel->con_handle != handle) continue;
4145                     if (a_channel->remote_cid != source_cid) continue;
4146                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_SOURCE_CID_ALREADY_ALLOCATED);
4147                     return 1;
4148                 }
4149 
4150                 // security: check encryption
4151                 if (service->required_security_level >= LEVEL_2){
4152                     if (gap_encryption_key_size(handle) == 0){
4153                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_ENCRYPTION);
4154                         return 1;
4155                     }
4156                     // anything less than 16 byte key size is insufficient
4157                     if (gap_encryption_key_size(handle) < 16){
4158                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_ENCYRPTION_KEY_SIZE_TOO_SHORT);
4159                         return 1;
4160                     }
4161                 }
4162 
4163                 // security: check authentication
4164                 if (service->required_security_level >= LEVEL_3){
4165                     if (!gap_authenticated(handle)){
4166                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHENTICATION);
4167                         return 1;
4168                     }
4169                 }
4170 
4171                 // security: check authorization
4172                 if (service->required_security_level >= LEVEL_4){
4173                     if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
4174                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHORIZATION);
4175                         return 1;
4176                     }
4177                 }
4178 
4179                 // allocate channel
4180                 channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_CBM, connection->address,
4181                                                      BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
4182                 if (!channel){
4183                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE);
4184                     return 1;
4185                 }
4186 
4187                 channel->con_handle = handle;
4188                 channel->remote_cid = source_cid;
4189                 channel->remote_sig_id = sig_id;
4190                 channel->remote_mtu = little_endian_read_16(command, 8);
4191                 channel->remote_mps = little_endian_read_16(command, 10);
4192                 channel->credits_outgoing = little_endian_read_16(command, 12);
4193 
4194                 // set initial state
4195                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
4196                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
4197 
4198                 // add to connections list
4199                 btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
4200 
4201                 // post connection request event
4202                 l2cap_cbm_emit_incoming_connection(channel);
4203 
4204             } else {
4205                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_SPSM_NOT_SUPPORTED);
4206             }
4207             break;
4208 
4209         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
4210             // check size
4211             if (len < 10u) return 0u;
4212 
4213             // Find channel for this sig_id and connection handle
4214             channel = NULL;
4215             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4216             while (btstack_linked_list_iterator_has_next(&it)){
4217                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4218                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
4219                 if (a_channel->con_handle   != handle) continue;
4220                 if (a_channel->local_sig_id != sig_id) continue;
4221                 channel = a_channel;
4222                 break;
4223             }
4224             if (!channel) break;
4225 
4226             // cid + 0
4227             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
4228             if (result){
4229                 channel->state = L2CAP_STATE_CLOSED;
4230                 uint8_t status = l2cap_cbm_status_for_result(result);
4231                 l2cap_cbm_emit_channel_opened(channel, status);
4232 
4233                 // discard channel
4234                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4235                 l2cap_free_channel_entry(channel);
4236                 break;
4237             }
4238 
4239             // success
4240             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4241             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
4242             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
4243             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
4244             channel->state = L2CAP_STATE_OPEN;
4245             l2cap_cbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
4246             break;
4247 #endif
4248 
4249 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4250         case L2CAP_FLOW_CONTROL_CREDIT_INDICATION:
4251             return l2cap_credit_based_handle_credit_indication(handle, command, len) ? 1 : 0;
4252 
4253         case DISCONNECTION_REQUEST:
4254 
4255             // check size
4256             if (len < 4u) return 0u;
4257 
4258             // find channel
4259             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4260             channel = l2cap_get_channel_for_local_cid_and_handle(local_cid, handle);
4261             if (!channel) {
4262                 log_error("credit: no channel for cid 0x%02x", local_cid);
4263                 break;
4264             }
4265             channel->remote_sig_id = sig_id;
4266             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
4267             break;
4268 
4269         case DISCONNECTION_RESPONSE:
4270             // check size
4271             if (len < 4u) return 0u;
4272 
4273             // find channel
4274             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4275             channel = l2cap_get_channel_for_local_cid_and_handle(local_cid, handle);
4276             if (!channel) break;
4277             if (channel->local_sig_id == sig_id) {
4278                 if (channel->state == L2CAP_STATE_WAIT_DISCONNECT){
4279                     l2cap_finalize_channel_close(channel);
4280                 }
4281             }
4282             break;
4283 #endif
4284 
4285         default:
4286             // command unknown -> reject command
4287             return 0;
4288     }
4289     return 1;
4290 }
4291 #endif
4292 
4293 #ifdef ENABLE_CLASSIC
4294 static void l2cap_acl_classic_handler_for_channel(l2cap_channel_t * l2cap_channel, uint8_t * packet, uint16_t size){
4295 
4296     // forward data only in OPEN state
4297     if (l2cap_channel->state != L2CAP_STATE_OPEN) return;
4298 
4299 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4300     if (l2cap_channel->channel_type == L2CAP_CHANNEL_TYPE_CHANNEL_ECBM){
4301         l2cap_credit_based_handle_pdu(l2cap_channel, packet, size);
4302         return;
4303     }
4304 #endif
4305 
4306 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
4307     if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
4308 
4309         int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
4310 
4311         // assert control + FCS fields are inside
4312         if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) return;
4313 
4314         if (l2cap_channel->fcs_option){
4315             // verify FCS (required if one side requested it)
4316             uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
4317             uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
4318 
4319 #ifdef L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL
4320             // simulate fcs error
4321             static int counter = 0;
4322             if (++counter == L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL) {
4323                 log_info("Simulate fcs error");
4324                 fcs_calculated++;
4325                 counter = 0;
4326             }
4327 #endif
4328 
4329             if (fcs_calculated == fcs_packet){
4330                 log_info("Packet FCS 0x%04x verified", fcs_packet);
4331             } else {
4332                 log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
4333                 // ERTM State Machine in Bluetooth Spec does not handle 'I-Frame with invalid FCS'
4334                 return;
4335             }
4336         }
4337 
4338         // switch on packet type
4339         uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
4340         uint8_t  req_seq = (control >> 8) & 0x3f;
4341         int final = (control >> 7) & 0x01;
4342         if (control & 1){
4343             // S-Frame
4344             int poll  = (control >> 4) & 0x01;
4345             l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
4346             log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
4347             l2cap_ertm_tx_packet_state_t * tx_state;
4348             switch (s){
4349                 case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
4350                     log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
4351                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4352                     if (poll && final){
4353                         // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
4354                         log_error("P=F=1 in S-Frame");
4355                         break;
4356                     }
4357                     if (poll){
4358                         // check if we did request selective retransmission before <==> we have stored SDU segments
4359                         int i;
4360                         int num_stored_out_of_order_packets = 0;
4361                         for (i=0;i<l2cap_channel->num_rx_buffers;i++){
4362                             int index = l2cap_channel->rx_store_index + i;
4363                             if (index >= l2cap_channel->num_rx_buffers){
4364                                 index -= l2cap_channel->num_rx_buffers;
4365                             }
4366                             l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
4367                             if (!rx_state->valid) continue;
4368                             num_stored_out_of_order_packets++;
4369                         }
4370                         if (num_stored_out_of_order_packets){
4371                             l2cap_channel->send_supervisor_frame_selective_reject = 1;
4372                         } else {
4373                             l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
4374                         }
4375                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
4376                     }
4377                     if (final){
4378                         // Stop-MonitorTimer
4379                         l2cap_ertm_stop_monitor_timer(l2cap_channel);
4380                         // If UnackedFrames > 0 then Start-RetransTimer
4381                         if (l2cap_channel->unacked_frames){
4382                             l2cap_ertm_start_retransmission_timer(l2cap_channel);
4383                         }
4384                         // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
4385                         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4386                     }
4387                     break;
4388                 case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
4389                     log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
4390                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4391                     // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
4392                     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4393                     break;
4394                 case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
4395                     log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
4396                     break;
4397                 case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
4398                     log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
4399                     if (poll){
4400                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4401                     }
4402                     // find requested i-frame
4403                     tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
4404                     if (tx_state){
4405                         log_info("Retransmission for tx_seq %u requested", req_seq);
4406                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
4407                         tx_state->retransmission_requested = 1;
4408                         l2cap_channel->srej_active = 1;
4409                     }
4410                     break;
4411                 default:
4412                     break;
4413             }
4414         } else {
4415             // I-Frame
4416             // get control
4417             l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
4418             uint8_t tx_seq = (control >> 1) & 0x3f;
4419             log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
4420             log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
4421             log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
4422             l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4423             if (final){
4424                 // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
4425                 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4426             }
4427 
4428             // get SDU
4429             const uint8_t * payload_data = &packet[COMPLETE_L2CAP_HEADER+2];
4430             uint16_t        payload_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
4431 
4432             // assert SDU size is smaller or equal to our buffers
4433             uint16_t max_payload_size = 0;
4434             switch (sar){
4435                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
4436                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
4437                     // SDU Length + MPS
4438                     max_payload_size = l2cap_channel->local_mps + 2;
4439                     break;
4440                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
4441                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
4442                     max_payload_size = l2cap_channel->local_mps;
4443                     break;
4444                 default:
4445                     btstack_assert(false);
4446                     break;
4447             }
4448             if (payload_len > max_payload_size){
4449                 log_info("payload len %u > max payload %u -> drop packet", payload_len, max_payload_size);
4450                 return;
4451             }
4452 
4453             // check ordering
4454             if (l2cap_channel->expected_tx_seq == tx_seq){
4455                 log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
4456                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
4457                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
4458 
4459                 // process SDU
4460                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, payload_data, payload_len);
4461 
4462                 // process stored segments
4463                 while (true){
4464                     int index = l2cap_channel->rx_store_index;
4465                     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
4466                     if (!rx_state->valid) break;
4467 
4468                     log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
4469                     l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
4470                     l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
4471 
4472                     rx_state->valid = 0;
4473                     l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
4474 
4475                     // update rx store index
4476                     index++;
4477                     if (index >= l2cap_channel->num_rx_buffers){
4478                         index = 0;
4479                     }
4480                     l2cap_channel->rx_store_index = index;
4481                 }
4482 
4483                 //
4484                 l2cap_channel->send_supervisor_frame_receiver_ready = 1;
4485 
4486             } else {
4487                 int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
4488                 if (delta < 2){
4489                     // store segment
4490                     l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, payload_data, payload_len);
4491 
4492                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
4493                     l2cap_channel->send_supervisor_frame_selective_reject = 1;
4494                 } else {
4495                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
4496                     l2cap_channel->send_supervisor_frame_reject = 1;
4497                 }
4498             }
4499         }
4500         return;
4501     }
4502 #endif
4503 
4504     // check size
4505     uint16_t payload_size = size - COMPLETE_L2CAP_HEADER;
4506     if (l2cap_channel->local_mtu < payload_size) return;
4507 
4508     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], payload_size);
4509 }
4510 #endif
4511 
4512 static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
4513 #ifdef ENABLE_CLASSIC
4514     l2cap_channel_t * l2cap_channel;
4515     l2cap_fixed_channel_t * l2cap_fixed_channel;
4516 
4517     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
4518     uint8_t  broadcast_flag = READ_ACL_FLAGS(packet) >> 2;
4519     switch (channel_id) {
4520 
4521         case L2CAP_CID_SIGNALING: {
4522             if (broadcast_flag != 0) break;
4523             uint32_t command_offset = 8;
4524             while ((command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET) < size) {
4525                 // assert signaling command is fully inside packet
4526                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
4527                 uint32_t next_command_offset = command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
4528                 if (next_command_offset > size){
4529                     log_error("l2cap signaling command len invalid -> drop");
4530                     break;
4531                 }
4532                 // handle signaling command
4533                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
4534                 // go to next command
4535                 command_offset = next_command_offset;
4536             }
4537             break;
4538         }
4539 
4540         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
4541             if (broadcast_flag == 0) break;
4542             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL);
4543             if (!l2cap_fixed_channel) break;
4544             if (!l2cap_fixed_channel->packet_handler) break;
4545             (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4546             break;
4547 
4548 #ifdef ENABLE_BLE
4549         case L2CAP_CID_BR_EDR_SECURITY_MANAGER:
4550             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
4551             if ((l2cap_fixed_channel == NULL) || (l2cap_fixed_channel->packet_handler == NULL)){
4552                 // Pairing Failed
4553                 l2cap_register_signaling_response(handle, (uint8_t) SM_PAIRING_FAILED, 0, L2CAP_CID_BR_EDR_SECURITY_MANAGER, SM_REASON_PAIRING_NOT_SUPPORTED);
4554             } else {
4555                 (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4556             }
4557             break;
4558 #endif
4559 
4560         default:
4561             if (broadcast_flag != 0) break;
4562             // Find channel for this channel_id and connection handle
4563             l2cap_channel = l2cap_get_channel_for_local_cid_and_handle(channel_id, handle);
4564             if (l2cap_channel != NULL){
4565                 l2cap_acl_classic_handler_for_channel(l2cap_channel, packet, size);
4566             }
4567             break;
4568     }
4569 #else
4570     UNUSED(handle); // ok: no code
4571     UNUSED(packet); // ok: no code
4572     UNUSED(size);   // ok: no code
4573 #endif
4574 }
4575 
4576 static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
4577 #ifdef ENABLE_BLE
4578 
4579     l2cap_fixed_channel_t * l2cap_fixed_channel;
4580 
4581 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4582     l2cap_channel_t * l2cap_channel;
4583 #endif
4584     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
4585     switch (channel_id) {
4586 
4587         case L2CAP_CID_SIGNALING_LE: {
4588             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
4589             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
4590             if ((COMPLETE_L2CAP_HEADER + 4u + len) > size) break;
4591             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
4592             if (!valid){
4593                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
4594             }
4595             break;
4596         }
4597 
4598         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
4599             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL);
4600             if (!l2cap_fixed_channel) break;
4601             if (!l2cap_fixed_channel->packet_handler) break;
4602             (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4603             break;
4604 
4605         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
4606             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
4607             if ((l2cap_fixed_channel == NULL) || (l2cap_fixed_channel->packet_handler == NULL)){
4608                 // Pairing Failed
4609                 l2cap_register_signaling_response(handle, (uint8_t) SM_PAIRING_FAILED, 0, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, SM_REASON_PAIRING_NOT_SUPPORTED);
4610             } else {
4611                 (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4612             }
4613             break;
4614 
4615         default:
4616 
4617 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4618             l2cap_channel = l2cap_get_channel_for_local_cid_and_handle(channel_id, handle);
4619             if (l2cap_channel != NULL) {
4620                 l2cap_credit_based_handle_pdu(l2cap_channel, packet, size);
4621             }
4622 #endif
4623             break;
4624     }
4625 #else
4626     UNUSED(handle); // ok: no code
4627     UNUSED(packet); // ok: no code
4628     UNUSED(size);   // ok: no code
4629 #endif
4630 }
4631 
4632 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
4633     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
4634     UNUSED(channel);        // ok: there is no channel
4635 
4636     // Assert full L2CAP header present
4637     if (size < COMPLETE_L2CAP_HEADER) return;
4638 
4639     // Dispatch to Classic or LE handler (SCO packets are not dispatched to L2CAP)
4640     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
4641     hci_connection_t *conn = hci_connection_for_handle(handle);
4642     if (!conn) return;
4643     if (conn->address_type == BD_ADDR_TYPE_ACL){
4644         l2cap_acl_classic_handler(handle, packet, size);
4645     } else {
4646         l2cap_acl_le_handler(handle, packet, size);
4647     }
4648 
4649     l2cap_run();
4650 }
4651 
4652 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
4653 void l2cap_register_fixed_channel(btstack_packet_handler_t packet_handler, uint16_t channel_id) {
4654     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
4655     if (!channel) return;
4656     channel->packet_handler = packet_handler;
4657 }
4658 
4659 #ifdef L2CAP_USES_CHANNELS
4660 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
4661 void l2cap_finalize_channel_close(l2cap_channel_t * channel){
4662     channel->state = L2CAP_STATE_CLOSED;
4663     l2cap_handle_channel_closed(channel);
4664     // discard channel
4665     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4666     l2cap_free_channel_entry(channel);
4667 }
4668 #endif
4669 
4670 #ifdef ENABLE_CLASSIC
4671 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
4672     return l2cap_get_service_internal(&l2cap_services, psm);
4673 }
4674 
4675 static void l2cap_update_minimal_security_level(void){
4676     // update minimal service security level
4677     gap_security_level_t minimal_level = LEVEL_1;
4678     btstack_linked_list_iterator_t it;
4679     btstack_linked_list_iterator_init(&it, &l2cap_services);
4680     while (btstack_linked_list_iterator_has_next(&it)){
4681         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
4682         if (service->required_security_level > minimal_level){
4683             minimal_level = service->required_security_level;
4684         };
4685     }
4686     gap_set_minimal_service_security_level(minimal_level);
4687 }
4688 
4689 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
4690 
4691     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
4692 
4693     // check for alread registered psm
4694     l2cap_service_t *service = l2cap_get_service(psm);
4695     if (service) {
4696         log_error("register: PSM %u already registered", psm);
4697         return L2CAP_SERVICE_ALREADY_REGISTERED;
4698     }
4699 
4700     // alloc structure
4701     service = btstack_memory_l2cap_service_get();
4702     if (!service) {
4703         log_error("register: no memory for l2cap_service_t");
4704         return BTSTACK_MEMORY_ALLOC_FAILED;
4705     }
4706 
4707     // fill in
4708     service->psm = psm;
4709     service->mtu = mtu;
4710     service->packet_handler = service_packet_handler;
4711     service->required_security_level = security_level;
4712 
4713     // add to services list
4714     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
4715 
4716     l2cap_update_minimal_security_level();
4717 
4718 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
4719     // enable page scan
4720     gap_connectable_control(1);
4721 #endif
4722 
4723 
4724     return ERROR_CODE_SUCCESS;
4725 }
4726 
4727 uint8_t l2cap_unregister_service(uint16_t psm){
4728 
4729     log_info("unregister psm 0x%x", psm);
4730 
4731     l2cap_service_t *service = l2cap_get_service(psm);
4732     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
4733     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
4734     btstack_memory_l2cap_service_free(service);
4735 
4736     l2cap_update_minimal_security_level();
4737 
4738 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
4739     // disable page scan when no services registered
4740     if (btstack_linked_list_empty(&l2cap_services)) {
4741         gap_connectable_control(0);
4742     }
4743 #endif
4744 
4745     return ERROR_CODE_SUCCESS;
4746 }
4747 #endif
4748 
4749 
4750 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4751 
4752 static void l2cap_credit_based_send_pdu(l2cap_channel_t *channel) {
4753     btstack_assert(channel != NULL);
4754     btstack_assert(channel->send_sdu_buffer != NULL);
4755     btstack_assert(channel->credits_outgoing > 0);
4756 
4757     // send part of SDU
4758     hci_reserve_packet_buffer();
4759     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
4760     uint8_t *l2cap_payload = acl_buffer + 8;
4761     uint16_t pos = 0;
4762     if (!channel->send_sdu_pos) {
4763         // store SDU len
4764         channel->send_sdu_pos += 2u;
4765         little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
4766         pos += 2u;
4767     }
4768     uint16_t payload_size = btstack_min(channel->send_sdu_len + 2u - channel->send_sdu_pos, channel->remote_mps - pos);
4769     log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size,
4770              channel->credits_outgoing);
4771     (void) memcpy(&l2cap_payload[pos],
4772                   &channel->send_sdu_buffer[channel->send_sdu_pos - 2u],
4773                   payload_size); // -2 for virtual SDU len
4774     pos += payload_size;
4775     channel->send_sdu_pos += payload_size;
4776     l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
4777 
4778     channel->credits_outgoing--;
4779 
4780     // update state (mark SDU as done) before calling hci_send_acl_packet_buffer (trigger l2cap_le_send_pdu again)
4781     bool done = channel->send_sdu_pos >= (channel->send_sdu_len + 2u);
4782     if (done) {
4783         channel->send_sdu_buffer = NULL;
4784     }
4785 
4786     hci_send_acl_packet_buffer(8u + pos);
4787 
4788     if (done) {
4789         // send done event
4790         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CBM_PACKET_SENT);
4791         // inform about can send now
4792         l2cap_cbm_notify_channel_can_send(channel);
4793     }
4794 }
4795 
4796 static uint8_t l2cap_credit_based_send_data(uint16_t local_cid, const uint8_t * data, uint16_t size){
4797 
4798     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4799     if (!channel) {
4800         log_error("l2cap send, no channel for cid 0x%02x", local_cid);
4801         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4802     }
4803 
4804     if (size > channel->remote_mtu){
4805         log_error("l2cap send, cid 0x%02x, data length exceeds remote MTU.", local_cid);
4806         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
4807     }
4808 
4809     if (channel->send_sdu_buffer){
4810         log_info("l2cap send, cid 0x%02x, cannot send", local_cid);
4811         return BTSTACK_ACL_BUFFERS_FULL;
4812     }
4813 
4814     channel->send_sdu_buffer = data;
4815     channel->send_sdu_len    = size;
4816     channel->send_sdu_pos    = 0;
4817 
4818     l2cap_notify_channel_can_send();
4819     return ERROR_CODE_SUCCESS;
4820 }
4821 
4822 static uint8_t l2cap_credit_based_provide_credits(uint16_t local_cid, uint16_t credits){
4823     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4824     if (!channel) {
4825         log_error("le credits no channel for cid 0x%02x", local_cid);
4826         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4827     }
4828 
4829     // check state
4830     if (channel->state != L2CAP_STATE_OPEN){
4831         log_error("le credits but channel 0x%02x not open yet", local_cid);
4832     }
4833 
4834     // ignore if set to automatic credits
4835     if (channel->automatic_credits) return ERROR_CODE_SUCCESS;
4836 
4837     // assert incoming credits + credits <= 0xffff
4838     uint32_t total_credits = channel->credits_incoming;
4839     total_credits += channel->new_credits_incoming;
4840     total_credits += credits;
4841     if (total_credits > 0xffffu){
4842         log_error("le credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
4843                   channel->new_credits_incoming, credits);
4844     }
4845 
4846     // set credits_granted
4847     channel->new_credits_incoming += credits;
4848 
4849     // go
4850     l2cap_run();
4851     return ERROR_CODE_SUCCESS;
4852 }
4853 
4854 static void l2cap_credit_based_send_credits(l2cap_channel_t *channel) {
4855     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
4856     channel->local_sig_id = l2cap_next_sig_id();
4857     uint16_t new_credits = channel->new_credits_incoming;
4858     channel->new_credits_incoming = 0;
4859     channel->credits_incoming += new_credits;
4860     uint16_t signaling_cid = channel->address_type == BD_ADDR_TYPE_ACL ? L2CAP_CID_SIGNALING : L2CAP_CID_SIGNALING_LE;
4861     l2cap_send_general_signaling_packet(channel->con_handle, signaling_cid, L2CAP_FLOW_CONTROL_CREDIT_INDICATION, channel->local_sig_id, channel->local_cid, new_credits);
4862 }
4863 
4864 // @return valid
4865 static bool l2cap_credit_based_handle_credit_indication(hci_con_handle_t handle, const uint8_t * command, uint16_t len){
4866     // check size
4867     if (len < 4u) return false;
4868 
4869     // find channel
4870     uint16_t remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4871     l2cap_channel_t * channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
4872     if (!channel) {
4873         log_error("credit: no channel for handle 0x%04x/cid 0x%02x", handle, remote_cid);
4874         return true;
4875     }
4876     uint16_t new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
4877     uint16_t credits_before = channel->credits_outgoing;
4878     channel->credits_outgoing += new_credits;
4879     // check for credit overrun
4880     if (credits_before > channel->credits_outgoing) {
4881         log_error("credit: new credits caused overrrun for cid 0x%02x, disconnecting", channel->local_cid);
4882         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4883         return true;
4884     }
4885     log_info("credit: %u credits for 0x%02x, now %u", new_credits, channel->local_cid, channel->credits_outgoing);
4886     l2cap_call_notify_channel_in_run = true;
4887     return true;
4888 }
4889 
4890 static void l2cap_credit_based_handle_pdu(l2cap_channel_t * l2cap_channel, const uint8_t * packet, uint16_t size){
4891     // ignore empty packets
4892     if (size == COMPLETE_L2CAP_HEADER) return;
4893 
4894     // credit counting
4895     if (l2cap_channel->credits_incoming == 0u){
4896         log_info("(e)CBM: packet received but no incoming credits");
4897         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4898         return;
4899     }
4900     l2cap_channel->credits_incoming--;
4901 
4902     // automatic credits
4903     if ((l2cap_channel->credits_incoming < L2CAP_CREDIT_BASED_FLOW_CONTROL_MODE_AUTOMATIC_CREDITS_WATERMARK) && l2cap_channel->automatic_credits){
4904         l2cap_channel->new_credits_incoming = L2CAP_CREDIT_BASED_FLOW_CONTROL_MODE_AUTOMATIC_CREDITS_INCREMENT;
4905     }
4906 
4907     // first fragment
4908     uint16_t pos = 0;
4909     if (!l2cap_channel->receive_sdu_len){
4910         if (size < (COMPLETE_L2CAP_HEADER + 2)) return;
4911         uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
4912         if(sdu_len > l2cap_channel->local_mtu) return;   // SDU would be larger than our buffer
4913         l2cap_channel->receive_sdu_len = sdu_len;
4914         l2cap_channel->receive_sdu_pos = 0;
4915         pos  += 2u;
4916         size -= 2u;
4917     }
4918     uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
4919     uint16_t remaining_space = l2cap_channel->local_mtu - l2cap_channel->receive_sdu_pos;
4920     if (fragment_size > remaining_space) return;         // SDU would cause buffer overrun
4921     (void)memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos],
4922                  &packet[COMPLETE_L2CAP_HEADER + pos],
4923                  fragment_size);
4924     l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
4925     // done?
4926     log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
4927     if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
4928         l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
4929         l2cap_channel->receive_sdu_len = 0;
4930     }
4931 }
4932 
4933 static uint8_t l2cap_credit_based_disconnect(uint16_t local_cid){
4934     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4935     if (!channel) {
4936         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4937     }
4938     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4939     l2cap_run();
4940     return ERROR_CODE_SUCCESS;
4941 }
4942 #endif
4943 
4944 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4945 
4946 static void l2cap_cbm_notify_channel_can_send(l2cap_channel_t *channel){
4947     if (!channel->waiting_for_can_send_now) return;
4948     if (channel->send_sdu_buffer) return;
4949     channel->waiting_for_can_send_now = 0;
4950     log_debug("le can send now, local_cid 0x%x", channel->local_cid);
4951     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CBM_CAN_SEND_NOW);
4952 }
4953 
4954 // 1BH2222
4955 static void l2cap_cbm_emit_incoming_connection(l2cap_channel_t *channel) {
4956     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",
4957              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
4958     uint8_t event[19];
4959     event[0] = L2CAP_EVENT_CBM_INCOMING_CONNECTION;
4960     event[1] = sizeof(event) - 2u;
4961     event[2] = channel->address_type;
4962     reverse_bd_addr(channel->address, &event[3]);
4963     little_endian_store_16(event,  9, channel->con_handle);
4964     little_endian_store_16(event, 11, channel->psm);
4965     little_endian_store_16(event, 13, channel->local_cid);
4966     little_endian_store_16(event, 15, channel->remote_cid);
4967     little_endian_store_16(event, 17, channel->remote_mtu);
4968     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
4969     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
4970 }
4971 // 11BH22222
4972 static void l2cap_cbm_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
4973     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",
4974              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
4975              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
4976     uint8_t event[23];
4977     event[0] = L2CAP_EVENT_CBM_CHANNEL_OPENED;
4978     event[1] = sizeof(event) - 2u;
4979     event[2] = status;
4980     event[3] = channel->address_type;
4981     reverse_bd_addr(channel->address, &event[4]);
4982     little_endian_store_16(event, 10, channel->con_handle);
4983     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
4984     little_endian_store_16(event, 13, channel->psm);
4985     little_endian_store_16(event, 15, channel->local_cid);
4986     little_endian_store_16(event, 17, channel->remote_cid);
4987     little_endian_store_16(event, 19, channel->local_mtu);
4988     little_endian_store_16(event, 21, channel->remote_mtu);
4989     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
4990     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
4991 }
4992 // 2
4993 static void l2cap_cbm_emit_channel_closed(l2cap_channel_t * channel){
4994     log_info("closed local_cid 0x%x", channel->local_cid);
4995     uint8_t event[4];
4996     event[0] = L2CAP_EVENT_CBM_CHANNEL_CLOSED;
4997     event[1] = sizeof(event) - 2u;
4998     little_endian_store_16(event, 2, channel->local_cid);
4999     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
5000     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
5001 }
5002 
5003 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
5004 void l2cap_cbm_finialize_channel_close(l2cap_channel_t * channel){
5005     channel->state = L2CAP_STATE_CLOSED;
5006     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
5007     // discard channel
5008     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
5009     l2cap_free_channel_entry(channel);
5010 }
5011 
5012 static inline l2cap_service_t * l2cap_cbm_get_service(uint16_t le_psm){
5013     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
5014 }
5015 
5016 uint8_t l2cap_cbm_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
5017 
5018     log_info("l2cap_cbm_register_service psm 0x%x", psm);
5019 
5020     // check for alread registered psm
5021     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5022     if (service) {
5023         return L2CAP_SERVICE_ALREADY_REGISTERED;
5024     }
5025 
5026     // alloc structure
5027     service = btstack_memory_l2cap_service_get();
5028     if (!service) {
5029         log_error("register: no memory for l2cap_service_t");
5030         return BTSTACK_MEMORY_ALLOC_FAILED;
5031     }
5032 
5033     // fill in
5034     service->psm = psm;
5035     service->mtu = 0;
5036     service->packet_handler = packet_handler;
5037     service->required_security_level = security_level;
5038 
5039     // add to services list
5040     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
5041 
5042     // done
5043     return ERROR_CODE_SUCCESS;
5044 }
5045 
5046 uint8_t l2cap_cbm_unregister_service(uint16_t psm) {
5047     log_info("l2cap_cbm_unregister_service psm 0x%x", psm);
5048     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5049     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
5050 
5051     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
5052     btstack_memory_l2cap_service_free(service);
5053     return ERROR_CODE_SUCCESS;
5054 }
5055 
5056 uint8_t l2cap_cbm_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
5057     // get channel
5058     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5059     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5060 
5061     // validate state
5062     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
5063         return ERROR_CODE_COMMAND_DISALLOWED;
5064     }
5065 
5066     // set state accept connection
5067     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
5068     channel->receive_sdu_buffer = receive_sdu_buffer;
5069     channel->local_mtu = mtu;
5070     channel->new_credits_incoming = initial_credits;
5071     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5072 
5073     // go
5074     l2cap_run();
5075     return ERROR_CODE_SUCCESS;
5076 }
5077 
5078 uint8_t l2cap_cbm_decline_connection(uint16_t local_cid, uint16_t result) {
5079     // get channel
5080     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5081     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5082 
5083     // validate state
5084     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
5085         return ERROR_CODE_COMMAND_DISALLOWED;
5086     }
5087 
5088     // set state decline connection
5089     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
5090     channel->reason = L2CAP_CBM_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE;
5091     l2cap_run();
5092     return ERROR_CODE_SUCCESS;
5093 }
5094 
5095 static gap_security_level_t l2cap_cbm_security_level_for_connection(hci_con_handle_t con_handle){
5096     uint8_t encryption_key_size = gap_encryption_key_size(con_handle);
5097     if (encryption_key_size == 0) return LEVEL_0;
5098 
5099     uint8_t authenticated = gap_authenticated(con_handle);
5100     if (!authenticated) return LEVEL_2;
5101 
5102     return encryption_key_size == 16 ? LEVEL_4 : LEVEL_3;
5103 }
5104 
5105 // used to handle pairing complete after triggering to increase
5106 static void l2cap_cbm_sm_packet_handler(uint8_t packet_type, uint16_t channel_nr, uint8_t *packet, uint16_t size) {
5107     UNUSED(channel_nr);
5108     UNUSED(size);
5109     UNUSED(packet_type);
5110     btstack_assert(packet_type == HCI_EVENT_PACKET);
5111     if (hci_event_packet_get_type(packet) != SM_EVENT_PAIRING_COMPLETE) return;
5112     hci_con_handle_t con_handle = sm_event_pairing_complete_get_handle(packet);
5113     btstack_linked_list_iterator_t it;
5114     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5115     while (btstack_linked_list_iterator_has_next(&it)) {
5116         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5117         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5118         if (channel->con_handle != con_handle) continue;
5119         if (channel->state != L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE) continue;
5120 
5121         // found channel, check security level
5122         if (l2cap_cbm_security_level_for_connection(con_handle) < channel->required_security_level){
5123             // pairing failed or wasn't good enough, inform user
5124             l2cap_cbm_emit_channel_opened(channel, ERROR_CODE_INSUFFICIENT_SECURITY);
5125             // discard channel
5126             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
5127             l2cap_free_channel_entry(channel);
5128         } else {
5129             // send conn request now
5130             channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5131             l2cap_run();
5132         }
5133     }
5134 }
5135 
5136 uint8_t l2cap_cbm_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5137     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
5138     uint16_t * out_local_cid) {
5139 
5140     static btstack_packet_callback_registration_t sm_event_callback_registration;
5141     static bool sm_callback_registered = false;
5142 
5143     log_info("create, handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
5144 
5145     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5146     if (!connection) {
5147         log_error("no hci_connection for handle 0x%04x", con_handle);
5148         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5149     }
5150 
5151     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_CBM, connection->address, connection->address_type, psm, mtu, security_level);
5152     if (!channel) {
5153         return BTSTACK_MEMORY_ALLOC_FAILED;
5154     }
5155     log_info("created %p", channel);
5156 
5157     // store local_cid
5158     if (out_local_cid){
5159        *out_local_cid = channel->local_cid;
5160     }
5161 
5162     // setup channel entry
5163     channel->con_handle = con_handle;
5164     channel->receive_sdu_buffer = receive_sdu_buffer;
5165     channel->new_credits_incoming = initial_credits;
5166     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5167 
5168     // add to connections list
5169     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
5170 
5171     // check security level
5172     if (l2cap_cbm_security_level_for_connection(con_handle) < channel->required_security_level){
5173         if (!sm_callback_registered){
5174             sm_callback_registered = true;
5175             // lazy registration for SM events
5176             sm_event_callback_registration.callback = &l2cap_cbm_sm_packet_handler;
5177             sm_add_event_handler(&sm_event_callback_registration);
5178         }
5179 
5180         // start pairing
5181         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
5182         sm_request_pairing(con_handle);
5183     } else {
5184         // send conn request right away
5185         channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5186         l2cap_run();
5187     }
5188 
5189     return ERROR_CODE_SUCCESS;
5190 }
5191 
5192 uint8_t l2cap_cbm_provide_credits(uint16_t local_cid, uint16_t credits){
5193     return l2cap_credit_based_provide_credits(local_cid, credits);
5194 }
5195 
5196 bool l2cap_cbm_can_send_now(uint16_t local_cid){
5197     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5198     if (!channel) {
5199         log_error("le can send now, no channel for cid 0x%02x", local_cid);
5200         return false;
5201     }
5202 
5203     // check state
5204     if (channel->state != L2CAP_STATE_OPEN) return false;
5205 
5206     // check queue
5207     if (channel->send_sdu_buffer) return false;
5208 
5209     // fine, go ahead
5210     return true;
5211 }
5212 
5213 uint8_t l2cap_cbm_request_can_send_now_event(uint16_t local_cid){
5214     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5215     if (!channel) {
5216         log_error("can send now, no channel for cid 0x%02x", local_cid);
5217         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5218     }
5219     channel->waiting_for_can_send_now = 1;
5220     l2cap_cbm_notify_channel_can_send(channel);
5221     return ERROR_CODE_SUCCESS;
5222 }
5223 
5224 uint8_t l2cap_cbm_send_data(uint16_t local_cid, uint8_t * data, uint16_t size){
5225     return l2cap_credit_based_send_data(local_cid, data, size);
5226 }
5227 
5228 uint8_t l2cap_cbm_disconnect(uint16_t local_cid){
5229     return l2cap_credit_based_disconnect(local_cid);
5230 }
5231 #endif
5232 
5233 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
5234 
5235 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){
5236 
5237     // check for already registered psm
5238     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5239     if (service) {
5240         return L2CAP_SERVICE_ALREADY_REGISTERED;
5241     }
5242 
5243     // alloc structure
5244     service = btstack_memory_l2cap_service_get();
5245     if (!service) {
5246         log_error("register: no memory for l2cap_service_t");
5247         return BTSTACK_MEMORY_ALLOC_FAILED;
5248     }
5249 
5250     // fill in
5251     service->psm = psm;
5252     service->mtu = min_remote_mtu;
5253     service->packet_handler = packet_handler;
5254     service->required_security_level = security_level;
5255 
5256     // add to services list
5257     btstack_linked_list_add(&l2cap_enhanced_services, (btstack_linked_item_t *) service);
5258 
5259     // done
5260     return ERROR_CODE_SUCCESS;
5261 }
5262 
5263 uint8_t l2cap_ecbm_unregister_service(uint16_t psm) {
5264     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5265     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
5266 
5267     btstack_linked_list_remove(&l2cap_enhanced_services, (btstack_linked_item_t *) service);
5268     btstack_memory_l2cap_service_free(service);
5269     return ERROR_CODE_SUCCESS;
5270 }
5271 
5272 void l2cap_ecbm_mps_set_min(uint16_t mps_min){
5273     l2cap_enhanced_mps_min = mps_min;
5274 }
5275 
5276 void l2cap_ecbm_mps_set_max(uint16_t mps_max){
5277     l2cap_enhanced_mps_max = mps_max;
5278 }
5279 
5280 uint8_t l2cap_ecbm_create_channels(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5281                                        gap_security_level_t security_level,
5282                                        uint16_t psm, uint8_t num_channels, uint16_t initial_credits, uint16_t mtu,
5283                                        uint8_t ** receive_sdu_buffers, uint16_t * out_local_cid){
5284 
5285     log_info("create enhanced, handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
5286 
5287     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5288     if (!connection) {
5289         log_error("no hci_connection for handle 0x%04x", con_handle);
5290         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5291     }
5292 
5293     // setup all channels
5294     btstack_linked_list_t channels = NULL;
5295     uint8_t status = l2cap_ecbm_setup_channels(&channels, packet_handler, num_channels, connection, psm, mtu,
5296                                                security_level);
5297 
5298     // add to connections list and set state + local_sig_id
5299     l2cap_channel_t * channel;
5300     uint8_t i = 0;
5301     uint8_t local_sig_id = l2cap_next_sig_id();
5302     while (true) {
5303         channel = (l2cap_channel_t *) btstack_linked_list_pop(&channels);
5304         if (channel == NULL) break;
5305         channel->state              = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST;
5306         channel->local_sig_id       = local_sig_id;
5307         channel->cid_index = i;
5308         channel->num_cids = num_channels;
5309         channel->credits_incoming   = initial_credits;
5310         channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5311         channel->receive_sdu_buffer = receive_sdu_buffers[i];
5312         // store local_cid
5313         if (out_local_cid){
5314             out_local_cid[i] = channel->local_cid;
5315         }
5316         btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
5317         i++;
5318     }
5319 
5320 #if 0
5321     // check security level
5322     if (l2cap_le_security_level_for_connection(con_handle) < channel->required_security_level){
5323         if (!sm_callback_registered){
5324             sm_callback_registered = true;
5325             // lazy registration for SM events
5326             sm_event_callback_registration.callback = &l2cap_sm_packet_handler;
5327             sm_add_event_handler(&sm_event_callback_registration);
5328         }
5329 
5330         // start pairing
5331         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
5332         sm_request_pairing(con_handle);
5333     } else {
5334         // send conn request right away
5335         channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5336         l2cap_run();
5337     }
5338 #endif
5339 
5340     l2cap_run();
5341 
5342     return status;
5343 }
5344 
5345 uint8_t l2cap_ecbm_accept_channels(uint16_t local_cid, uint8_t num_channels, uint16_t initial_credits,
5346                                             uint16_t receive_buffer_size, uint8_t ** receive_buffers, uint16_t * out_local_cids){
5347 
5348     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5349     if (!channel) {
5350 
5351         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5352     }
5353     //
5354     hci_con_handle_t  con_handle    = channel->con_handle;
5355     uint8_t           local_sig_id  = channel->local_sig_id;
5356     uint8_t           channel_index = 0;
5357     btstack_linked_list_iterator_t it;
5358     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5359     while (btstack_linked_list_iterator_has_next(&it)) {
5360         channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5361         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5362         if (channel->con_handle != con_handle) continue;
5363         if (channel->local_sig_id != local_sig_id) continue;
5364         if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT) continue;
5365 
5366         if (channel_index < num_channels){
5367             // assign buffer and cid
5368             out_local_cids[channel_index] = channel->local_cid;
5369             channel->receive_sdu_buffer = receive_buffers[channel_index];
5370             channel->local_mtu = receive_buffer_size;
5371             channel->credits_incoming   = initial_credits;
5372             channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5373             channel_index++;
5374         } else {
5375             // clear local cid for response packet
5376             channel->local_cid = 0;
5377             channel->reason = L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INSUFFICIENT_RESOURCES_AVAILABLE;
5378         }
5379         // update state
5380         channel->state = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE;
5381     }
5382     l2cap_run();
5383     return ERROR_CODE_SUCCESS;
5384 }
5385 
5386 uint8_t l2cap_ecbm_decline_channels(uint16_t local_cid, uint16_t result){
5387     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5388     if (!channel) {
5389         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5390     }
5391     //
5392     hci_con_handle_t  con_handle    = channel->con_handle;
5393     uint8_t           local_sig_id  = channel->local_sig_id;
5394     btstack_linked_list_iterator_t it;
5395     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5396     while (btstack_linked_list_iterator_has_next(&it)) {
5397         channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5398         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5399         if (channel->con_handle != con_handle) continue;
5400         if (channel->local_sig_id != local_sig_id) continue;
5401         if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT) continue;
5402 
5403         // prepare response
5404         channel->local_cid = 0;
5405         channel->reason = result;
5406         channel->state = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE;
5407     }
5408     l2cap_run();
5409     return ERROR_CODE_SUCCESS;
5410 }
5411 
5412 uint8_t l2cap_ecbm_request_can_send_now_event(uint16_t local_cid){
5413     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5414     if (!channel) {
5415         log_error("can send now, no channel for cid 0x%02x", local_cid);
5416         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5417     }
5418     channel->waiting_for_can_send_now = 1;
5419     l2cap_cbm_notify_channel_can_send(channel);
5420     return ERROR_CODE_SUCCESS;
5421 }
5422 
5423 uint8_t l2cap_ecbm_reconfigure_channels(uint8_t num_cids, uint16_t * local_cids, int16_t receive_buffer_size, uint8_t ** receive_buffers){
5424     btstack_assert(receive_buffers != NULL);
5425     btstack_assert(local_cids != NULL);
5426 
5427     if (num_cids > L2CAP_ECBM_MAX_CID_ARRAY_SIZE){
5428         return ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS;
5429     }
5430 
5431     // check if all cids exist and have the same con handle
5432     uint8_t i;
5433     hci_con_handle_t con_handle = HCI_CON_HANDLE_INVALID;
5434     for (i = 0 ; i < num_cids ; i++){
5435         l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cids[i]);
5436         if (!channel) {
5437             return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5438         }
5439         if (channel->state != L2CAP_STATE_OPEN){
5440             return ERROR_CODE_COMMAND_DISALLOWED;
5441         }
5442         if (con_handle == HCI_CON_HANDLE_INVALID){
5443             con_handle = channel->con_handle;
5444         } else if (con_handle != channel->con_handle){
5445             return ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS;
5446         }
5447     }
5448     // set renegotiation data and state
5449     uint8_t sig_id = l2cap_next_sig_id();
5450     for (i = 0 ; i < num_cids ; i++){
5451         l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cids[i]);
5452         channel->cid_index = i;
5453         channel->num_cids = num_cids;
5454         channel->local_sig_id = sig_id;
5455         channel->renegotiate_mtu = receive_buffer_size;
5456         channel->renegotiate_sdu_buffer = receive_buffers[i];
5457         channel->state = L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST;
5458     }
5459 
5460 
5461     l2cap_run();
5462     return ERROR_CODE_SUCCESS;
5463 }
5464 
5465 uint8_t l2cap_ecbm_send_data(uint16_t local_cid, const uint8_t * data, uint16_t size){
5466     return l2cap_credit_based_send_data(local_cid, data, size);
5467 }
5468 
5469 uint8_t l2cap_ecbm_provide_credits(uint16_t local_cid, uint16_t credits){
5470     return l2cap_credit_based_provide_credits(local_cid, credits);
5471 }
5472 
5473 uint8_t l2cap_ecbm_disconnect(uint16_t local_cid){
5474     return l2cap_credit_based_disconnect(local_cid);
5475 }
5476 #endif
5477 
5478 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
5479 // @deprecated - please use l2cap_ertm_create_channel
5480 uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
5481                                   l2cap_ertm_config_t * ertm_contig, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
5482     log_error("deprecated - please use l2cap_ertm_create_channel");
5483     return l2cap_ertm_create_channel(packet_handler, address, psm, ertm_contig, buffer, size, out_local_cid);
5484 };
5485 
5486 // @deprecated - please use l2cap_ertm_accept_connection
5487 uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, l2cap_ertm_config_t * ertm_contig, uint8_t * buffer, uint32_t size){
5488     log_error("deprecated - please use l2cap_ertm_accept_connection");
5489     return l2cap_ertm_accept_connection(local_cid, ertm_contig, buffer, size);
5490 }
5491 #endif
5492 
5493 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
5494 // @deprecated - please use l2cap_cbm_register_service
5495 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
5496     log_error("deprecated - please use l2cap_cbm_register_service");
5497     return l2cap_cbm_register_service(packet_handler, psm, security_level);
5498 }
5499 
5500 // @deprecated - please use l2cap_cbm_unregister_service
5501 uint8_t l2cap_le_unregister_service(uint16_t psm){
5502     log_error("deprecated - please use l2cap_cbm_unregister_service");
5503     return l2cap_cbm_unregister_service(psm);
5504 }
5505 
5506 // @deprecated - please use l2cap_cbm_accept_connection
5507 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
5508     log_error("deprecated - please use l2cap_cbm_accept_connection");
5509     return l2cap_cbm_accept_connection(local_cid, receive_sdu_buffer, mtu, initial_credits);
5510 }
5511 
5512 // @deprecated - please use l2cap_cbm_decline_connection
5513 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
5514     log_error("deprecated - please use l2cap_cbm_decline_connection");
5515     return l2cap_cbm_decline_connection(local_cid, L2CAP_CBM_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE);
5516 }
5517 
5518 // @deprecated - please use l2cap_cbm_create_channel
5519 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5520                                 uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
5521                                 uint16_t * out_local_cid){
5522     log_error("deprecated - please use l2cap_cbm_create_channel");
5523     return l2cap_cbm_create_channel(packet_handler, con_handle, psm, receive_sdu_buffer, mtu, initial_credits, security_level, out_local_cid);
5524 }
5525 
5526 // @deprecated - please use l2cap_cbm_provide_credits
5527 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
5528     log_error("deprecated - please use l2cap_cbm_provide_credits");
5529     return l2cap_cbm_provide_credits(local_cid, credits);
5530 }
5531 
5532 // @deprecated - please use l2cap_cbm_can_send_now
5533 bool l2cap_le_can_send_now(uint16_t local_cid){
5534     log_error("deprecated - please use l2cap_cbm_can_send_now");
5535     return l2cap_cbm_can_send_now(local_cid);
5536 }
5537 
5538 // @deprecated - please use l2cap_cbm_request_can_send_now_event
5539 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
5540     log_error("deprecated - please use l2cap_cbm_request_can_send_now_event");
5541     return l2cap_cbm_request_can_send_now_event(local_cid);
5542 }
5543 
5544 // @deprecated - please use l2cap_cbm_send_data
5545 uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t size){
5546     log_error("deprecated - please use l2cap_cbm_send_data");
5547     return l2cap_cbm_send_data(local_cid, data, size);
5548 }
5549 
5550 // @deprecated - please use l2cap_cbm_disconnect
5551 uint8_t l2cap_le_disconnect(uint16_t local_cid){
5552     log_error("deprecated - please use l2cap_cbm_disconnect");
5553     return l2cap_cbm_disconnect(local_cid);
5554 }
5555 #endif
5556