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