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