xref: /btstack/src/l2cap.c (revision 0e83ff1de7450f0484724c20bb379961742912cb)
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                     {
3191                         uint16_t remote_mps = little_endian_read_16(command, pos + 7);
3192                         // optimize our tx buffer configuration based on actual remote mps if remote mps is smaller than planned
3193                         if (remote_mps < channel->remote_mps){
3194                             // get current tx storage
3195                             uint16_t num_bytes_per_tx_buffer_before = sizeof(l2cap_ertm_tx_packet_state_t) + channel->remote_mps;
3196                             uint16_t tx_storage = channel->num_tx_buffers * num_bytes_per_tx_buffer_before;
3197 
3198                             channel->remote_mps = remote_mps;
3199                             uint16_t num_bytes_per_tx_buffer_now = sizeof(l2cap_ertm_tx_packet_state_t) + channel->remote_mps;
3200                             channel->num_tx_buffers = tx_storage / num_bytes_per_tx_buffer_now;
3201                             uint32_t total_storage = (sizeof(l2cap_ertm_rx_packet_state_t) + channel->local_mps) * channel->num_rx_buffers + tx_storage + channel->local_mtu;
3202                             l2cap_ertm_setup_buffers(channel, (uint8_t *) channel->rx_packets_state, total_storage);
3203                         }
3204                         // limit remote mtu by our tx buffers. Include 2 bytes SDU Length
3205                         uint16_t effective_mtu = channel->remote_mps * channel->num_tx_buffers - 2;
3206                         channel->remote_mtu    = btstack_min( effective_mtu, channel->remote_mtu);
3207                     }
3208                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
3209                         channel->remote_tx_window_size,
3210                         channel->remote_max_transmit,
3211                         channel->remote_retransmission_timeout_ms,
3212                         channel->remote_monitor_timeout_ms,
3213                         channel->remote_mps);
3214                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
3215                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3216                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3217                     } else {
3218                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
3219                     }
3220                     break;
3221                 case L2CAP_CHANNEL_MODE_BASIC:
3222                     switch (mode){
3223                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
3224                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
3225                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
3226                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3227                             }
3228                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
3229                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
3230                             break;
3231                         default: // case L2CAP_CHANNEL_MODE_BASIC:
3232                             // TODO store and evaluate configuration
3233                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
3234                             break;
3235                     }
3236                     break;
3237                 default:
3238                     break;
3239             }
3240         }
3241         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
3242             use_fcs = command[pos];
3243         }
3244 #endif
3245         // check for unknown options
3246         if ((option_hint == 0) && ((option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) || (option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE))){
3247             log_info("l2cap cid %u, unknown option 0x%02x", channel->local_cid, option_type);
3248             channel->unknown_option = option_type;
3249             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
3250         }
3251         pos += length;
3252     }
3253 
3254 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3255         // "FCS" has precedence over "No FCS"
3256         uint8_t update = channel->fcs_option || use_fcs;
3257         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
3258         channel->fcs_option = update;
3259         // If ERTM mandatory, but remote didn't send Retransmission and Flowcontrol options -> disconnect
3260         if (((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM) == 0) & (channel->ertm_mandatory)){
3261             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3262         }
3263 #endif
3264 }
3265 
3266 // @pre command len is valid, see check in l2cap_signaling_handler_channel
3267 static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
3268     log_info("l2cap_signaling_handle_configure_response");
3269 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3270     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3271     uint16_t pos     = 10;
3272     while (pos < end_pos){
3273         uint8_t option_hint = command[pos] >> 7;
3274         uint8_t option_type = command[pos] & 0x7f;
3275         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
3276         pos++;
3277         uint8_t length = command[pos++];
3278 
3279         // Retransmission and Flow Control Option
3280         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
3281             switch (channel->mode){
3282                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
3283                     if (channel->ertm_mandatory){
3284                         // ??
3285                     } else {
3286                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
3287                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
3288                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3289                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3290                         }
3291                     }
3292                     break;
3293                 case L2CAP_CHANNEL_MODE_BASIC:
3294                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
3295                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
3296                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3297                     }
3298                     break;
3299                 default:
3300                     break;
3301             }
3302         }
3303 
3304         // check for unknown options
3305         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
3306             log_info("l2cap cid %u, unknown option 0x%02x", channel->local_cid, option_type);
3307             channel->unknown_option = option_type;
3308             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
3309         }
3310 
3311         pos += length;
3312     }
3313 #else
3314     UNUSED(channel);  // ok: no code
3315     UNUSED(result);   // ok: no code
3316     UNUSED(command);  // ok: no code
3317 #endif
3318 }
3319 
3320 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
3321     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
3322     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
3323     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
3324     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
3325     if (channel->state == L2CAP_STATE_OPEN) return 0;
3326     return 1;
3327 }
3328 
3329 
3330 // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
3331 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
3332 
3333     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3334     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
3335     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3336     uint16_t result = 0;
3337 
3338     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
3339 
3340     // handle DISCONNECT REQUESTS seperately
3341     if (code == DISCONNECTION_REQUEST){
3342         l2cap_handle_disconnect_request(channel, identifier);
3343         return;
3344     }
3345 
3346     // @STATEMACHINE(l2cap)
3347     switch (channel->state) {
3348 
3349         case L2CAP_STATE_WAIT_CONNECT_RSP:
3350             switch (code){
3351                 case CONNECTION_RESPONSE:
3352                     if (cmd_len < 8){
3353                         // command imcomplete
3354                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3355                         break;
3356                     }
3357                     l2cap_stop_rtx(channel);
3358                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3359                     switch (result) {
3360                         case 0:
3361                             // successful connection
3362                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3363                             channel->state = L2CAP_STATE_CONFIG;
3364                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
3365                             break;
3366                         case 1:
3367                             // connection pending. get some coffee, but start the ERTX
3368                             l2cap_start_ertx(channel);
3369                             break;
3370                         default:
3371                             // channel closed
3372                             channel->state = L2CAP_STATE_CLOSED;
3373                             // map l2cap connection response result to BTstack status enumeration
3374                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
3375 
3376                             // drop link key if security block
3377                             if ((L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result) == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
3378                                 gap_drop_link_key_for_bd_addr(channel->address);
3379                             }
3380 
3381                             // discard channel
3382                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3383                             l2cap_free_channel_entry(channel);
3384                             break;
3385                     }
3386                     break;
3387 
3388                 default:
3389                     //@TODO: implement other signaling packets
3390                     break;
3391             }
3392             break;
3393 
3394         case L2CAP_STATE_CONFIG:
3395             switch (code) {
3396                 case CONFIGURE_REQUEST:
3397                     if (cmd_len < 4){
3398                         // command incomplete
3399                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3400                         break;
3401                     }
3402                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
3403                     l2cap_signaling_handle_configure_request(channel, command);
3404                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
3405                         // only done if continuation not set
3406                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
3407                     }
3408                     break;
3409                 case CONFIGURE_RESPONSE:
3410                     if (cmd_len < 6){
3411                         // command incomplete
3412                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3413                         break;
3414                     }
3415                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3416                     l2cap_stop_rtx(channel);
3417                     l2cap_signaling_handle_configure_response(channel, result, command);
3418                     switch (result){
3419                         case 0: // success
3420                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
3421                             break;
3422                         case 4: // pending
3423                             l2cap_start_ertx(channel);
3424                             break;
3425                         default:
3426 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3427                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
3428                                 // remote does not offer ertm but it's required
3429                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3430                                 break;
3431                             }
3432 #endif
3433                             // retry on negative result
3434                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
3435                             break;
3436                     }
3437                     break;
3438                 default:
3439                     break;
3440             }
3441             if (l2cap_channel_ready_for_open(channel)){
3442 
3443 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3444                 // assert that packet can be stored in fragment buffers in ertm
3445                 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3446                     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
3447                     uint16_t usable_mtu = channel->num_tx_buffers == 1 ? effective_mps : channel->num_tx_buffers * effective_mps - 2;
3448                     if (usable_mtu < channel->remote_mtu){
3449                         log_info("Remote MTU %u > max storable ERTM packet, only using MTU = %u", channel->remote_mtu, usable_mtu);
3450                         channel->remote_mtu = usable_mtu;
3451                     }
3452                 }
3453 #endif
3454                 // for open:
3455                 channel->state = L2CAP_STATE_OPEN;
3456                 l2cap_emit_channel_opened(channel, 0);
3457             }
3458             break;
3459 
3460         case L2CAP_STATE_WAIT_DISCONNECT:
3461             switch (code) {
3462                 case DISCONNECTION_RESPONSE:
3463                     l2cap_finalize_channel_close(channel);
3464                     break;
3465                 default:
3466                     //@TODO: implement other signaling packets
3467                     break;
3468             }
3469             break;
3470 
3471         case L2CAP_STATE_CLOSED:
3472             // @TODO handle incoming requests
3473             break;
3474 
3475         case L2CAP_STATE_OPEN:
3476             //@TODO: implement other signaling packets, e.g. re-configure
3477             break;
3478         default:
3479             break;
3480     }
3481     // log_info("new state %u", channel->state);
3482 }
3483 
3484 #ifdef ENABLE_CLASSIC
3485 static void l2cap_handle_information_request_complete(hci_connection_t * connection){
3486 
3487     connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
3488 
3489     // emit event
3490     uint8_t event[8];
3491     event[0] = L2CAP_EVENT_INFORMATION_RESPONSE;
3492     event[1] = sizeof(event) - 2;
3493     little_endian_store_16(event, 2, connection->con_handle);
3494     little_endian_store_16(event, 4, connection->l2cap_state.extended_feature_mask);
3495     little_endian_store_16(event, 6, connection->l2cap_state.fixed_channels_supported);
3496     l2cap_emit_event(event, sizeof(event));
3497 
3498     // trigger connection request
3499     btstack_linked_list_iterator_t it;
3500     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3501     while (btstack_linked_list_iterator_has_next(&it)){
3502         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3503         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3504         if (channel->con_handle != connection->con_handle) continue;
3505 
3506         // incoming connection: information request was triggered after user has accepted connection,
3507         // now: verify channel configuration, esp. if ertm will be mandatory
3508         if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
3509             // default: continue
3510             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
3511 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3512             if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
3513                 // ERTM not possible, select basic mode and release buffer
3514                 channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3515                 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3516 
3517                 // bail if ERTM is mandatory
3518                 if (channel->ertm_mandatory){
3519                     // We chose 'no resources available' for "ERTM mandatory but you don't even know ERTM exists"
3520                     log_info("ERTM mandatory -> reject connection");
3521                     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
3522                     channel->reason = L2CAP_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE;
3523                 }  else {
3524                     log_info("ERTM not supported by remote -> use Basic mode");
3525                 }
3526             }
3527 #endif
3528             continue;
3529         }
3530 
3531         // outgoing connection: information request is triggered before connection request
3532         if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
3533 
3534 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3535             // if ERTM was requested, but is not listed in extended feature mask:
3536             if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
3537 
3538                 if (channel->ertm_mandatory){
3539                     // bail if ERTM is mandatory
3540                     channel->state = L2CAP_STATE_CLOSED;
3541                     // map l2cap connection response result to BTstack status enumeration
3542                     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
3543                     // discard channel
3544                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3545                     l2cap_free_channel_entry(channel);
3546                     continue;
3547 
3548                 } else {
3549                     // fallback to Basic mode
3550                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3551                     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3552                 }
3553             }
3554 #endif
3555 
3556             // respond to connection request
3557             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
3558             continue;
3559         }
3560     }
3561 }
3562 #endif
3563 
3564 // @pre command len is valid, see check in l2cap_acl_classic_handler
3565 static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
3566 
3567     hci_connection_t * connection;
3568     btstack_linked_list_iterator_t it;
3569 
3570     // get code, signal identifier and command len
3571     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3572     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
3573     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3574 
3575     // general commands without an assigned channel
3576     switch(code) {
3577 
3578         case CONNECTION_REQUEST:
3579             if (cmd_len == 4){
3580                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3581                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3582                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
3583             } else {
3584                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3585             }
3586             return;
3587 
3588         case ECHO_REQUEST:
3589             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
3590             return;
3591 
3592         case INFORMATION_REQUEST:
3593             if (cmd_len == 2) {
3594                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3595                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
3596                 return;
3597             }
3598             break;
3599 
3600         case INFORMATION_RESPONSE:
3601             connection = hci_connection_for_handle(handle);
3602             if (!connection) return;
3603             switch (connection->l2cap_state.information_state){
3604                 case L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE:
3605                     // get extended features from response if valid
3606                     if (cmd_len >= 6) {
3607                         uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3608                         uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3609                         if (result == 0 && info_type == L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) {
3610                             connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3611                         }
3612                         log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
3613                         if ((connection->l2cap_state.extended_feature_mask & 0x80) != 0){
3614                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_FIXED_CHANNELS_REQUEST;
3615                         } else {
3616                             // information request complete
3617                             l2cap_handle_information_request_complete(connection);
3618                         }
3619                     }
3620                     break;
3621                 case L2CAP_INFORMATION_STATE_W4_FIXED_CHANNELS_RESPONSE:
3622                     if (cmd_len >= 12) {
3623                         uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3624                         uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3625                         if (result == 0 && info_type == L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED) {
3626                             connection->l2cap_state.fixed_channels_supported = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3627                         }
3628                         log_info("fixed channels mask 0x%02x", connection->l2cap_state.fixed_channels_supported);
3629                         // information request complete
3630                         l2cap_handle_information_request_complete(connection);
3631                     }
3632                     break;
3633                 default:
3634                     break;
3635             }
3636             return;
3637 
3638 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
3639         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
3640         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
3641         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
3642         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
3643             l2cap_ecbm_signaling_handler_dispatch(handle, L2CAP_CID_SIGNALING, command, sig_id);
3644             return;
3645         case L2CAP_FLOW_CONTROL_CREDIT_INDICATION:
3646             // return if valid
3647             if (l2cap_credit_based_handle_credit_indication(handle, command, cmd_len)) return;
3648             break;
3649 
3650         case COMMAND_REJECT:
3651             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3652             while (btstack_linked_list_iterator_has_next(&it)) {
3653                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3654                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3655                 if (channel->con_handle != handle) continue;
3656                 if (channel->local_sig_id != sig_id) continue;
3657                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE) continue;
3658 
3659                 // open failed
3660                 channel->state = L2CAP_STATE_CLOSED;
3661                 l2cap_ecbm_emit_channel_opened(channel,
3662                                                ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES);
3663                 // drop failed channel
3664                 btstack_linked_list_iterator_remove(&it);
3665                 l2cap_free_channel_entry(channel);
3666             }
3667             break;
3668 #endif
3669 
3670         default:
3671             break;
3672     }
3673 
3674     // Get potential destination CID
3675     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3676 
3677     // Find channel for this sig_id and connection handle
3678     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3679     while (btstack_linked_list_iterator_has_next(&it)){
3680         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3681         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3682         if (channel->con_handle != handle) continue;
3683         if (code & 1) {
3684             // match odd commands (responses) by previous signaling identifier
3685             if (channel->local_sig_id == sig_id) {
3686                 l2cap_signaling_handler_channel(channel, command);
3687                 return;
3688             }
3689         } else {
3690             // match even commands (requests) by local channel id
3691             if (channel->local_cid == dest_cid) {
3692                 l2cap_signaling_handler_channel(channel, command);
3693                 return;
3694             }
3695         }
3696     }
3697 
3698     // send command reject
3699     l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3700 }
3701 #endif
3702 
3703 #ifdef L2CAP_USES_CHANNELS
3704 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3705     btstack_linked_list_iterator_t it;
3706     btstack_linked_list_iterator_init(&it, services);
3707     while (btstack_linked_list_iterator_has_next(&it)){
3708         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
3709         if ( service->psm == psm){
3710             return service;
3711         };
3712     }
3713     return NULL;
3714 }
3715 #endif
3716 
3717 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
3718 
3719 static uint8_t l2cap_ecbm_setup_channels(btstack_linked_list_t * channels,
3720                                          btstack_packet_handler_t packet_handler, uint8_t num_channels,
3721                                          hci_connection_t * connection, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
3722     uint8_t i;
3723     uint8_t status = ERROR_CODE_SUCCESS;
3724     for (i=0;i<num_channels;i++){
3725         l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_ECBM, connection->address, connection->address_type, psm, mtu, security_level);
3726         if (!channel) {
3727             status = BTSTACK_MEMORY_ALLOC_FAILED;
3728             break;
3729         }
3730         channel->con_handle = connection->con_handle;
3731         btstack_linked_list_add_tail(channels, (btstack_linked_item_t *) channel);
3732     }
3733 
3734     // free channels if not all allocated
3735     if (status != ERROR_CODE_SUCCESS){
3736         while (true) {
3737             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_pop(channels);
3738             if (channel == NULL) break;
3739             l2cap_free_channel_entry(channel);
3740         }
3741     }
3742 
3743     return status;
3744 }
3745 
3746 static inline l2cap_service_t * l2cap_ecbm_get_service(uint16_t spsm){
3747     return l2cap_get_service_internal(&l2cap_enhanced_services, spsm);
3748 }
3749 
3750 static inline uint8_t l2cap_ecbm_status_for_result(uint16_t result) {
3751     switch (result) {
3752         case L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS:
3753             return ERROR_CODE_SUCCESS;
3754         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_SPSM_NOT_SUPPORTED:
3755             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_PSM;
3756         case L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INSUFFICIENT_RESOURCES_AVAILABLE:
3757             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_RESOURCES;
3758         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHENTICATION:
3759         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHORIZATION:
3760         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_ENCYRPTION_KEY_SIZE_TOO_SHORT:
3761         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_ENCRYPTION:
3762             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY;
3763         default:
3764             // invalid Source CID, Source CID already allocated, unacceptable parameters
3765             return L2CAP_CONNECTION_RESPONSE_UNKNOWN_ERROR;
3766     }
3767 }
3768 
3769 static int l2cap_ecbm_signaling_handler_dispatch(hci_con_handle_t handle, uint16_t signaling_cid, uint8_t *command,
3770                                                  uint8_t sig_id) {
3771 
3772     hci_connection_t *connection;
3773     btstack_linked_list_iterator_t it;
3774     l2cap_service_t *service;
3775     uint16_t spsm;
3776     uint8_t num_channels;
3777     uint16_t num_channels_and_signaling_cid;
3778     uint8_t i;
3779     uint16_t new_mtu;
3780     uint16_t new_mps;
3781     uint16_t initial_credits;
3782     uint16_t result;
3783     uint8_t status;
3784 
3785     uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3786     uint16_t len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3787     log_info("enhanced dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
3788 
3789     switch (code) {
3790         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
3791             // check size
3792             if (len < 10u) return 0u;
3793 
3794             // get hci connection, bail if not found (must not happen)
3795             connection = hci_connection_for_handle(handle);
3796             btstack_assert(connection != NULL);
3797 
3798             // get num channels to establish
3799             num_channels = (len - 8) / sizeof(uint16_t);
3800 
3801             // combine signaling cid and number channels for l2cap_register_signaling_response
3802             num_channels_and_signaling_cid = (num_channels << 8) | signaling_cid;
3803 
3804             // check if service registered
3805             spsm = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3806             service = l2cap_ecbm_get_service(spsm);
3807 
3808             if (service) {
3809 
3810                 uint16_t remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3811                 uint16_t remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3812                 uint16_t credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
3813 
3814                 // param: check remote mtu
3815                 if (service->mtu > remote_mtu) {
3816                     l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3817                                                       num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INVALID_PARAMETERS);
3818                     return 1;
3819                 }
3820 
3821                 // security: check authentication
3822                 if (service->required_security_level >= LEVEL_3) {
3823                     if (!gap_authenticated(handle)) {
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_INSUFFICIENT_AUTHENTICATION);
3826                         return 1;
3827                     }
3828                 }
3829 
3830                 // security: check encryption
3831                 // L2CAP.TS.p31 does not check for Connection refused - insufficient encryption which might be send for no encryption
3832                 if (service->required_security_level >= LEVEL_2) {
3833                     if (gap_encryption_key_size(handle) < 16) {
3834                         l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3835                                                           num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_ENCYRPTION_KEY_SIZE_TOO_SHORT);
3836                         return 1;
3837                     }
3838                 }
3839 
3840                 // report the last result code != 0
3841                 result = 0;
3842                 // store one of the local cids for the event
3843                 uint16_t a_local_cid = 0;
3844                 for (i = 0; i < num_channels; i++) {
3845 
3846                     // check source cids
3847                     uint16_t source_cid = little_endian_read_16(command, 12 + (i * 2));
3848                     if (source_cid < 0x40u) {
3849                         result = L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INVALID_SOURCE_CID;
3850                         continue;
3851                     }
3852 
3853                     // go through list of channels for this ACL connection and check if we get a match
3854                     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3855                     bool source_cid_allocated = false;
3856                     while (btstack_linked_list_iterator_has_next(&it)) {
3857                         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3858                         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3859                         if (channel->con_handle != handle) continue;
3860                         if (channel->remote_cid != source_cid) continue;
3861                         source_cid_allocated = true;
3862                         break;
3863                     }
3864                     if (source_cid_allocated) {
3865                         result = 0x00a;
3866                         continue;
3867                     }
3868 
3869                     // setup channel
3870                     l2cap_channel_t *channel = l2cap_create_channel_entry(service->packet_handler,
3871                                                                           L2CAP_CHANNEL_TYPE_CHANNEL_ECBM,
3872                                                                           connection->address,
3873                                                                           connection->address_type, spsm,
3874                                                                           service->mtu,
3875                                                                           service->required_security_level);
3876 
3877                     if (channel == NULL) {
3878                         // Some connections refused – insufficient resources available
3879                         result = 0x004;
3880                         continue;
3881                     }
3882 
3883                     // setup state
3884                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
3885                     channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
3886                     channel->con_handle = connection->con_handle;
3887                     channel->remote_sig_id = sig_id;
3888                     channel->remote_cid = source_cid;
3889                     channel->remote_mtu = remote_mtu;
3890                     channel->remote_mps = remote_mps;
3891                     channel->credits_outgoing = credits_outgoing;
3892                     channel->cid_index = i;
3893                     channel->num_cids = num_channels;
3894 
3895                     // if more than one error, we can report any of them
3896                     channel->reason = result;
3897 
3898                     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
3899 
3900                     a_local_cid = channel->local_cid;
3901                 }
3902 
3903                 // if no channels have been created, all have been refused, and we can respond right away
3904                 if (a_local_cid == 0) {
3905                     l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3906                                                       num_channels_and_signaling_cid, result);
3907                     return 1;
3908                 }
3909 
3910                 // emit incoming data connection event
3911                 uint8_t event[16];
3912                 event[0] = L2CAP_EVENT_ECBM_INCOMING_CONNECTION;
3913                 event[1] = sizeof(event) - 2;
3914                 event[2] = connection->address_type;
3915                 reverse_bd_addr(connection->address, &event[3]);
3916                 little_endian_store_16(event, 9, connection->con_handle);
3917                 little_endian_store_16(event, 11, spsm);
3918                 event[13] = num_channels;
3919                 little_endian_store_16(event, 14, a_local_cid);
3920                 hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
3921                 (*service->packet_handler)(HCI_EVENT_PACKET, a_local_cid, event, sizeof(event));
3922 
3923             } else {
3924                 l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3925                                                   num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_SPSM_NOT_SUPPORTED);
3926             }
3927             return 1;
3928 
3929         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
3930             // check size
3931             if (len < 10u) return 0u;
3932 
3933             // get hci connection, ignore if not found
3934             connection = hci_connection_for_handle(handle);
3935             if (connection == NULL) return 0;
3936 
3937             // get channel config: mtu, mps, initial credits, result
3938             new_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3939             new_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3940             initial_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3941             result = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
3942             status = l2cap_ecbm_status_for_result(result);
3943 
3944             // get num channels to modify
3945             num_channels = (len - 8) / sizeof(uint16_t);
3946             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3947             while (btstack_linked_list_iterator_has_next(&it)) {
3948                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3949                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3950                 if (channel->con_handle != handle) continue;
3951                 if (channel->local_sig_id != sig_id) continue;
3952                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE) continue;
3953                 if (channel->cid_index < num_channels) {
3954                     uint16_t remote_cid = little_endian_read_16(command, 12 + channel->cid_index * sizeof(uint16_t));
3955                     if (remote_cid != 0) {
3956                         channel->state = L2CAP_STATE_OPEN;
3957                         channel->remote_cid = remote_cid;
3958                         channel->remote_mtu = new_mtu;
3959                         channel->remote_mps = new_mps;
3960                         channel->credits_outgoing = initial_credits;
3961                         l2cap_ecbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
3962                         continue;
3963                     }
3964                 }
3965                 // open failed
3966                 l2cap_ecbm_emit_channel_opened(channel, status);
3967                 // drop failed channel
3968                 btstack_linked_list_iterator_remove(&it);
3969                 btstack_memory_l2cap_channel_free(channel);
3970             }
3971             return 1;
3972 
3973         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
3974             // check minimal size
3975             if (len < 6) return 0u;
3976 
3977             // get hci connection, bail if not found (must not happen)
3978             connection = hci_connection_for_handle(handle);
3979             btstack_assert(connection != NULL);
3980 
3981             // get num channels to modify
3982             num_channels = (len - 4) / sizeof(uint16_t);
3983 
3984             // get new mtu and mps
3985             new_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3986             new_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3987 
3988             // validate request
3989             result = 0;
3990             for (i = 0; i < num_channels; i++) {
3991                 // check cid
3992                 uint16_t remote_cid = little_endian_read_16(command, 8 + (i * sizeof(uint16_t)));
3993                 l2cap_channel_t *channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
3994                 if (channel == NULL) {
3995                     result = L2CAP_ECBM_RECONFIGURE_FAILED_DESTINATION_CID_INVALID;
3996                     break;
3997                 }
3998                 // check MTU is not reduced
3999                 if (channel->remote_mtu > new_mtu) {
4000                     result = L2CAP_ECBM_RECONFIGURE_FAILED_MTU_REDUCTION_NOT_ALLOWED;
4001                     break;
4002                 }
4003                 // check MPS reduction
4004                 if ((num_channels > 1) && (channel->remote_mps > new_mps)) {
4005                     result = L2CAP_ECBM_RECONFIGURE_FAILED_MPS_REDUCTION_MULTIPLE_CHANNELS;
4006                     break;
4007                 }
4008                 // check MPS valid
4009                 if (new_mps < l2cap_enhanced_mps_min) {
4010                     result = L2CAP_ECBM_RECONFIGURE_FAILED_UNACCEPTABLE_PARAMETERS;
4011                     break;
4012                 }
4013             }
4014 
4015             // send reject
4016             if (result != 0) {
4017                 l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST, sig_id, signaling_cid,
4018                                                   result);
4019                 return 1;
4020             }
4021 
4022             // update channels
4023             for (i = 0; i < num_channels; i++) {
4024                 uint16_t remote_cid = little_endian_read_16(command, 8 + (i * sizeof(uint16_t)));
4025                 l2cap_channel_t *channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
4026                 channel->remote_mps = new_mps;
4027                 channel->remote_mtu = new_mtu;
4028                 // emit event
4029                 uint8_t event[8];
4030                 event[0] = L2CAP_EVENT_ECBM_RECONFIGURED;
4031                 event[1] = sizeof(event) - 2;
4032                 little_endian_store_16(event, 2, channel->local_cid);
4033                 little_endian_store_16(event, 4, new_mtu);
4034                 little_endian_store_16(event, 6, new_mps);
4035                 l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
4036             }
4037 
4038             // send accept
4039             l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST, sig_id, signaling_cid, 0);
4040             return 1;
4041 
4042         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
4043             // check size
4044             if (len < 2u) return 0u;
4045 
4046             result = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4047             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4048             while (btstack_linked_list_iterator_has_next(&it)) {
4049                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4050                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4051                 if (channel->con_handle != handle) continue;
4052                 if (channel->local_sig_id != sig_id) continue;
4053                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_RENEGOTIATION_RESPONSE) continue;
4054                 // complete request
4055                 if (result == 0) {
4056                     channel->receive_sdu_buffer = channel->renegotiate_sdu_buffer;
4057                     channel->local_mtu = channel->renegotiate_mtu;
4058                 }
4059                 channel->state = L2CAP_STATE_OPEN;
4060                 // emit event
4061                 l2cap_ecbm_emit_reconfigure_complete(channel, result);
4062             }
4063             break;
4064 
4065         default:
4066             btstack_unreachable();
4067             break;
4068     }
4069     return 0;
4070 }
4071 
4072 #endif
4073 
4074 #ifdef ENABLE_BLE
4075 
4076 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
4077     uint8_t event[6];
4078     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
4079     event[1] = 4;
4080     little_endian_store_16(event, 2, con_handle);
4081     little_endian_store_16(event, 4, result);
4082     l2cap_emit_event(event, sizeof(event));
4083 }
4084 
4085 // @return valid
4086 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
4087     hci_connection_t * connection;
4088     uint16_t result;
4089     uint8_t  event[12];
4090 
4091 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4092     l2cap_channel_t * channel;
4093     btstack_linked_list_iterator_t it;
4094 #endif
4095 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4096     uint16_t local_cid;
4097     uint16_t le_psm;
4098     l2cap_service_t * service;
4099     uint16_t source_cid;
4100 #endif
4101 
4102     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
4103     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
4104     log_info("le dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
4105 
4106     switch (code){
4107 
4108         case CONNECTION_PARAMETER_UPDATE_REQUEST:
4109             // check size
4110             if (len < 8u) return 0u;
4111             connection = hci_connection_for_handle(handle);
4112             if (connection != NULL){
4113                 if (connection->role != HCI_ROLE_MASTER){
4114                     // reject command without notifying upper layer when not in master role
4115                     return 0;
4116                 }
4117                 le_connection_parameter_range_t existing_range;
4118                 gap_get_connection_parameter_range(&existing_range);
4119                 uint16_t le_conn_interval_min   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
4120                 uint16_t le_conn_interval_max   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
4121                 uint16_t le_conn_latency        = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
4122                 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
4123 
4124                 int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
4125                 if (update_parameter){
4126                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
4127                     connection->le_conn_interval_min = le_conn_interval_min;
4128                     connection->le_conn_interval_max = le_conn_interval_max;
4129                     connection->le_conn_latency = le_conn_latency;
4130                     connection->le_supervision_timeout = le_supervision_timeout;
4131                 } else {
4132                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
4133                 }
4134                 connection->le_con_param_update_identifier = sig_id;
4135             }
4136 
4137             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
4138             event[1] = 8;
4139             little_endian_store_16(event, 2, handle);
4140             (void)memcpy(&event[4], &command[4], 8);
4141             l2cap_emit_event(event, sizeof(event));
4142             break;
4143 
4144         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
4145             // check size
4146             if (len < 2u) return 0u;
4147             result = little_endian_read_16(command, 4);
4148             l2cap_emit_connection_parameter_update_response(handle, result);
4149             break;
4150 
4151 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
4152         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
4153         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
4154         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
4155         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
4156             return l2cap_ecbm_signaling_handler_dispatch(handle, L2CAP_CID_SIGNALING_LE, command, sig_id);
4157 #endif
4158 
4159 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4160         case COMMAND_REJECT:
4161             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4162             while (btstack_linked_list_iterator_has_next(&it)){
4163                 channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4164                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4165                 if (channel->con_handle   != handle) continue;
4166                 if (channel->local_sig_id != sig_id) continue;
4167 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4168                 // if received while waiting for le connection response, assume legacy device
4169                 if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
4170                     channel->state = L2CAP_STATE_CLOSED;
4171                     // no official value for this, use: Connection refused – LE_PSM not supported
4172                     l2cap_cbm_emit_channel_opened(channel, L2CAP_CBM_CONNECTION_RESULT_SPSM_NOT_SUPPORTED);
4173 
4174                     // discard channel
4175                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4176                     l2cap_free_channel_entry(channel);
4177                     continue;
4178                 }
4179 #endif
4180 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
4181                 // if received while waiting for le connection response, assume legacy device
4182                 if (channel->state == L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE){
4183                     channel->state = L2CAP_STATE_CLOSED;
4184                     // treat as SPSM not supported
4185                     l2cap_ecbm_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_PSM);
4186 
4187                     // discard channel
4188                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4189                     l2cap_free_channel_entry(channel);
4190                     continue;
4191                 }
4192 #endif
4193             }
4194             break;
4195 #endif
4196 
4197 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4198         case LE_CREDIT_BASED_CONNECTION_REQUEST:
4199             // check size
4200             if (len < 10u) return 0u;
4201 
4202             // get hci connection, bail if not found (must not happen)
4203             connection = hci_connection_for_handle(handle);
4204             if (!connection) return 0;
4205 
4206             // check if service registered
4207             le_psm  = little_endian_read_16(command, 4);
4208             service = l2cap_cbm_get_service(le_psm);
4209             source_cid = little_endian_read_16(command, 6);
4210 
4211             if (service){
4212                 if (source_cid < 0x40u){
4213                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INVALID_SOURCE_CID);
4214                     return 1;
4215                 }
4216 
4217                 // go through list of channels for this ACL connection and check if we get a match
4218                 btstack_linked_list_iterator_init(&it, &l2cap_channels);
4219                 while (btstack_linked_list_iterator_has_next(&it)){
4220                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4221                     if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
4222                     if (a_channel->con_handle != handle) continue;
4223                     if (a_channel->remote_cid != source_cid) continue;
4224                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_SOURCE_CID_ALREADY_ALLOCATED);
4225                     return 1;
4226                 }
4227 
4228                 // security: check encryption
4229                 if (service->required_security_level >= LEVEL_2){
4230                     if (gap_encryption_key_size(handle) == 0){
4231                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_ENCRYPTION);
4232                         return 1;
4233                     }
4234                     // anything less than 16 byte key size is insufficient
4235                     if (gap_encryption_key_size(handle) < 16){
4236                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_ENCYRPTION_KEY_SIZE_TOO_SHORT);
4237                         return 1;
4238                     }
4239                 }
4240 
4241                 // security: check authentication
4242                 if (service->required_security_level >= LEVEL_3){
4243                     if (!gap_authenticated(handle)){
4244                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHENTICATION);
4245                         return 1;
4246                     }
4247                 }
4248 
4249                 // security: check authorization
4250                 if (service->required_security_level >= LEVEL_4){
4251                     if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
4252                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHORIZATION);
4253                         return 1;
4254                     }
4255                 }
4256 
4257                 // allocate channel
4258                 channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_CBM, connection->address,
4259                                                      BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
4260                 if (!channel){
4261                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE);
4262                     return 1;
4263                 }
4264 
4265                 channel->con_handle = handle;
4266                 channel->remote_cid = source_cid;
4267                 channel->remote_sig_id = sig_id;
4268                 channel->remote_mtu = little_endian_read_16(command, 8);
4269                 channel->remote_mps = little_endian_read_16(command, 10);
4270                 channel->credits_outgoing = little_endian_read_16(command, 12);
4271 
4272                 // set initial state
4273                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
4274                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
4275 
4276                 // add to connections list
4277                 btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
4278 
4279                 // post connection request event
4280                 l2cap_cbm_emit_incoming_connection(channel);
4281 
4282             } else {
4283                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_SPSM_NOT_SUPPORTED);
4284             }
4285             break;
4286 
4287         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
4288             // check size
4289             if (len < 10u) return 0u;
4290 
4291             // Find channel for this sig_id and connection handle
4292             channel = NULL;
4293             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4294             while (btstack_linked_list_iterator_has_next(&it)){
4295                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4296                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
4297                 if (a_channel->con_handle   != handle) continue;
4298                 if (a_channel->local_sig_id != sig_id) continue;
4299                 channel = a_channel;
4300                 break;
4301             }
4302             if (!channel) break;
4303 
4304             // cid + 0
4305             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
4306             if (result){
4307                 channel->state = L2CAP_STATE_CLOSED;
4308                 uint8_t status = l2cap_cbm_status_for_result(result);
4309                 l2cap_cbm_emit_channel_opened(channel, status);
4310 
4311                 // discard channel
4312                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4313                 l2cap_free_channel_entry(channel);
4314                 break;
4315             }
4316 
4317             // success
4318             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4319             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
4320             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
4321             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
4322             channel->state = L2CAP_STATE_OPEN;
4323             l2cap_cbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
4324             break;
4325 #endif
4326 
4327 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4328         case L2CAP_FLOW_CONTROL_CREDIT_INDICATION:
4329             return l2cap_credit_based_handle_credit_indication(handle, command, len) ? 1 : 0;
4330 
4331         case DISCONNECTION_REQUEST:
4332 
4333             // check size
4334             if (len < 4u) return 0u;
4335 
4336             // find channel
4337             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4338             channel = l2cap_get_channel_for_local_cid_and_handle(local_cid, handle);
4339             if (!channel) {
4340                 log_error("credit: no channel for cid 0x%02x", local_cid);
4341                 break;
4342             }
4343             channel->remote_sig_id = sig_id;
4344             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
4345             break;
4346 
4347         case DISCONNECTION_RESPONSE:
4348             // check size
4349             if (len < 4u) return 0u;
4350 
4351             // find channel
4352             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4353             channel = l2cap_get_channel_for_local_cid_and_handle(local_cid, handle);
4354             if (!channel) break;
4355             if (channel->local_sig_id == sig_id) {
4356                 if (channel->state == L2CAP_STATE_WAIT_DISCONNECT){
4357                     l2cap_finalize_channel_close(channel);
4358                 }
4359             }
4360             break;
4361 #endif
4362 
4363         default:
4364             // command unknown -> reject command
4365             return 0;
4366     }
4367     return 1;
4368 }
4369 #endif
4370 
4371 #ifdef ENABLE_CLASSIC
4372 static void l2cap_acl_classic_handler_for_channel(l2cap_channel_t * l2cap_channel, uint8_t * packet, uint16_t size){
4373 
4374     // forward data only in OPEN state
4375     if (l2cap_channel->state != L2CAP_STATE_OPEN) return;
4376 
4377 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4378     if (l2cap_channel->channel_type == L2CAP_CHANNEL_TYPE_CHANNEL_ECBM){
4379         l2cap_credit_based_handle_pdu(l2cap_channel, packet, size);
4380         return;
4381     }
4382 #endif
4383 
4384 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
4385     if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
4386 
4387         int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
4388 
4389         // assert control + FCS fields are inside
4390         if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) return;
4391 
4392         if (l2cap_channel->fcs_option){
4393             // verify FCS (required if one side requested it)
4394             uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
4395             uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
4396 
4397 #ifdef L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL
4398             // simulate fcs error
4399             static int counter = 0;
4400             if (++counter == L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL) {
4401                 log_info("Simulate fcs error");
4402                 fcs_calculated++;
4403                 counter = 0;
4404             }
4405 #endif
4406 
4407             if (fcs_calculated == fcs_packet){
4408                 log_info("Packet FCS 0x%04x verified", fcs_packet);
4409             } else {
4410                 log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
4411                 // ERTM State Machine in Bluetooth Spec does not handle 'I-Frame with invalid FCS'
4412                 return;
4413             }
4414         }
4415 
4416         // switch on packet type
4417         uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
4418         uint8_t  req_seq = (control >> 8) & 0x3f;
4419         int final = (control >> 7) & 0x01;
4420         if (control & 1){
4421             // S-Frame
4422             int poll  = (control >> 4) & 0x01;
4423             l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
4424             log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
4425             l2cap_ertm_tx_packet_state_t * tx_state;
4426             switch (s){
4427                 case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
4428                     log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
4429                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4430                     if (poll && final){
4431                         // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
4432                         log_error("P=F=1 in S-Frame");
4433                         break;
4434                     }
4435                     if (poll){
4436                         // check if we did request selective retransmission before <==> we have stored SDU segments
4437                         int i;
4438                         int num_stored_out_of_order_packets = 0;
4439                         for (i=0;i<l2cap_channel->num_rx_buffers;i++){
4440                             int index = l2cap_channel->rx_store_index + i;
4441                             if (index >= l2cap_channel->num_rx_buffers){
4442                                 index -= l2cap_channel->num_rx_buffers;
4443                             }
4444                             l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
4445                             if (!rx_state->valid) continue;
4446                             num_stored_out_of_order_packets++;
4447                         }
4448                         if (num_stored_out_of_order_packets){
4449                             l2cap_channel->send_supervisor_frame_selective_reject = 1;
4450                         } else {
4451                             l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
4452                         }
4453                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
4454                     }
4455                     if (final){
4456                         // Stop-MonitorTimer
4457                         l2cap_ertm_stop_monitor_timer(l2cap_channel);
4458                         // If UnackedFrames > 0 then Start-RetransTimer
4459                         if (l2cap_channel->unacked_frames){
4460                             l2cap_ertm_start_retransmission_timer(l2cap_channel);
4461                         }
4462                         // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
4463                         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4464                     }
4465                     break;
4466                 case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
4467                     log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
4468                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4469                     // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
4470                     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4471                     break;
4472                 case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
4473                     log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
4474                     break;
4475                 case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
4476                     log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
4477                     if (poll){
4478                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4479                     }
4480                     // find requested i-frame
4481                     tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
4482                     if (tx_state){
4483                         log_info("Retransmission for tx_seq %u requested", req_seq);
4484                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
4485                         tx_state->retransmission_requested = 1;
4486                         l2cap_channel->srej_active = 1;
4487                     }
4488                     break;
4489                 default:
4490                     break;
4491             }
4492         } else {
4493             // I-Frame
4494             // get control
4495             l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
4496             uint8_t tx_seq = (control >> 1) & 0x3f;
4497             log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
4498             log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
4499             log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
4500             l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4501             if (final){
4502                 // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
4503                 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4504             }
4505 
4506             // get SDU
4507             const uint8_t * payload_data = &packet[COMPLETE_L2CAP_HEADER+2];
4508             uint16_t        payload_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
4509 
4510             // assert SDU size is smaller or equal to our buffers
4511             uint16_t max_payload_size = 0;
4512             switch (sar){
4513                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
4514                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
4515                     // SDU Length + MPS
4516                     max_payload_size = l2cap_channel->local_mps + 2;
4517                     break;
4518                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
4519                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
4520                     max_payload_size = l2cap_channel->local_mps;
4521                     break;
4522                 default:
4523                     btstack_assert(false);
4524                     break;
4525             }
4526             if (payload_len > max_payload_size){
4527                 log_info("payload len %u > max payload %u -> drop packet", payload_len, max_payload_size);
4528                 return;
4529             }
4530 
4531             // check ordering
4532             if (l2cap_channel->expected_tx_seq == tx_seq){
4533                 log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
4534                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
4535                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
4536 
4537                 // process SDU
4538                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, payload_data, payload_len);
4539 
4540                 // process stored segments
4541                 while (true){
4542                     int index = l2cap_channel->rx_store_index;
4543                     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
4544                     if (!rx_state->valid) break;
4545 
4546                     log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
4547                     l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
4548                     l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
4549 
4550                     rx_state->valid = 0;
4551                     l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
4552 
4553                     // update rx store index
4554                     index++;
4555                     if (index >= l2cap_channel->num_rx_buffers){
4556                         index = 0;
4557                     }
4558                     l2cap_channel->rx_store_index = index;
4559                 }
4560 
4561                 //
4562                 l2cap_channel->send_supervisor_frame_receiver_ready = 1;
4563 
4564             } else {
4565                 int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
4566                 if (delta < 2){
4567                     // store segment
4568                     l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, payload_data, payload_len);
4569 
4570                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
4571                     l2cap_channel->send_supervisor_frame_selective_reject = 1;
4572                 } else {
4573                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
4574                     l2cap_channel->send_supervisor_frame_reject = 1;
4575                 }
4576             }
4577         }
4578         return;
4579     }
4580 #endif
4581 
4582     // check size
4583     uint16_t payload_size = size - COMPLETE_L2CAP_HEADER;
4584     if (l2cap_channel->local_mtu < payload_size) return;
4585 
4586     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], payload_size);
4587 }
4588 #endif
4589 
4590 static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
4591 #ifdef ENABLE_CLASSIC
4592     l2cap_channel_t * l2cap_channel;
4593     l2cap_fixed_channel_t * l2cap_fixed_channel;
4594 
4595     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
4596     uint8_t  broadcast_flag = READ_ACL_FLAGS(packet) >> 2;
4597     switch (channel_id) {
4598 
4599         case L2CAP_CID_SIGNALING: {
4600             if (broadcast_flag != 0) break;
4601             uint32_t command_offset = 8;
4602             while ((command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET) < size) {
4603                 // assert signaling command is fully inside packet
4604                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
4605                 uint32_t next_command_offset = command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
4606                 if (next_command_offset > size){
4607                     log_error("l2cap signaling command len invalid -> drop");
4608                     break;
4609                 }
4610                 // handle signaling command
4611                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
4612                 // go to next command
4613                 command_offset = next_command_offset;
4614             }
4615             break;
4616         }
4617 
4618         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
4619             if (broadcast_flag == 0) break;
4620             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL);
4621             if (!l2cap_fixed_channel) break;
4622             if (!l2cap_fixed_channel->packet_handler) break;
4623             (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4624             break;
4625 
4626 #ifdef ENABLE_BLE
4627         case L2CAP_CID_BR_EDR_SECURITY_MANAGER:
4628             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
4629             if ((l2cap_fixed_channel == NULL) || (l2cap_fixed_channel->packet_handler == NULL)){
4630                 // Pairing Failed
4631                 l2cap_register_signaling_response(handle, (uint8_t) SM_PAIRING_FAILED, 0, L2CAP_CID_BR_EDR_SECURITY_MANAGER, SM_REASON_PAIRING_NOT_SUPPORTED);
4632             } else {
4633                 (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4634             }
4635             break;
4636 #endif
4637 
4638         default:
4639             if (broadcast_flag != 0) break;
4640             // Find channel for this channel_id and connection handle
4641             l2cap_channel = l2cap_get_channel_for_local_cid_and_handle(channel_id, handle);
4642             if (l2cap_channel != NULL){
4643                 l2cap_acl_classic_handler_for_channel(l2cap_channel, packet, size);
4644             }
4645             break;
4646     }
4647 #else
4648     UNUSED(handle); // ok: no code
4649     UNUSED(packet); // ok: no code
4650     UNUSED(size);   // ok: no code
4651 #endif
4652 }
4653 
4654 static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
4655 #ifdef ENABLE_BLE
4656 
4657     l2cap_fixed_channel_t * l2cap_fixed_channel;
4658 
4659 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4660     l2cap_channel_t * l2cap_channel;
4661 #endif
4662     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
4663     switch (channel_id) {
4664 
4665         case L2CAP_CID_SIGNALING_LE: {
4666             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
4667             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
4668             if ((COMPLETE_L2CAP_HEADER + 4u + len) > size) break;
4669             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
4670             if (!valid){
4671                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
4672             }
4673             break;
4674         }
4675 
4676         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
4677             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL);
4678             if (!l2cap_fixed_channel) break;
4679             if (!l2cap_fixed_channel->packet_handler) break;
4680             (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4681             break;
4682 
4683         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
4684             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
4685             if ((l2cap_fixed_channel == NULL) || (l2cap_fixed_channel->packet_handler == NULL)){
4686                 // Pairing Failed
4687                 l2cap_register_signaling_response(handle, (uint8_t) SM_PAIRING_FAILED, 0, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, SM_REASON_PAIRING_NOT_SUPPORTED);
4688             } else {
4689                 (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4690             }
4691             break;
4692 
4693         default:
4694 
4695 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4696             l2cap_channel = l2cap_get_channel_for_local_cid_and_handle(channel_id, handle);
4697             if (l2cap_channel != NULL) {
4698                 l2cap_credit_based_handle_pdu(l2cap_channel, packet, size);
4699             }
4700 #endif
4701             break;
4702     }
4703 #else
4704     UNUSED(handle); // ok: no code
4705     UNUSED(packet); // ok: no code
4706     UNUSED(size);   // ok: no code
4707 #endif
4708 }
4709 
4710 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
4711     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
4712     UNUSED(channel);        // ok: there is no channel
4713 
4714     // Assert full L2CAP header present
4715     if (size < COMPLETE_L2CAP_HEADER) return;
4716 
4717     // Dispatch to Classic or LE handler (SCO packets are not dispatched to L2CAP)
4718     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
4719     hci_connection_t *conn = hci_connection_for_handle(handle);
4720     if (!conn) return;
4721     if (conn->address_type == BD_ADDR_TYPE_ACL){
4722         l2cap_acl_classic_handler(handle, packet, size);
4723     } else {
4724         l2cap_acl_le_handler(handle, packet, size);
4725     }
4726 
4727     l2cap_run();
4728 }
4729 
4730 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
4731 void l2cap_register_fixed_channel(btstack_packet_handler_t packet_handler, uint16_t channel_id) {
4732     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
4733     if (!channel) return;
4734     channel->packet_handler = packet_handler;
4735 }
4736 
4737 #ifdef L2CAP_USES_CHANNELS
4738 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
4739 void l2cap_finalize_channel_close(l2cap_channel_t * channel){
4740     channel->state = L2CAP_STATE_CLOSED;
4741     l2cap_handle_channel_closed(channel);
4742     // discard channel
4743     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4744     l2cap_free_channel_entry(channel);
4745 }
4746 #endif
4747 
4748 #ifdef ENABLE_CLASSIC
4749 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
4750     return l2cap_get_service_internal(&l2cap_services, psm);
4751 }
4752 
4753 static void l2cap_update_minimal_security_level(void){
4754     // update minimal service security level
4755     gap_security_level_t minimal_level = LEVEL_1;
4756     btstack_linked_list_iterator_t it;
4757     btstack_linked_list_iterator_init(&it, &l2cap_services);
4758     while (btstack_linked_list_iterator_has_next(&it)){
4759         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
4760         if (service->required_security_level > minimal_level){
4761             minimal_level = service->required_security_level;
4762         };
4763     }
4764     gap_set_minimal_service_security_level(minimal_level);
4765 }
4766 
4767 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
4768 
4769     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
4770 
4771     // check for alread registered psm
4772     l2cap_service_t *service = l2cap_get_service(psm);
4773     if (service) {
4774         log_error("register: PSM %u already registered", psm);
4775         return L2CAP_SERVICE_ALREADY_REGISTERED;
4776     }
4777 
4778     // alloc structure
4779     service = btstack_memory_l2cap_service_get();
4780     if (!service) {
4781         log_error("register: no memory for l2cap_service_t");
4782         return BTSTACK_MEMORY_ALLOC_FAILED;
4783     }
4784 
4785     // fill in
4786     service->psm = psm;
4787     service->mtu = mtu;
4788     service->packet_handler = service_packet_handler;
4789     service->required_security_level = security_level;
4790 
4791     // add to services list
4792     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
4793 
4794     l2cap_update_minimal_security_level();
4795 
4796 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
4797     // enable page scan
4798     gap_connectable_control(1);
4799 #endif
4800 
4801 
4802     return ERROR_CODE_SUCCESS;
4803 }
4804 
4805 uint8_t l2cap_unregister_service(uint16_t psm){
4806 
4807     log_info("unregister psm 0x%x", psm);
4808 
4809     l2cap_service_t *service = l2cap_get_service(psm);
4810     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
4811     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
4812     btstack_memory_l2cap_service_free(service);
4813 
4814     l2cap_update_minimal_security_level();
4815 
4816 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
4817     // disable page scan when no services registered
4818     if (btstack_linked_list_empty(&l2cap_services)) {
4819         gap_connectable_control(0);
4820     }
4821 #endif
4822 
4823     return ERROR_CODE_SUCCESS;
4824 }
4825 #endif
4826 
4827 
4828 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4829 
4830 static void l2cap_credit_based_send_pdu(l2cap_channel_t *channel) {
4831     btstack_assert(channel != NULL);
4832     btstack_assert(channel->send_sdu_buffer != NULL);
4833     btstack_assert(channel->credits_outgoing > 0);
4834 
4835     // send part of SDU
4836     hci_reserve_packet_buffer();
4837     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
4838     uint8_t *l2cap_payload = acl_buffer + 8;
4839     uint16_t pos = 0;
4840     if (!channel->send_sdu_pos) {
4841         // store SDU len
4842         channel->send_sdu_pos += 2u;
4843         little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
4844         pos += 2u;
4845     }
4846     uint16_t payload_size = btstack_min(channel->send_sdu_len + 2u - channel->send_sdu_pos, channel->remote_mps - pos);
4847     log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size,
4848              channel->credits_outgoing);
4849     (void) memcpy(&l2cap_payload[pos],
4850                   &channel->send_sdu_buffer[channel->send_sdu_pos - 2u],
4851                   payload_size); // -2 for virtual SDU len
4852     pos += payload_size;
4853     channel->send_sdu_pos += payload_size;
4854     l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
4855 
4856     channel->credits_outgoing--;
4857 
4858     // update state (mark SDU as done) before calling hci_send_acl_packet_buffer (trigger l2cap_le_send_pdu again)
4859     bool done = channel->send_sdu_pos >= (channel->send_sdu_len + 2u);
4860     if (done) {
4861         channel->send_sdu_buffer = NULL;
4862     }
4863 
4864     hci_send_acl_packet_buffer(8u + pos);
4865 
4866     if (done) {
4867         // send done event
4868         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_PACKET_SENT);
4869         // inform about can send now
4870         l2cap_credit_based_notify_channel_can_send(channel);
4871     }
4872 }
4873 
4874 static uint8_t l2cap_credit_based_send_data(l2cap_channel_t * channel, const uint8_t * data, uint16_t size){
4875 
4876     if (size > channel->remote_mtu){
4877         log_error("l2cap send, cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
4878         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
4879     }
4880 
4881     if (channel->send_sdu_buffer){
4882         log_info("l2cap send, cid 0x%02x, cannot send", channel->local_cid);
4883         return BTSTACK_ACL_BUFFERS_FULL;
4884     }
4885 
4886     channel->send_sdu_buffer = data;
4887     channel->send_sdu_len    = size;
4888     channel->send_sdu_pos    = 0;
4889 
4890     l2cap_notify_channel_can_send();
4891     return ERROR_CODE_SUCCESS;
4892 }
4893 
4894 static uint8_t l2cap_credit_based_provide_credits(uint16_t local_cid, uint16_t credits){
4895     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4896     if (!channel) {
4897         log_error("le credits no channel for cid 0x%02x", local_cid);
4898         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4899     }
4900 
4901     // check state
4902     if (channel->state != L2CAP_STATE_OPEN){
4903         log_error("le credits but channel 0x%02x not open yet", local_cid);
4904     }
4905 
4906     // ignore if set to automatic credits
4907     if (channel->automatic_credits) return ERROR_CODE_SUCCESS;
4908 
4909     // assert incoming credits + credits <= 0xffff
4910     uint32_t total_credits = channel->credits_incoming;
4911     total_credits += channel->new_credits_incoming;
4912     total_credits += credits;
4913     if (total_credits > 0xffffu){
4914         log_error("le credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
4915                   channel->new_credits_incoming, credits);
4916     }
4917 
4918     // set credits_granted
4919     channel->new_credits_incoming += credits;
4920 
4921     // go
4922     l2cap_run();
4923     return ERROR_CODE_SUCCESS;
4924 }
4925 
4926 static void l2cap_credit_based_send_credits(l2cap_channel_t *channel) {
4927     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
4928     channel->local_sig_id = l2cap_next_sig_id();
4929     uint16_t new_credits = channel->new_credits_incoming;
4930     channel->new_credits_incoming = 0;
4931     channel->credits_incoming += new_credits;
4932     uint16_t signaling_cid = channel->address_type == BD_ADDR_TYPE_ACL ? L2CAP_CID_SIGNALING : L2CAP_CID_SIGNALING_LE;
4933     l2cap_send_general_signaling_packet(channel->con_handle, signaling_cid, L2CAP_FLOW_CONTROL_CREDIT_INDICATION, channel->local_sig_id, channel->local_cid, new_credits);
4934 }
4935 
4936 // @return valid
4937 static bool l2cap_credit_based_handle_credit_indication(hci_con_handle_t handle, const uint8_t * command, uint16_t len){
4938     // check size
4939     if (len < 4u) return false;
4940 
4941     // find channel
4942     uint16_t remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4943     l2cap_channel_t * channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
4944     if (!channel) {
4945         log_error("credit: no channel for handle 0x%04x/cid 0x%02x", handle, remote_cid);
4946         return true;
4947     }
4948     uint16_t new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
4949     uint16_t credits_before = channel->credits_outgoing;
4950     channel->credits_outgoing += new_credits;
4951     // check for credit overrun
4952     if (credits_before > channel->credits_outgoing) {
4953         log_error("credit: new credits caused overrrun for cid 0x%02x, disconnecting", channel->local_cid);
4954         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4955         return true;
4956     }
4957     log_info("credit: %u credits for 0x%02x, now %u", new_credits, channel->local_cid, channel->credits_outgoing);
4958     l2cap_call_notify_channel_in_run = true;
4959     return true;
4960 }
4961 
4962 static void l2cap_credit_based_handle_pdu(l2cap_channel_t * l2cap_channel, const uint8_t * packet, uint16_t size){
4963     // ignore empty packets
4964     if (size == COMPLETE_L2CAP_HEADER) return;
4965 
4966     // credit counting
4967     if (l2cap_channel->credits_incoming == 0u){
4968         log_info("(e)CBM: packet received but no incoming credits");
4969         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4970         return;
4971     }
4972     l2cap_channel->credits_incoming--;
4973 
4974     // automatic credits
4975     if ((l2cap_channel->credits_incoming < L2CAP_CREDIT_BASED_FLOW_CONTROL_MODE_AUTOMATIC_CREDITS_WATERMARK) && l2cap_channel->automatic_credits){
4976         l2cap_channel->new_credits_incoming = L2CAP_CREDIT_BASED_FLOW_CONTROL_MODE_AUTOMATIC_CREDITS_INCREMENT;
4977     }
4978 
4979     // first fragment
4980     uint16_t pos = 0;
4981     if (!l2cap_channel->receive_sdu_len){
4982         if (size < (COMPLETE_L2CAP_HEADER + 2)) return;
4983         uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
4984         if(sdu_len > l2cap_channel->local_mtu) return;   // SDU would be larger than our buffer
4985         l2cap_channel->receive_sdu_len = sdu_len;
4986         l2cap_channel->receive_sdu_pos = 0;
4987         pos  += 2u;
4988         size -= 2u;
4989     }
4990     uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
4991     uint16_t remaining_space = l2cap_channel->local_mtu - l2cap_channel->receive_sdu_pos;
4992     if (fragment_size > remaining_space) return;         // SDU would cause buffer overrun
4993     (void)memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos],
4994                  &packet[COMPLETE_L2CAP_HEADER + pos],
4995                  fragment_size);
4996     l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
4997     // done?
4998     log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
4999     if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
5000         l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
5001         l2cap_channel->receive_sdu_len = 0;
5002     }
5003 }
5004 
5005 static void l2cap_credit_based_notify_channel_can_send(l2cap_channel_t *channel){
5006     if (!channel->waiting_for_can_send_now) return;
5007     if (channel->send_sdu_buffer) return;
5008     channel->waiting_for_can_send_now = 0;
5009     log_debug("le can send now, local_cid 0x%x", channel->local_cid);
5010     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CAN_SEND_NOW);
5011 }
5012 #endif
5013 
5014 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
5015 // 1BH2222
5016 static void l2cap_cbm_emit_incoming_connection(l2cap_channel_t *channel) {
5017     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",
5018              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
5019     uint8_t event[19];
5020     event[0] = L2CAP_EVENT_CBM_INCOMING_CONNECTION;
5021     event[1] = sizeof(event) - 2u;
5022     event[2] = channel->address_type;
5023     reverse_bd_addr(channel->address, &event[3]);
5024     little_endian_store_16(event,  9, channel->con_handle);
5025     little_endian_store_16(event, 11, channel->psm);
5026     little_endian_store_16(event, 13, channel->local_cid);
5027     little_endian_store_16(event, 15, channel->remote_cid);
5028     little_endian_store_16(event, 17, channel->remote_mtu);
5029     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
5030     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
5031 }
5032 // 11BH22222
5033 static void l2cap_cbm_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
5034     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",
5035              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
5036              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
5037     uint8_t event[23];
5038     event[0] = L2CAP_EVENT_CBM_CHANNEL_OPENED;
5039     event[1] = sizeof(event) - 2u;
5040     event[2] = status;
5041     event[3] = channel->address_type;
5042     reverse_bd_addr(channel->address, &event[4]);
5043     little_endian_store_16(event, 10, channel->con_handle);
5044     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
5045     little_endian_store_16(event, 13, channel->psm);
5046     little_endian_store_16(event, 15, channel->local_cid);
5047     little_endian_store_16(event, 17, channel->remote_cid);
5048     little_endian_store_16(event, 19, channel->local_mtu);
5049     little_endian_store_16(event, 21, channel->remote_mtu);
5050     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
5051     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
5052 }
5053 
5054 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
5055 void l2cap_cbm_finialize_channel_close(l2cap_channel_t * channel){
5056     channel->state = L2CAP_STATE_CLOSED;
5057     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
5058     // discard channel
5059     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
5060     l2cap_free_channel_entry(channel);
5061 }
5062 
5063 static inline l2cap_service_t * l2cap_cbm_get_service(uint16_t le_psm){
5064     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
5065 }
5066 
5067 uint8_t l2cap_cbm_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
5068 
5069     log_info("l2cap_cbm_register_service psm 0x%x", psm);
5070 
5071     // check for alread registered psm
5072     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5073     if (service) {
5074         return L2CAP_SERVICE_ALREADY_REGISTERED;
5075     }
5076 
5077     // alloc structure
5078     service = btstack_memory_l2cap_service_get();
5079     if (!service) {
5080         log_error("register: no memory for l2cap_service_t");
5081         return BTSTACK_MEMORY_ALLOC_FAILED;
5082     }
5083 
5084     // fill in
5085     service->psm = psm;
5086     service->mtu = 0;
5087     service->packet_handler = packet_handler;
5088     service->required_security_level = security_level;
5089 
5090     // add to services list
5091     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
5092 
5093     // done
5094     return ERROR_CODE_SUCCESS;
5095 }
5096 
5097 uint8_t l2cap_cbm_unregister_service(uint16_t psm) {
5098     log_info("l2cap_cbm_unregister_service psm 0x%x", psm);
5099     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5100     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
5101 
5102     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
5103     btstack_memory_l2cap_service_free(service);
5104     return ERROR_CODE_SUCCESS;
5105 }
5106 
5107 uint8_t l2cap_cbm_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
5108     // get channel
5109     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5110     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5111 
5112     // validate state
5113     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
5114         return ERROR_CODE_COMMAND_DISALLOWED;
5115     }
5116 
5117     // set state accept connection
5118     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
5119     channel->receive_sdu_buffer = receive_sdu_buffer;
5120     channel->local_mtu = mtu;
5121     channel->new_credits_incoming = initial_credits;
5122     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5123 
5124     // go
5125     l2cap_run();
5126     return ERROR_CODE_SUCCESS;
5127 }
5128 
5129 uint8_t l2cap_cbm_decline_connection(uint16_t local_cid, uint16_t result) {
5130     // get channel
5131     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5132     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5133 
5134     // validate state
5135     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
5136         return ERROR_CODE_COMMAND_DISALLOWED;
5137     }
5138 
5139     // set state decline connection
5140     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
5141     channel->reason = result;
5142     l2cap_run();
5143     return ERROR_CODE_SUCCESS;
5144 }
5145 
5146 static gap_security_level_t l2cap_cbm_security_level_for_connection(hci_con_handle_t con_handle){
5147     uint8_t encryption_key_size = gap_encryption_key_size(con_handle);
5148     if (encryption_key_size == 0) return LEVEL_0;
5149 
5150     bool authenticated = gap_authenticated(con_handle);
5151     if (!authenticated) return LEVEL_2;
5152 
5153     return encryption_key_size == 16 ? LEVEL_4 : LEVEL_3;
5154 }
5155 
5156 // used to handle pairing complete after triggering to increase
5157 static void l2cap_cbm_sm_packet_handler(uint8_t packet_type, uint16_t channel_nr, uint8_t *packet, uint16_t size) {
5158     UNUSED(channel_nr);
5159     UNUSED(size);
5160     UNUSED(packet_type);
5161     btstack_assert(packet_type == HCI_EVENT_PACKET);
5162     if (hci_event_packet_get_type(packet) != SM_EVENT_PAIRING_COMPLETE) return;
5163     hci_con_handle_t con_handle = sm_event_pairing_complete_get_handle(packet);
5164     btstack_linked_list_iterator_t it;
5165     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5166     while (btstack_linked_list_iterator_has_next(&it)) {
5167         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5168         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5169         if (channel->con_handle != con_handle) continue;
5170         if (channel->state != L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE) continue;
5171 
5172         // found channel, check security level
5173         if (l2cap_cbm_security_level_for_connection(con_handle) < channel->required_security_level){
5174             // pairing failed or wasn't good enough, inform user
5175             l2cap_cbm_emit_channel_opened(channel, ERROR_CODE_INSUFFICIENT_SECURITY);
5176             // discard channel
5177             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
5178             l2cap_free_channel_entry(channel);
5179         } else {
5180             // send conn request now
5181             channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5182             l2cap_run();
5183         }
5184     }
5185 }
5186 
5187 uint8_t l2cap_cbm_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5188     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
5189     uint16_t * out_local_cid) {
5190 
5191     static btstack_packet_callback_registration_t sm_event_callback_registration;
5192     static bool sm_callback_registered = false;
5193 
5194     log_info("create, handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
5195 
5196     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5197     if (!connection) {
5198         log_error("no hci_connection for handle 0x%04x", con_handle);
5199         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5200     }
5201 
5202     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_CBM, connection->address, connection->address_type, psm, mtu, security_level);
5203     if (!channel) {
5204         return BTSTACK_MEMORY_ALLOC_FAILED;
5205     }
5206     log_info("created %p", channel);
5207 
5208     // store local_cid
5209     if (out_local_cid){
5210        *out_local_cid = channel->local_cid;
5211     }
5212 
5213     // setup channel entry
5214     channel->con_handle = con_handle;
5215     channel->receive_sdu_buffer = receive_sdu_buffer;
5216     channel->new_credits_incoming = initial_credits;
5217     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5218 
5219     // add to connections list
5220     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
5221 
5222     // check security level
5223     if (l2cap_cbm_security_level_for_connection(con_handle) < channel->required_security_level){
5224         if (!sm_callback_registered){
5225             sm_callback_registered = true;
5226             // lazy registration for SM events
5227             sm_event_callback_registration.callback = &l2cap_cbm_sm_packet_handler;
5228             sm_add_event_handler(&sm_event_callback_registration);
5229         }
5230 
5231         // start pairing
5232         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
5233         sm_request_pairing(con_handle);
5234     } else {
5235         // send conn request right away
5236         channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5237         l2cap_run();
5238     }
5239 
5240     return ERROR_CODE_SUCCESS;
5241 }
5242 
5243 uint8_t l2cap_cbm_provide_credits(uint16_t local_cid, uint16_t credits){
5244     return l2cap_credit_based_provide_credits(local_cid, credits);
5245 }
5246 #endif
5247 
5248 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
5249 
5250 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){
5251 
5252     // check for already registered psm
5253     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5254     if (service) {
5255         return L2CAP_SERVICE_ALREADY_REGISTERED;
5256     }
5257 
5258     // alloc structure
5259     service = btstack_memory_l2cap_service_get();
5260     if (!service) {
5261         log_error("register: no memory for l2cap_service_t");
5262         return BTSTACK_MEMORY_ALLOC_FAILED;
5263     }
5264 
5265     // fill in
5266     service->psm = psm;
5267     service->mtu = min_remote_mtu;
5268     service->packet_handler = packet_handler;
5269     service->required_security_level = security_level;
5270 
5271     // add to services list
5272     btstack_linked_list_add(&l2cap_enhanced_services, (btstack_linked_item_t *) service);
5273 
5274     // done
5275     return ERROR_CODE_SUCCESS;
5276 }
5277 
5278 uint8_t l2cap_ecbm_unregister_service(uint16_t psm) {
5279     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5280     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
5281 
5282     btstack_linked_list_remove(&l2cap_enhanced_services, (btstack_linked_item_t *) service);
5283     btstack_memory_l2cap_service_free(service);
5284     return ERROR_CODE_SUCCESS;
5285 }
5286 
5287 void l2cap_ecbm_mps_set_min(uint16_t mps_min){
5288     l2cap_enhanced_mps_min = mps_min;
5289 }
5290 
5291 void l2cap_ecbm_mps_set_max(uint16_t mps_max){
5292     l2cap_enhanced_mps_max = mps_max;
5293 }
5294 
5295 uint8_t l2cap_ecbm_create_channels(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5296                                        gap_security_level_t security_level,
5297                                        uint16_t psm, uint8_t num_channels, uint16_t initial_credits, uint16_t mtu,
5298                                        uint8_t ** receive_sdu_buffers, uint16_t * out_local_cid){
5299 
5300     log_info("create enhanced, handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
5301 
5302     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5303     if (!connection) {
5304         log_error("no hci_connection for handle 0x%04x", con_handle);
5305         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5306     }
5307 
5308     // setup all channels
5309     btstack_linked_list_t channels = NULL;
5310     uint8_t status = l2cap_ecbm_setup_channels(&channels, packet_handler, num_channels, connection, psm, mtu,
5311                                                security_level);
5312 
5313     // add to connections list and set state + local_sig_id
5314     l2cap_channel_t * channel;
5315     uint8_t i = 0;
5316     uint8_t local_sig_id = l2cap_next_sig_id();
5317     while (true) {
5318         channel = (l2cap_channel_t *) btstack_linked_list_pop(&channels);
5319         if (channel == NULL) break;
5320         channel->state              = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST;
5321         channel->local_sig_id       = local_sig_id;
5322         channel->cid_index = i;
5323         channel->num_cids = num_channels;
5324         channel->credits_incoming   = initial_credits;
5325         channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5326         channel->receive_sdu_buffer = receive_sdu_buffers[i];
5327         // store local_cid
5328         if (out_local_cid){
5329             out_local_cid[i] = channel->local_cid;
5330         }
5331         btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
5332         i++;
5333     }
5334 
5335 #if 0
5336     // check security level
5337     if (l2cap_le_security_level_for_connection(con_handle) < channel->required_security_level){
5338         if (!sm_callback_registered){
5339             sm_callback_registered = true;
5340             // lazy registration for SM events
5341             sm_event_callback_registration.callback = &l2cap_sm_packet_handler;
5342             sm_add_event_handler(&sm_event_callback_registration);
5343         }
5344 
5345         // start pairing
5346         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
5347         sm_request_pairing(con_handle);
5348     } else {
5349         // send conn request right away
5350         channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5351         l2cap_run();
5352     }
5353 #endif
5354 
5355     l2cap_run();
5356 
5357     return status;
5358 }
5359 
5360 uint8_t l2cap_ecbm_accept_channels(uint16_t local_cid, uint8_t num_channels, uint16_t initial_credits,
5361                                             uint16_t receive_buffer_size, uint8_t ** receive_buffers, uint16_t * out_local_cids){
5362 
5363     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5364     if (!channel) {
5365 
5366         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5367     }
5368     //
5369     hci_con_handle_t  con_handle    = channel->con_handle;
5370     uint8_t           local_sig_id  = channel->local_sig_id;
5371     uint8_t           channel_index = 0;
5372     btstack_linked_list_iterator_t it;
5373     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5374     while (btstack_linked_list_iterator_has_next(&it)) {
5375         channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5376         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5377         if (channel->con_handle != con_handle) continue;
5378         if (channel->local_sig_id != local_sig_id) continue;
5379         if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT) continue;
5380 
5381         if (channel_index < num_channels){
5382             // assign buffer and cid
5383             out_local_cids[channel_index] = channel->local_cid;
5384             channel->receive_sdu_buffer = receive_buffers[channel_index];
5385             channel->local_mtu = receive_buffer_size;
5386             channel->credits_incoming   = initial_credits;
5387             channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5388             channel_index++;
5389         } else {
5390             // clear local cid for response packet
5391             channel->local_cid = 0;
5392             channel->reason = L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INSUFFICIENT_RESOURCES_AVAILABLE;
5393         }
5394         // update state
5395         channel->state = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE;
5396     }
5397     l2cap_run();
5398     return ERROR_CODE_SUCCESS;
5399 }
5400 
5401 uint8_t l2cap_ecbm_decline_channels(uint16_t local_cid, uint16_t result){
5402     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5403     if (!channel) {
5404         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5405     }
5406     //
5407     hci_con_handle_t  con_handle    = channel->con_handle;
5408     uint8_t           local_sig_id  = channel->local_sig_id;
5409     btstack_linked_list_iterator_t it;
5410     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5411     while (btstack_linked_list_iterator_has_next(&it)) {
5412         channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5413         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5414         if (channel->con_handle != con_handle) continue;
5415         if (channel->local_sig_id != local_sig_id) continue;
5416         if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT) continue;
5417 
5418         // prepare response
5419         channel->local_cid = 0;
5420         channel->reason = result;
5421         channel->state = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE;
5422     }
5423     l2cap_run();
5424     return ERROR_CODE_SUCCESS;
5425 }
5426 
5427 uint8_t l2cap_ecbm_reconfigure_channels(uint8_t num_cids, uint16_t * local_cids, int16_t receive_buffer_size, uint8_t ** receive_buffers){
5428     btstack_assert(receive_buffers != NULL);
5429     btstack_assert(local_cids != NULL);
5430 
5431     if (num_cids > L2CAP_ECBM_MAX_CID_ARRAY_SIZE){
5432         return ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS;
5433     }
5434 
5435     // check if all cids exist and have the same con handle
5436     uint8_t i;
5437     hci_con_handle_t con_handle = HCI_CON_HANDLE_INVALID;
5438     for (i = 0 ; i < num_cids ; i++){
5439         l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cids[i]);
5440         if (!channel) {
5441             return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5442         }
5443         if (channel->state != L2CAP_STATE_OPEN){
5444             return ERROR_CODE_COMMAND_DISALLOWED;
5445         }
5446         if (con_handle == HCI_CON_HANDLE_INVALID){
5447             con_handle = channel->con_handle;
5448         } else if (con_handle != channel->con_handle){
5449             return ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS;
5450         }
5451     }
5452     // set renegotiation data and state
5453     uint8_t sig_id = l2cap_next_sig_id();
5454     for (i = 0 ; i < num_cids ; i++){
5455         l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cids[i]);
5456         channel->cid_index = i;
5457         channel->num_cids = num_cids;
5458         channel->local_sig_id = sig_id;
5459         channel->renegotiate_mtu = receive_buffer_size;
5460         channel->renegotiate_sdu_buffer = receive_buffers[i];
5461         channel->state = L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST;
5462     }
5463 
5464 
5465     l2cap_run();
5466     return ERROR_CODE_SUCCESS;
5467 }
5468 
5469 uint8_t l2cap_ecbm_provide_credits(uint16_t local_cid, uint16_t credits){
5470     return l2cap_credit_based_provide_credits(local_cid, credits);
5471 }
5472 #endif
5473 
5474 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
5475 // @deprecated - please use l2cap_ertm_create_channel
5476 uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
5477                                   l2cap_ertm_config_t * ertm_contig, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
5478     log_error("deprecated - please use l2cap_ertm_create_channel");
5479     return l2cap_ertm_create_channel(packet_handler, address, psm, ertm_contig, buffer, size, out_local_cid);
5480 };
5481 
5482 // @deprecated - please use l2cap_ertm_accept_connection
5483 uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, l2cap_ertm_config_t * ertm_contig, uint8_t * buffer, uint32_t size){
5484     log_error("deprecated - please use l2cap_ertm_accept_connection");
5485     return l2cap_ertm_accept_connection(local_cid, ertm_contig, buffer, size);
5486 }
5487 #endif
5488 
5489 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
5490 // @deprecated - please use l2cap_cbm_register_service
5491 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
5492     log_error("deprecated - please use l2cap_cbm_register_service");
5493     return l2cap_cbm_register_service(packet_handler, psm, security_level);
5494 }
5495 
5496 // @deprecated - please use l2cap_cbm_unregister_service
5497 uint8_t l2cap_le_unregister_service(uint16_t psm){
5498     log_error("deprecated - please use l2cap_cbm_unregister_service");
5499     return l2cap_cbm_unregister_service(psm);
5500 }
5501 
5502 // @deprecated - please use l2cap_cbm_accept_connection
5503 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
5504     log_error("deprecated - please use l2cap_cbm_accept_connection");
5505     return l2cap_cbm_accept_connection(local_cid, receive_sdu_buffer, mtu, initial_credits);
5506 }
5507 
5508 // @deprecated - please use l2cap_cbm_decline_connection
5509 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
5510     log_error("deprecated - please use l2cap_cbm_decline_connection");
5511     return l2cap_cbm_decline_connection(local_cid, L2CAP_CBM_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE);
5512 }
5513 
5514 // @deprecated - please use l2cap_cbm_create_channel
5515 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5516                                 uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
5517                                 uint16_t * out_local_cid){
5518     log_error("deprecated - please use l2cap_cbm_create_channel");
5519     return l2cap_cbm_create_channel(packet_handler, con_handle, psm, receive_sdu_buffer, mtu, initial_credits, security_level, out_local_cid);
5520 }
5521 
5522 // @deprecated - please use l2cap_cbm_provide_credits
5523 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
5524     log_error("deprecated - please use l2cap_cbm_provide_credits");
5525     return l2cap_cbm_provide_credits(local_cid, credits);
5526 }
5527 
5528 // @deprecated - please use l2cap_can_send_packet_now
5529 bool l2cap_le_can_send_now(uint16_t local_cid){
5530     log_error("deprecated - please use l2cap_can_send_packet_now");
5531     return l2cap_can_send_packet_now(local_cid);
5532 }
5533 
5534 // @deprecated - please use l2cap_request_can_send_now_event
5535 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
5536     log_error("deprecated - please use l2cap_request_can_send_now_event");
5537     return l2cap_request_can_send_now_event(local_cid);
5538 }
5539 
5540 // @deprecated - please use l2cap_cbm_send_data
5541 uint8_t l2cap_le_send_data(uint16_t local_cid, const uint8_t * data, uint16_t size){
5542     log_error("deprecated - please use l2cap_cbm_send_data");
5543     return l2cap_send(local_cid, data, size);
5544 }
5545 
5546 // @deprecated - please use l2cap_disconnect
5547 uint8_t l2cap_le_disconnect(uint16_t local_cid){
5548     log_error("deprecated - please use l2cap_disconnect");
5549     return l2cap_disconnect(local_cid);
5550 }
5551 #endif
5552