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