xref: /btstack/src/l2cap.c (revision a9ec7ee053cb5b64c1651a56c2d80606d96c8a9d)
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     // we need to know if ERTM is supported before sending a config response
724     channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
725     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
726     btstack_assert(connection != NULL);
727     switch (connection->l2cap_state.information_state){
728         case L2CAP_INFORMATION_STATE_IDLE:
729             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
730             break;
731         case L2CAP_INFORMATION_STATE_DONE:
732             l2cap_handle_information_request_complete(connection);
733             break;
734         default:
735             break;
736     }
737 
738     l2cap_run();
739 
740     return ERROR_CODE_SUCCESS;
741 }
742 
743 uint8_t l2cap_ertm_decline_connection(uint16_t local_cid){
744     l2cap_decline_connection(local_cid);
745     return ERROR_CODE_SUCCESS;
746 }
747 
748 uint8_t l2cap_ertm_set_busy(uint16_t local_cid){
749     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
750     if (!channel) {
751         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
752         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
753     }
754     if (!channel->local_busy){
755         channel->local_busy = 1;
756         channel->send_supervisor_frame_receiver_not_ready = 1;
757         l2cap_run();
758     }
759     return ERROR_CODE_SUCCESS;
760 }
761 
762 uint8_t l2cap_ertm_set_ready(uint16_t local_cid){
763     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
764     if (!channel) {
765         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
766         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
767     }
768     if (channel->local_busy){
769         channel->local_busy = 0;
770         channel->send_supervisor_frame_receiver_ready_poll = 1;
771         l2cap_run();
772     }
773     return ERROR_CODE_SUCCESS;
774 }
775 
776 // Process-ReqSeq
777 static void l2cap_ertm_process_req_seq(l2cap_channel_t * l2cap_channel, uint8_t req_seq){
778     int num_buffers_acked = 0;
779     l2cap_ertm_tx_packet_state_t * tx_state;
780     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);
781     while (true){
782 
783         // no unack packets left
784         if (l2cap_channel->unacked_frames == 0) {
785             // stop retransmission timer
786             l2cap_ertm_stop_retransmission_timer(l2cap_channel);
787             break;
788         }
789 
790         tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
791         // calc delta
792         int delta = (req_seq - tx_state->tx_seq) & 0x03f;
793         if (delta == 0) break;  // all packets acknowledged
794         if (delta > l2cap_channel->remote_tx_window_size) break;
795 
796         num_buffers_acked++;
797         l2cap_channel->num_stored_tx_frames--;
798         l2cap_channel->unacked_frames--;
799         log_info("RR seq %u => packet with tx_seq %u done", req_seq, tx_state->tx_seq);
800 
801         l2cap_channel->tx_read_index++;
802         if (l2cap_channel->tx_read_index >= l2cap_channel->num_rx_buffers){
803             l2cap_channel->tx_read_index = 0;
804         }
805     }
806     if (num_buffers_acked){
807         log_info("num_buffers_acked %u", num_buffers_acked);
808     l2cap_ertm_notify_channel_can_send(l2cap_channel);
809 }
810 }
811 
812 static l2cap_ertm_tx_packet_state_t * l2cap_ertm_get_tx_state(l2cap_channel_t * l2cap_channel, uint8_t tx_seq){
813     int i;
814     for (i=0;i<l2cap_channel->num_tx_buffers;i++){
815         l2cap_ertm_tx_packet_state_t * tx_state = &l2cap_channel->tx_packets_state[i];
816         if (tx_state->tx_seq == tx_seq) return tx_state;
817     }
818     return NULL;
819 }
820 
821 // @param delta number of frames in the future, >= 1
822 // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
823 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){
824     log_info("Store SDU with delta %u", delta);
825     // get rx state for packet to store
826     int index = l2cap_channel->rx_store_index + delta - 1;
827     if (index > l2cap_channel->num_rx_buffers){
828         index -= l2cap_channel->num_rx_buffers;
829     }
830     log_info("Index of packet to store %u", index);
831     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
832     // check if buffer is free
833     if (rx_state->valid){
834         log_error("Packet buffer already used");
835         return;
836     }
837     rx_state->valid = 1;
838     rx_state->sar = sar;
839     rx_state->len = size;
840     uint8_t * rx_buffer = &l2cap_channel->rx_packets_data[index];
841     (void)memcpy(rx_buffer, payload, size);
842 }
843 
844 // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
845 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){
846     uint16_t reassembly_sdu_length;
847     switch (sar){
848         case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
849             // assert total packet size <= our mtu
850             if (size > l2cap_channel->local_mtu) break;
851             // packet complete -> disapatch
852             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, (uint8_t*) payload, size);
853             break;
854         case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
855             // read SDU len
856             reassembly_sdu_length = little_endian_read_16(payload, 0);
857             payload += 2;
858             size    -= 2;
859             // assert reassembled size <= our mtu
860             if (reassembly_sdu_length > l2cap_channel->local_mtu) break;
861             // store start segment
862             l2cap_channel->reassembly_sdu_length = reassembly_sdu_length;
863             (void)memcpy(&l2cap_channel->reassembly_buffer[0], payload, size);
864             l2cap_channel->reassembly_pos = size;
865             break;
866         case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
867             // assert size of reassembled data <= our mtu
868             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
869             // store continuation segment
870             (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
871                          payload, size);
872             l2cap_channel->reassembly_pos += size;
873             break;
874         case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
875             // assert size of reassembled data <= our mtu
876             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
877             // store continuation segment
878             (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
879                          payload, size);
880             l2cap_channel->reassembly_pos += size;
881             // assert size of reassembled data matches announced sdu length
882             if (l2cap_channel->reassembly_pos != l2cap_channel->reassembly_sdu_length) break;
883             // packet complete -> disapatch
884             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->reassembly_buffer, l2cap_channel->reassembly_pos);
885             l2cap_channel->reassembly_pos = 0;
886             break;
887         default:
888             btstack_assert(false);
889             break;
890     }
891 }
892 
893 static void l2cap_ertm_channel_send_information_frame(l2cap_channel_t * channel){
894     channel->unacked_frames++;
895     int index = channel->tx_send_index;
896     channel->tx_send_index++;
897     if (channel->tx_send_index >= channel->num_tx_buffers){
898         channel->tx_send_index = 0;
899     }
900     l2cap_ertm_send_information_frame(channel, index, 0);   // final = 0
901 }
902 
903 #endif
904 
905 #ifdef L2CAP_USES_CHANNELS
906 static uint16_t l2cap_next_local_cid(void){
907     do {
908         if (l2cap_local_source_cid == 0xfffeu) {
909             l2cap_local_source_cid = 0x40;
910         } else {
911             l2cap_local_source_cid++;
912         }
913     } while (l2cap_get_channel_for_local_cid(l2cap_local_source_cid) != NULL);
914     return l2cap_local_source_cid;
915 }
916 #endif
917 
918 static uint8_t l2cap_next_sig_id(void){
919     if (l2cap_sig_seq_nr == 0xffu) {
920         l2cap_sig_seq_nr = 1;
921     } else {
922         l2cap_sig_seq_nr++;
923     }
924     return l2cap_sig_seq_nr;
925 }
926 
927 void l2cap_init(void){
928 #ifdef L2CAP_USES_CHANNELS
929     l2cap_local_source_cid  = 0x40;
930 #endif
931     l2cap_sig_seq_nr  = 0xff;
932 
933 #ifdef ENABLE_CLASSIC
934     // Setup Connectionless Channel
935     l2cap_fixed_channel_connectionless.local_cid     = L2CAP_CID_CONNECTIONLESS_CHANNEL;
936     l2cap_fixed_channel_connectionless.channel_type  = L2CAP_CHANNEL_TYPE_CONNECTIONLESS;
937     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_connectionless);
938 #endif
939 
940 #ifdef ENABLE_BLE
941     // Setup fixed ATT Channel
942     l2cap_fixed_channel_att.local_cid    = L2CAP_CID_ATTRIBUTE_PROTOCOL;
943     l2cap_fixed_channel_att.channel_type = L2CAP_CHANNEL_TYPE_FIXED;
944     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_att);
945 
946     // Setup fixed SM Channel
947     l2cap_fixed_channel_sm.local_cid     = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
948     l2cap_fixed_channel_sm.channel_type  = L2CAP_CHANNEL_TYPE_FIXED;
949     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_sm);
950 #endif
951 
952 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
953     l2cap_enhanced_mps_min = 0x0001;
954     l2cap_enhanced_mps_max = 0xffff;
955 #endif
956 
957     //
958     // register callback with HCI
959     //
960     l2cap_hci_event_callback_registration.callback = &l2cap_hci_event_handler;
961     hci_add_event_handler(&l2cap_hci_event_callback_registration);
962 
963     hci_register_acl_packet_handler(&l2cap_acl_handler);
964 
965 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
966 #ifdef ENABLE_CLASSIC
967     gap_connectable_control(0); // no services yet
968 #endif
969 #endif
970 }
971 
972 /**
973  * @brief De-Init L2CAP
974  */
975 void l2cap_deinit(void){
976     l2cap_channels = NULL;
977     l2cap_signaling_responses_pending = 0;
978 #ifdef ENABLE_CLASSIC
979     l2cap_require_security_level2_for_outgoing_sdp = 0;
980     (void)memset(&l2cap_fixed_channel_connectionless, 0, sizeof(l2cap_fixed_channel_connectionless));
981     l2cap_services = NULL;
982     (void)memset(l2cap_outgoing_classic_addr, 0, 6);
983 #endif
984 #ifdef ENABLE_BLE
985     l2cap_le_custom_max_mtu = 0;
986     (void)memset(&l2cap_fixed_channel_att, 0, sizeof(l2cap_fixed_channel_att));
987     (void)memset(&l2cap_fixed_channel_sm, 0, sizeof(l2cap_fixed_channel_sm));
988 #endif
989 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
990     l2cap_le_services = NULL;
991 #endif
992 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
993     l2cap_enhanced_services = NULL;
994 #endif
995     l2cap_event_handlers = NULL;
996 }
997 
998 void l2cap_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
999     btstack_linked_list_add_tail(&l2cap_event_handlers, (btstack_linked_item_t*) callback_handler);
1000 }
1001 
1002 void l2cap_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
1003     btstack_linked_list_remove(&l2cap_event_handlers, (btstack_linked_item_t*) callback_handler);
1004 }
1005 
1006 static void l2cap_emit_event(uint8_t *event, uint16_t size) {
1007     hci_dump_packet( HCI_EVENT_PACKET, 1, event, size);
1008     // dispatch to all event handlers
1009     btstack_linked_list_iterator_t it;
1010     btstack_linked_list_iterator_init(&it, &l2cap_event_handlers);
1011     while (btstack_linked_list_iterator_has_next(&it)){
1012         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
1013         entry->callback(HCI_EVENT_PACKET, 0, event, size);
1014     }
1015 }
1016 
1017 void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
1018     UNUSED(con_handle);  // ok: there is no con handle
1019 
1020     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
1021     if (!channel) return;
1022     channel->waiting_for_can_send_now = 1;
1023     l2cap_notify_channel_can_send();
1024 }
1025 
1026 bool l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
1027     UNUSED(channel_id); // ok: only depends on Controller LE buffers
1028 
1029     return hci_can_send_acl_packet_now(con_handle);
1030 }
1031 
1032 uint8_t *l2cap_get_outgoing_buffer(void){
1033     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
1034 }
1035 
1036 // only for L2CAP Basic Channels
1037 bool l2cap_reserve_packet_buffer(void){
1038     return hci_reserve_packet_buffer();
1039 }
1040 
1041 // only for L2CAP Basic Channels
1042 void l2cap_release_packet_buffer(void){
1043     hci_release_packet_buffer();
1044 }
1045 
1046 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){
1047     // 0 - Connection handle : PB=pb : BC=00
1048     little_endian_store_16(acl_buffer, 0u, con_handle | (packet_boundary << 12u) | (0u << 14u));
1049     // 2 - ACL length
1050     little_endian_store_16(acl_buffer, 2u,  len + 4u);
1051     // 4 - L2CAP packet length
1052     little_endian_store_16(acl_buffer, 4u,  len + 0u);
1053     // 6 - L2CAP channel DEST
1054     little_endian_store_16(acl_buffer, 6,  remote_cid);
1055 }
1056 
1057 // assumption - only on LE connections
1058 uint8_t l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
1059 
1060     if (!hci_is_packet_buffer_reserved()){
1061         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
1062         return BTSTACK_ACL_BUFFERS_FULL;
1063     }
1064 
1065     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
1066         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
1067         return BTSTACK_ACL_BUFFERS_FULL;
1068     }
1069 
1070     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
1071 
1072     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1073     l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
1074     // send
1075     return hci_send_acl_packet_buffer(len+8u);
1076 }
1077 
1078 // assumption - only on LE connections
1079 uint8_t l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
1080 
1081     if (!hci_can_send_acl_packet_now(con_handle)){
1082         log_info("l2cap_send cid 0x%02x, cannot send", cid);
1083         return BTSTACK_ACL_BUFFERS_FULL;
1084     }
1085 
1086     hci_reserve_packet_buffer();
1087     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1088 
1089     (void)memcpy(&acl_buffer[8], data, len);
1090 
1091     return l2cap_send_prepared_connectionless(con_handle, cid, len);
1092 }
1093 
1094 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
1095     log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
1096     uint8_t event[4];
1097     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
1098     event[1] = sizeof(event) - 2u;
1099     little_endian_store_16(event, 2, channel);
1100     hci_dump_packet( HCI_EVENT_PACKET, 1, event, sizeof(event));
1101     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
1102 }
1103 
1104 #ifdef L2CAP_USES_CHANNELS
1105 static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
1106     (* (channel->packet_handler))(type, channel->local_cid, data, size);
1107 }
1108 
1109 static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
1110     uint8_t event[4];
1111     event[0] = event_code;
1112     event[1] = sizeof(event) - 2u;
1113     little_endian_store_16(event, 2, channel->local_cid);
1114     hci_dump_packet( HCI_EVENT_PACKET, 1, event, sizeof(event));
1115     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1116 }
1117 #endif
1118 
1119 #ifdef ENABLE_CLASSIC
1120 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
1121     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",
1122              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
1123              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
1124     uint8_t event[26];
1125     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
1126     event[1] = sizeof(event) - 2;
1127     event[2] = status;
1128     reverse_bd_addr(channel->address, &event[3]);
1129     little_endian_store_16(event,  9, channel->con_handle);
1130     little_endian_store_16(event, 11, channel->psm);
1131     little_endian_store_16(event, 13, channel->local_cid);
1132     little_endian_store_16(event, 15, channel->remote_cid);
1133     little_endian_store_16(event, 17, channel->local_mtu);
1134     little_endian_store_16(event, 19, channel->remote_mtu);
1135     little_endian_store_16(event, 21, channel->flush_timeout);
1136     event[23] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
1137 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1138     log_info("ERTM mode %u, fcs enabled %u", channel->mode, channel->fcs_option);
1139     event[24] = channel->mode;
1140     event[25] = channel->fcs_option;
1141 
1142 #else
1143     event[24] = L2CAP_CHANNEL_MODE_BASIC;
1144     event[25] = 0;
1145 #endif
1146     hci_dump_packet( HCI_EVENT_PACKET, 1, event, sizeof(event));
1147     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1148 }
1149 
1150 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
1151     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
1152              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
1153     uint8_t event[16];
1154     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
1155     event[1] = sizeof(event) - 2;
1156     reverse_bd_addr(channel->address, &event[2]);
1157     little_endian_store_16(event,  8, channel->con_handle);
1158     little_endian_store_16(event, 10, channel->psm);
1159     little_endian_store_16(event, 12, channel->local_cid);
1160     little_endian_store_16(event, 14, channel->remote_cid);
1161     hci_dump_packet( HCI_EVENT_PACKET, 1, event, sizeof(event));
1162     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1163 }
1164 
1165 static void l2cap_handle_channel_open_failed(l2cap_channel_t * channel, uint8_t status){
1166 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1167     // emit ertm buffer released, as it's not needed. if in basic mode, it was either not allocated or already released
1168     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1169         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1170     }
1171 #endif
1172     l2cap_emit_channel_opened(channel, status);
1173 }
1174 
1175 #endif
1176 
1177 #ifdef L2CAP_USES_CHANNELS
1178 
1179 static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
1180     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
1181     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
1182 }
1183 
1184 static void l2cap_handle_channel_closed(l2cap_channel_t * channel){
1185 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1186     // emit ertm buffer released, as it's not needed anymore. if in basic mode, it was either not allocated or already released
1187     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1188         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1189     }
1190 #endif
1191     l2cap_emit_channel_closed(channel);
1192 }
1193 #endif
1194 
1195 static l2cap_fixed_channel_t * l2cap_channel_item_by_cid(uint16_t cid){
1196     btstack_linked_list_iterator_t it;
1197     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1198     while (btstack_linked_list_iterator_has_next(&it)){
1199         l2cap_fixed_channel_t * channel = (l2cap_fixed_channel_t*) btstack_linked_list_iterator_next(&it);
1200         if (channel->local_cid == cid) {
1201             return channel;
1202         }
1203     }
1204     return NULL;
1205 }
1206 
1207 // used for fixed channels in LE (ATT/SM) and Classic (Connectionless Channel). CID < 0x04
1208 static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid){
1209     if (local_cid >= 0x40u) return NULL;
1210     return (l2cap_fixed_channel_t*) l2cap_channel_item_by_cid(local_cid);
1211 }
1212 
1213 #ifdef L2CAP_USES_CHANNELS
1214 
1215 static int l2cap_is_dynamic_channel_type(l2cap_channel_type_t channel_type) {
1216     switch (channel_type) {
1217         case L2CAP_CHANNEL_TYPE_CLASSIC:
1218         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
1219         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
1220             return 1;
1221         default:
1222             return 0;
1223     }
1224 }
1225 
1226 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
1227     if (local_cid < 0x40u) return NULL;
1228     return (l2cap_channel_t*) l2cap_channel_item_by_cid(local_cid);
1229 }
1230 
1231 static l2cap_channel_t * l2cap_get_channel_for_local_cid_and_handle(uint16_t local_cid, hci_con_handle_t con_handle){
1232     if (local_cid < 0x40u) return NULL;
1233     l2cap_channel_t * l2cap_channel = (l2cap_channel_t*) l2cap_channel_item_by_cid(local_cid);
1234     if (l2cap_channel == NULL)  return NULL;
1235     if (l2cap_channel->con_handle != con_handle) return NULL;
1236     return l2cap_channel;
1237 }
1238 #endif
1239 
1240 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
1241 static l2cap_channel_t * l2cap_get_channel_for_remote_handle_and_cid(hci_con_handle_t con_handle, uint16_t remote_cid){
1242     btstack_linked_list_iterator_t it;
1243     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1244     while (btstack_linked_list_iterator_has_next(&it)){
1245         l2cap_fixed_channel_t * channel = (l2cap_fixed_channel_t*) btstack_linked_list_iterator_next(&it);
1246         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
1247         l2cap_channel_t * dynamic_channel = (l2cap_channel_t *) channel;
1248         if (dynamic_channel->con_handle != con_handle) continue;
1249         if (dynamic_channel->remote_cid != remote_cid) continue;
1250         return dynamic_channel;
1251     }
1252     return NULL;
1253 }
1254 #endif
1255 
1256 #ifdef L2CAP_USES_CHANNELS
1257 uint8_t l2cap_request_can_send_now_event(uint16_t local_cid){
1258     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1259     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
1260     channel->waiting_for_can_send_now = 1;
1261     switch (channel->channel_type){
1262         case L2CAP_CHANNEL_TYPE_CLASSIC:
1263 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1264             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1265                 l2cap_ertm_notify_channel_can_send(channel);
1266                 return ERROR_CODE_SUCCESS;
1267             }
1268 #endif
1269             l2cap_notify_channel_can_send();
1270             break;
1271 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
1272         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
1273             l2cap_credit_based_notify_channel_can_send(channel);
1274             break;
1275 #endif
1276 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1277         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
1278             l2cap_credit_based_notify_channel_can_send(channel);
1279             break;
1280 #endif
1281         default:
1282             break;
1283     }
1284     return ERROR_CODE_SUCCESS;
1285 }
1286 
1287 bool l2cap_can_send_packet_now(uint16_t local_cid){
1288     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1289     if (!channel) return false;
1290     if (channel->state != L2CAP_STATE_OPEN) return false;
1291     switch (channel->channel_type){
1292         case L2CAP_CHANNEL_TYPE_CLASSIC:
1293 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1294             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1295                 return l2cap_ertm_can_store_packet_now(channel);
1296             }
1297 #endif
1298             return hci_can_send_acl_packet_now(channel->con_handle);
1299 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
1300         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
1301             return channel->send_sdu_buffer == NULL;
1302 #endif
1303 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1304         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
1305             return channel->send_sdu_buffer == NULL;
1306 #endif
1307         default:
1308             return false;
1309     }
1310 }
1311 
1312 uint8_t l2cap_send(uint16_t local_cid, const uint8_t *data, uint16_t len){
1313     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1314     if (!channel) {
1315         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
1316         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
1317     }
1318     switch (channel->channel_type){
1319 #ifdef ENABLE_CLASSIC
1320         case L2CAP_CHANNEL_TYPE_CLASSIC:
1321             return l2cap_classic_send(channel, data, len);
1322 #endif
1323 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
1324         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
1325             return l2cap_credit_based_send_data(channel, data, len);
1326 #endif
1327 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1328         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
1329             return l2cap_credit_based_send_data(channel, data, len);
1330 #endif
1331         default:
1332             return ERROR_CODE_UNSPECIFIED_ERROR;
1333     }
1334 }
1335 #endif
1336 
1337 #ifdef ENABLE_CLASSIC
1338 bool l2cap_can_send_prepared_packet_now(uint16_t local_cid){
1339     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1340     if (!channel) return false;
1341 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1342     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1343         return false;
1344     }
1345 #endif
1346     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
1347 }
1348 
1349 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
1350     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1351     if (channel) {
1352         return channel->remote_mtu;
1353     }
1354     return 0;
1355 }
1356 #endif
1357 
1358 #ifdef ENABLE_CLASSIC
1359 // RTX Timer only exist for dynamic channels
1360 static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
1361     btstack_linked_list_iterator_t it;
1362     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1363     while (btstack_linked_list_iterator_has_next(&it)){
1364         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1365         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
1366         if (&channel->rtx == ts) {
1367             return channel;
1368         }
1369     }
1370     return NULL;
1371 }
1372 
1373 static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
1374     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
1375     if (!channel) return;
1376 
1377     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
1378 
1379     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
1380     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
1381     // notify client
1382     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
1383 
1384     // discard channel
1385     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1386     l2cap_free_channel_entry(channel);
1387 }
1388 
1389 static uint8_t l2cap_classic_packet_boundary_flag(void){
1390     return (hci_non_flushable_packet_boundary_flag_supported() && (hci_automatic_flush_timeout() == 0)) ? 0x00 : 0x02;
1391 }
1392 #endif
1393 
1394 #ifdef L2CAP_USES_CHANNELS
1395 static void l2cap_stop_rtx(l2cap_channel_t * channel){
1396     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
1397     btstack_run_loop_remove_timer(&channel->rtx);
1398 }
1399 #endif
1400 
1401 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){
1402     if (!hci_can_send_acl_packet_now(handle)){
1403         log_info("l2cap_send_classic_signaling_packet, cannot send");
1404         return BTSTACK_ACL_BUFFERS_FULL;
1405     }
1406     hci_reserve_packet_buffer();
1407     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1408     uint16_t len = l2cap_create_signaling_packet(acl_buffer, handle, pb_flags, cid, cmd, identifier, argptr);
1409     va_end(argptr);
1410     return hci_send_acl_packet_buffer(len);
1411 }
1412 
1413 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
1414 static int l2cap_send_general_signaling_packet(hci_con_handle_t handle, uint16_t signaling_cid, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1415     va_list argptr;
1416     va_start(argptr, identifier);
1417     uint8_t pb_flags = 0x00;
1418 #ifdef ENABLE_CLASSIC
1419     if (signaling_cid == L2CAP_CID_SIGNALING){
1420         pb_flags = l2cap_classic_packet_boundary_flag();
1421     }
1422 #endif
1423 uint8_t result = l2cap_send_signaling_packet(handle, pb_flags, signaling_cid, cmd, identifier, argptr);
1424     va_end(argptr);
1425     return result;
1426 }
1427 #endif
1428 
1429 #ifdef ENABLE_CLASSIC
1430 
1431 static void l2cap_start_rtx(l2cap_channel_t * channel){
1432     l2cap_stop_rtx(channel);
1433     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
1434     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1435     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
1436     btstack_run_loop_add_timer(&channel->rtx);
1437 }
1438 
1439 static void l2cap_start_ertx(l2cap_channel_t * channel){
1440     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
1441     l2cap_stop_rtx(channel);
1442     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1443     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
1444     btstack_run_loop_add_timer(&channel->rtx);
1445 }
1446 
1447 void l2cap_require_security_level_2_for_outgoing_sdp(void){
1448     l2cap_require_security_level2_for_outgoing_sdp = 1;
1449 }
1450 
1451 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
1452     return (psm == BLUETOOTH_PSM_SDP) && (!l2cap_require_security_level2_for_outgoing_sdp);
1453 }
1454 
1455 static int l2cap_send_classic_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1456     va_list argptr;
1457     va_start(argptr, identifier);
1458     uint8_t pb_flag = l2cap_classic_packet_boundary_flag();
1459     uint8_t result = l2cap_send_signaling_packet(handle, pb_flag, L2CAP_CID_SIGNALING, cmd, identifier, argptr);
1460     va_end(argptr);
1461     return result;
1462 }
1463 
1464 // assumption - only on Classic connections
1465 // cannot be used for L2CAP ERTM
1466 uint8_t l2cap_send_prepared(uint16_t local_cid, uint16_t len){
1467 
1468     if (!hci_is_packet_buffer_reserved()){
1469         log_error("l2cap_send_prepared called without reserving packet first");
1470         return BTSTACK_ACL_BUFFERS_FULL;
1471     }
1472 
1473     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1474     if (!channel) {
1475         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
1476         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
1477     }
1478 
1479     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
1480         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
1481         return BTSTACK_ACL_BUFFERS_FULL;
1482     }
1483 
1484     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
1485 
1486     int fcs_size = 0;
1487 
1488 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1489     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->fcs_option){
1490         fcs_size = 2;
1491     }
1492 #endif
1493 
1494     // set non-flushable packet boundary flag if supported on Controller
1495     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1496     uint8_t packet_boundary_flag = l2cap_classic_packet_boundary_flag();
1497     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
1498 
1499 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1500     if (fcs_size){
1501         // calculate FCS over l2cap data
1502         uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
1503         log_info("I-Frame: fcs 0x%04x", fcs);
1504         little_endian_store_16(acl_buffer, 8 + len, fcs);
1505     }
1506 #endif
1507 
1508     // send
1509     return hci_send_acl_packet_buffer(len+8+fcs_size);
1510 }
1511 
1512 // assumption - only on Classic connections
1513 static uint8_t l2cap_classic_send(l2cap_channel_t * channel, const uint8_t *data, uint16_t len){
1514 
1515 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1516     // send in ERTM
1517     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1518         return l2cap_ertm_send(channel, data, len);
1519     }
1520 #endif
1521 
1522     if (len > channel->remote_mtu){
1523         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
1524         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
1525     }
1526 
1527     if (!hci_can_send_acl_packet_now(channel->con_handle)){
1528         log_info("l2cap_send cid 0x%02x, cannot send", channel->local_cid);
1529         return BTSTACK_ACL_BUFFERS_FULL;
1530     }
1531 
1532     hci_reserve_packet_buffer();
1533     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1534     (void)memcpy(&acl_buffer[8], data, len);
1535     return l2cap_send_prepared(channel->local_cid, len);
1536 }
1537 
1538 int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
1539     return l2cap_send_classic_signaling_packet(con_handle, ECHO_REQUEST, l2cap_next_sig_id(), len, data);
1540 }
1541 
1542 static inline void channelStateVarSetFlag(l2cap_channel_t *channel, uint16_t flag){
1543     channel->state_var = channel->state_var | flag;
1544 }
1545 
1546 static inline void channelStateVarClearFlag(l2cap_channel_t *channel, uint16_t flag){
1547     channel->state_var = channel->state_var & ~flag;
1548 }
1549 #endif
1550 
1551 
1552 #ifdef ENABLE_BLE
1553 static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1554     va_list argptr;
1555     va_start(argptr, identifier);
1556     uint8_t pb_flags = 0x00;  // First non-automatically-flushable packet of a higher layer message
1557     uint8_t result = l2cap_send_signaling_packet(handle, pb_flags, L2CAP_CID_SIGNALING_LE, cmd, identifier, argptr);
1558     va_end(argptr);
1559     return result;
1560 }
1561 #endif
1562 
1563 uint16_t l2cap_max_mtu(void){
1564     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
1565 }
1566 
1567 #ifdef ENABLE_BLE
1568 uint16_t l2cap_max_le_mtu(void){
1569     if (l2cap_le_custom_max_mtu != 0u) return l2cap_le_custom_max_mtu;
1570     return l2cap_max_mtu();
1571 }
1572 
1573 void l2cap_set_max_le_mtu(uint16_t max_mtu){
1574     if (max_mtu < l2cap_max_mtu()){
1575         l2cap_le_custom_max_mtu = max_mtu;
1576     }
1577 }
1578 #endif
1579 
1580 #ifdef ENABLE_CLASSIC
1581 
1582 static uint16_t l2cap_setup_options_mtu(uint8_t * config_options, uint16_t mtu){
1583     config_options[0] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
1584     config_options[1] = 2; // len param
1585     little_endian_store_16(config_options, 2, mtu);
1586     return 4;
1587 }
1588 
1589 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1590 static int l2cap_ertm_mode(l2cap_channel_t * channel){
1591     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
1592     return ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE)
1593         &&  (connection->l2cap_state.extended_feature_mask & 0x08));
1594 }
1595 #endif
1596 
1597 static uint16_t l2cap_setup_options_request(l2cap_channel_t * channel, uint8_t * config_options){
1598 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1599     // use ERTM options if supported by remote and channel ready to use it
1600     if (l2cap_ertm_mode(channel) && channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1601         return l2cap_setup_options_ertm_request(channel, config_options);
1602     }
1603 #endif
1604     uint16_t mtu = channel->local_mtu;
1605     return l2cap_setup_options_mtu(config_options, mtu);
1606 }
1607 
1608 static uint16_t l2cap_setup_options_mtu_response(l2cap_channel_t * channel, uint8_t * config_options){
1609     uint16_t mtu = btstack_min(channel->local_mtu, channel->remote_mtu);
1610     return l2cap_setup_options_mtu(config_options, mtu);
1611 }
1612 
1613 static uint32_t l2cap_extended_features_mask(void){
1614     // extended features request supported, features: fixed channels, unicast connectionless data reception
1615     uint32_t features = 0x280;
1616 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1617     features |= 0x0028;
1618 #endif
1619     return features;
1620 }
1621 #endif
1622 
1623 //
1624 #ifdef ENABLE_CLASSIC
1625 
1626 // returns true if channel was finalized
1627 static bool l2cap_run_for_classic_channel(l2cap_channel_t * channel){
1628 
1629 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1630     uint8_t  config_options[18];
1631 #else
1632     uint8_t  config_options[10];
1633 #endif
1634 
1635     switch (channel->state){
1636 
1637         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1638         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
1639             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1640             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
1641                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
1642                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONN_RESP_PEND);
1643                 l2cap_send_classic_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id,
1644                                                     channel->local_cid, channel->remote_cid, 1, 0);
1645             }
1646             break;
1647 
1648         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1649             if (!hci_can_send_command_packet_now()) break;
1650             // send connection request - set state first
1651             channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
1652             // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
1653             (void)memcpy(l2cap_outgoing_classic_addr, channel->address, 6);
1654             hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_get_allow_role_switch());
1655             break;
1656 
1657         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
1658             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1659             channel->state = L2CAP_STATE_INVALID;
1660             l2cap_send_classic_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id,
1661                                                 channel->local_cid, channel->remote_cid, channel->reason, 0);
1662             // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1663             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1664             l2cap_free_channel_entry(channel);
1665             channel = NULL;
1666             break;
1667 
1668         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
1669             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1670             channel->state = L2CAP_STATE_CONFIG;
1671             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1672             l2cap_send_classic_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id,
1673                                                 channel->local_cid, channel->remote_cid, 0, 0);
1674             break;
1675 
1676         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
1677             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1678             // success, start l2cap handshake
1679             channel->local_sig_id = l2cap_next_sig_id();
1680             channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
1681             l2cap_send_classic_signaling_packet(channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id,
1682                                                 channel->psm, channel->local_cid);
1683             l2cap_start_rtx(channel);
1684             break;
1685 
1686         case L2CAP_STATE_CONFIG:
1687             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1688 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1689             // fallback to basic mode if ERTM requested but not not supported by remote
1690             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1691                 if (!l2cap_ertm_mode(channel)){
1692                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1693                     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
1694                 }
1695             }
1696 #endif
1697             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
1698                 uint16_t flags = 0;
1699                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1700                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
1701                     flags = 1;
1702                 } else {
1703                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1704                 }
1705                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
1706                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1707                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1708                                                         channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS,
1709                                                         1, &channel->unknown_option);
1710 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1711                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
1712                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1713                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1714                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1715                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1716                                                         channel->remote_cid, flags,
1717                                                         L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS, options_size,
1718                                                         &config_options);
1719                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM){
1720                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
1721                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1722                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1723                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1724                                                         channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS,
1725                                                         options_size, &config_options);
1726 #endif
1727                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
1728                     channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1729                     uint16_t options_size = l2cap_setup_options_mtu_response(channel, config_options);
1730                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1731                                                         channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS,
1732                                                         options_size, &config_options);
1733                 } else {
1734                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1735                                                         channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
1736                 }
1737                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1738             }
1739             else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
1740                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1741                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
1742                 channel->local_sig_id = l2cap_next_sig_id();
1743                 uint16_t options_size = l2cap_setup_options_request(channel, config_options);
1744                 l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id,
1745                                                     channel->remote_cid, 0, options_size, &config_options);
1746                 l2cap_start_rtx(channel);
1747             }
1748             if (l2cap_channel_ready_for_open(channel)){
1749                 channel->state = L2CAP_STATE_OPEN;
1750                 l2cap_emit_channel_opened(channel, 0);  // success
1751             }
1752             break;
1753 
1754         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1755             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1756             channel->state = L2CAP_STATE_INVALID;
1757             l2cap_send_classic_signaling_packet(channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id,
1758                                                 channel->local_cid, channel->remote_cid);
1759             // 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 :)
1760             l2cap_finalize_channel_close(channel);  // -- remove from list
1761             channel = NULL;
1762             break;
1763 
1764         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1765             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1766             channel->local_sig_id = l2cap_next_sig_id();
1767             channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1768             l2cap_send_classic_signaling_packet(channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id,
1769                                                 channel->remote_cid, channel->local_cid);
1770             break;
1771         default:
1772             break;
1773     }
1774 
1775     // handle channel finalize on L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE and L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE
1776     return channel == NULL;
1777 }
1778 
1779 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1780 static void l2cap_run_for_classic_channel_ertm(l2cap_channel_t * channel){
1781 
1782     // ERTM mode
1783     if (channel->mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) return;
1784 
1785     // check if we can still send
1786     if (channel->con_handle == HCI_CON_HANDLE_INVALID) return;
1787     if (!hci_can_send_acl_packet_now(channel->con_handle)) return;
1788 
1789     if (channel->send_supervisor_frame_receiver_ready){
1790         channel->send_supervisor_frame_receiver_ready = 0;
1791         log_info("Send S-Frame: RR %u, final %u", channel->req_seq, channel->set_final_bit_after_packet_with_poll_bit_set);
1792         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);
1793         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1794         l2cap_ertm_send_supervisor_frame(channel, control);
1795         return;
1796     }
1797     if (channel->send_supervisor_frame_receiver_ready_poll){
1798         channel->send_supervisor_frame_receiver_ready_poll = 0;
1799         log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
1800         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
1801         l2cap_ertm_send_supervisor_frame(channel, control);
1802         return;
1803     }
1804     if (channel->send_supervisor_frame_receiver_not_ready){
1805         channel->send_supervisor_frame_receiver_not_ready = 0;
1806         log_info("Send S-Frame: RNR %u", channel->req_seq);
1807         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
1808         l2cap_ertm_send_supervisor_frame(channel, control);
1809         return;
1810     }
1811     if (channel->send_supervisor_frame_reject){
1812         channel->send_supervisor_frame_reject = 0;
1813         log_info("Send S-Frame: REJ %u", channel->req_seq);
1814         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 0, 0, channel->req_seq);
1815         l2cap_ertm_send_supervisor_frame(channel, control);
1816         return;
1817     }
1818     if (channel->send_supervisor_frame_selective_reject){
1819         channel->send_supervisor_frame_selective_reject = 0;
1820         log_info("Send S-Frame: SREJ %u", channel->expected_tx_seq);
1821         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);
1822         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1823         l2cap_ertm_send_supervisor_frame(channel, control);
1824         return;
1825     }
1826 
1827     if (channel->srej_active){
1828         int i;
1829         for (i=0;i<channel->num_tx_buffers;i++){
1830             l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
1831             if (tx_state->retransmission_requested) {
1832                 tx_state->retransmission_requested = 0;
1833                 uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set;
1834                 channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1835                 l2cap_ertm_send_information_frame(channel, i, final);
1836                 break;
1837             }
1838         }
1839         if (i == channel->num_tx_buffers){
1840             // no retransmission request found
1841             channel->srej_active = 0;
1842         } else {
1843             // packet was sent
1844             return;
1845         }
1846     }
1847 }
1848 #endif /* ERTM */
1849 #endif /* Classic */
1850 
1851 static void l2cap_run_signaling_response(void) {
1852 
1853     // check pending signaling responses
1854     while (l2cap_signaling_responses_pending){
1855 
1856         hci_con_handle_t handle = l2cap_signaling_responses[0].handle;
1857 
1858         if (!hci_can_send_acl_packet_now(handle)) break;
1859 
1860         uint8_t  sig_id        = l2cap_signaling_responses[0].sig_id;
1861         uint8_t  response_code = l2cap_signaling_responses[0].code;
1862         uint16_t result        = l2cap_signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT, REJECT_SM_PAIRING, L2CAP_CREDIT_BASED_CONNECTION_REQUEST
1863         uint8_t  buffer[2];                                          // REJECT_SM_PAIRING
1864         uint16_t source_cid    = l2cap_signaling_responses[0].cid;   // CONNECTION_REQUEST, REJECT_SM_PAIRING
1865 #ifdef ENABLE_CLASSIC
1866         uint16_t info_type     = l2cap_signaling_responses[0].data;  // INFORMATION_REQUEST
1867 #endif
1868 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1869         uint8_t num_channels = l2cap_signaling_responses[0].cid >> 8;                 // L2CAP_CREDIT_BASED_CONNECTION_REQUEST
1870         uint16_t signaling_cid = (uint16_t) l2cap_signaling_responses[0].cid & 0xff;  // L2CAP_CREDIT_BASED_CONNECTION_REQUEST, L2CAP_CREDIT_BASED_CONNECTION_REQUEST
1871 #endif
1872 
1873         // remove first item before sending (to avoid sending response mutliple times)
1874         l2cap_signaling_responses_pending--;
1875         int i;
1876         for (i=0; i < l2cap_signaling_responses_pending; i++){
1877             (void)memcpy(&l2cap_signaling_responses[i],
1878                          &l2cap_signaling_responses[i + 1],
1879                          sizeof(l2cap_signaling_response_t));
1880         }
1881 
1882         switch (response_code){
1883 #ifdef ENABLE_CLASSIC
1884             case CONNECTION_REQUEST:
1885                 l2cap_send_classic_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
1886                 break;
1887             case ECHO_REQUEST:
1888                 l2cap_send_classic_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
1889                 break;
1890             case INFORMATION_REQUEST:
1891                 switch (info_type){
1892                     case L2CAP_INFO_TYPE_CONNECTIONLESS_MTU: {
1893                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
1894                         l2cap_send_classic_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0,
1895                                                             sizeof(connectionless_mtu), &connectionless_mtu);
1896                         }
1897                         break;
1898                     case L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED: {
1899                             uint32_t features = l2cap_extended_features_mask();
1900                         l2cap_send_classic_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0,
1901                                                             sizeof(features), &features);
1902                         }
1903                         break;
1904                     case L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED: {
1905                             uint8_t map[8];
1906                             memset(map, 0, 8);
1907                             // L2CAP Signaling Channel (bit 1) + Connectionless reception (bit 2)
1908                             map[0] = (1 << 1) | (1 << 2);
1909 #if defined(ENABLE_BLE) || defined (ENABLE_EXPLICIT_BR_EDR_SECURITY_MANAGER)
1910                             // BR/EDR Security Manager (bit 7) if BR/EDR Secure Connections possible
1911                             if (gap_secure_connections_active()){
1912                                 map[0] |= (1 << 7);
1913                             }
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] = (uint8_t) 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, 1, 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 
2579 #ifdef ENABLE_L2CAP_INFORMATION_REQUESTS_ON_CONNECT
2580     // trigger query of extended features and fixed channels right away (instead of later)
2581     hci_connection_t * hci_connection = hci_connection_for_handle(handle);
2582     btstack_assert(hci_connection != NULL);
2583     hci_connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2584 #endif
2585 
2586     // process
2587     l2cap_run();
2588 }
2589 #endif
2590 
2591 static bool l2cap_channel_ready_to_send(l2cap_channel_t * channel){
2592     switch (channel->channel_type){
2593 #ifdef ENABLE_CLASSIC
2594         case L2CAP_CHANNEL_TYPE_CLASSIC:
2595             if (channel->state != L2CAP_STATE_OPEN) return false;
2596 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2597             // send if we have more data and remote windows isn't full yet
2598             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2599                 if (channel->unacked_frames >= btstack_min(channel->num_stored_tx_frames, channel->remote_tx_window_size)) return false;
2600                 return hci_can_send_acl_packet_now(channel->con_handle) != 0;
2601             }
2602 #endif
2603             if (!channel->waiting_for_can_send_now) return false;
2604             return hci_can_send_acl_packet_now(channel->con_handle) != 0;
2605         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2606             if (!channel->waiting_for_can_send_now) return false;
2607             return hci_can_send_acl_classic_packet_now() != 0;
2608 #endif
2609 #ifdef ENABLE_BLE
2610         case L2CAP_CHANNEL_TYPE_FIXED:
2611             if (!channel->waiting_for_can_send_now) return false;
2612             return hci_can_send_acl_le_packet_now() != 0;
2613 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2614         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
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             return hci_can_send_acl_packet_now(channel->con_handle) != 0;
2619 #endif
2620 #endif
2621 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2622         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
2623             if (channel->state != L2CAP_STATE_OPEN) return false;
2624             if (channel->send_sdu_buffer == NULL) return false;
2625             if (channel->credits_outgoing == 0u) return false;
2626             return hci_can_send_acl_packet_now(channel->con_handle) != 0;
2627 #endif
2628         default:
2629             return false;
2630     }
2631 }
2632 
2633 static void l2cap_channel_trigger_send(l2cap_channel_t * channel){
2634     switch (channel->channel_type){
2635 #ifdef ENABLE_CLASSIC
2636         case L2CAP_CHANNEL_TYPE_CLASSIC:
2637 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2638             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2639                 l2cap_ertm_channel_send_information_frame(channel);
2640                 return;
2641             }
2642 #endif
2643             channel->waiting_for_can_send_now = 0;
2644             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2645             break;
2646         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2647             channel->waiting_for_can_send_now = 0;
2648             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2649             break;
2650 #endif
2651 #ifdef ENABLE_BLE
2652         case L2CAP_CHANNEL_TYPE_FIXED:
2653             channel->waiting_for_can_send_now = 0;
2654             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2655             break;
2656 #endif
2657 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2658         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
2659             l2cap_credit_based_send_pdu(channel);
2660             break;
2661 #endif
2662 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2663         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
2664             l2cap_credit_based_send_pdu(channel);
2665             break;
2666 #endif
2667         default:
2668             break;
2669     }
2670 }
2671 
2672 static void l2cap_notify_channel_can_send(void){
2673     bool done = false;
2674     while (!done){
2675         done = true;
2676         btstack_linked_list_iterator_t it;
2677         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2678         while (btstack_linked_list_iterator_has_next(&it)){
2679             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2680             bool ready = l2cap_channel_ready_to_send(channel);
2681             if (!ready) continue;
2682 
2683             // requeue channel for fairness
2684             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2685             btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2686 
2687             // trigger sending
2688             l2cap_channel_trigger_send(channel);
2689 
2690             // exit inner loop as we just broke the iterator, but try again
2691             done = false;
2692             break;
2693         }
2694     }
2695 }
2696 
2697 #ifdef L2CAP_USES_CHANNELS
2698 
2699 uint8_t l2cap_disconnect(uint16_t local_cid){
2700     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2701     if (!channel) {
2702         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2703     }
2704     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2705     l2cap_run();
2706     return ERROR_CODE_SUCCESS;
2707 }
2708 
2709 static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){
2710     // open cannot fail for for incoming connections
2711     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0;
2712 
2713     // check state
2714     switch (channel->state){
2715         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2716         case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2717         case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES:
2718         case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2719         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
2720         case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES:
2721         case L2CAP_STATE_WAIT_CONNECT_RSP:
2722         case L2CAP_STATE_CONFIG:
2723         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
2724         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
2725         case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE:
2726         case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD:
2727             return 1;
2728 
2729         case L2CAP_STATE_OPEN:
2730         case L2CAP_STATE_CLOSED:
2731         case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES:
2732         case L2CAP_STATE_WAIT_DISCONNECT:
2733         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY:
2734         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
2735         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
2736         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2737         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
2738         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
2739         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
2740         case L2CAP_STATE_INVALID:
2741         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2742             return 0;
2743 
2744         default:
2745             // get a "warning" about new states
2746             btstack_assert(false);
2747             return 0;
2748     }
2749 }
2750 #endif
2751 
2752 #ifdef ENABLE_CLASSIC
2753 static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){
2754     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2755         l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2756     } else {
2757         l2cap_handle_channel_closed(channel);
2758     }
2759     l2cap_free_channel_entry(channel);
2760 }
2761 #endif
2762 
2763 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2764 static void l2cap_handle_hci_le_disconnect_event(l2cap_channel_t * channel){
2765     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2766         l2cap_cbm_emit_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2767     } else {
2768         l2cap_emit_channel_closed(channel);
2769     }
2770     l2cap_free_channel_entry(channel);
2771 }
2772 #endif
2773 
2774 #ifdef ENABLE_CLASSIC
2775 static void l2cap_check_classic_timeout(hci_con_handle_t handle){
2776     if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) {
2777         return;
2778     }
2779     if (hci_authentication_active_for_handle(handle)) {
2780         return;
2781     }
2782     bool hci_con_used = false;
2783     btstack_linked_list_iterator_t it;
2784     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2785     while (btstack_linked_list_iterator_has_next(&it)){
2786         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2787         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2788         if (channel->con_handle != handle) continue;
2789         hci_con_used = true;
2790         break;
2791     }
2792     if (hci_con_used) {
2793         return;
2794     }
2795     if (!hci_can_send_command_packet_now()) {
2796         return;
2797     }
2798     hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
2799 }
2800 
2801 static void l2cap_handle_features_complete(hci_con_handle_t handle){
2802     if (hci_remote_features_available(handle) == false){
2803         return;
2804     }
2805     btstack_linked_list_iterator_t it;
2806     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2807     while (btstack_linked_list_iterator_has_next(&it)){
2808         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2809         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2810         if (channel->con_handle != handle) continue;
2811         log_info("remote supported features, channel %p, cid %04x - state %u", channel, channel->local_cid, channel->state);
2812         l2cap_handle_remote_supported_features_received(channel);
2813     }
2814 }
2815 
2816 static void l2cap_handle_security_level_incoming_sufficient(l2cap_channel_t * channel){
2817     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2818     l2cap_emit_incoming_connection(channel);
2819 }
2820 
2821 static void l2cap_handle_security_level(hci_con_handle_t handle, gap_security_level_t actual_level){
2822     log_info("security level update for handle 0x%04x", handle);
2823 
2824     // trigger l2cap information requests
2825     if (actual_level > LEVEL_0){
2826         hci_connection_t * hci_connection = hci_connection_for_handle(handle);
2827         btstack_assert(hci_connection != NULL);
2828         if (hci_connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
2829             hci_connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2830         }
2831     }
2832 
2833     btstack_linked_list_iterator_t it;
2834     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2835     while (btstack_linked_list_iterator_has_next(&it)){
2836         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2837         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2838         if (channel->con_handle != handle) continue;
2839 
2840         gap_security_level_t required_level = channel->required_security_level;
2841 
2842         log_info("channel %p, cid %04x - state %u: actual %u >= required %u?", channel, channel->local_cid, channel->state, actual_level, required_level);
2843 
2844         switch (channel->state){
2845             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2846                 if (actual_level >= required_level){
2847                     l2cap_handle_security_level_incoming_sufficient(channel);
2848                 } else {
2849                     channel->reason = L2CAP_CONNECTION_RESULT_SECURITY_BLOCK;
2850                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2851                 }
2852                 break;
2853 
2854             case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2855                 if (actual_level >= required_level){
2856                     l2cap_ready_to_connect(channel);
2857                 } else {
2858                     // security level insufficient, report error and free channel
2859                     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY);
2860                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t  *) channel);
2861                     l2cap_free_channel_entry(channel);
2862                 }
2863                 break;
2864 
2865             default:
2866                 break;
2867         }
2868     }
2869 }
2870 #endif
2871 
2872 #ifdef L2CAP_USES_CHANNELS
2873 static void l2cap_handle_disconnection_complete(hci_con_handle_t handle){
2874     // collect channels to close
2875     btstack_linked_list_t channels_to_close = NULL;
2876     btstack_linked_list_iterator_t it;
2877     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2878     while (btstack_linked_list_iterator_has_next(&it)) {
2879         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2880         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2881         if (channel->con_handle != handle) continue;
2882         btstack_linked_list_iterator_remove(&it);
2883         btstack_linked_list_add(&channels_to_close, (btstack_linked_item_t *) channel);
2884     }
2885     // send l2cap open failed or closed events for all channels on this handle and free them
2886     btstack_linked_list_iterator_init(&it, &channels_to_close);
2887     while (btstack_linked_list_iterator_has_next(&it)) {
2888         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2889         btstack_linked_list_iterator_remove(&it);
2890         switch(channel->channel_type){
2891 #ifdef ENABLE_CLASSIC
2892             case L2CAP_CHANNEL_TYPE_CLASSIC:
2893                 l2cap_handle_hci_disconnect_event(channel);
2894                 break;
2895 #endif
2896 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2897             case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
2898                 l2cap_handle_hci_le_disconnect_event(channel);
2899                 break;
2900 #endif
2901 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2902             case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
2903                 switch (channel->state) {
2904                     case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST:
2905                     case L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE:
2906                         // emit open failed if disconnected before connection complete
2907                         l2cap_ecbm_emit_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2908                         break;
2909                     case L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST:
2910                     case L2CAP_STATE_WAIT_ENHANCED_RENEGOTIATION_RESPONSE:
2911                         // emit reconfigure failure - result = 0xffff
2912                         l2cap_ecbm_emit_reconfigure_complete(channel, 0xffff);
2913                         break;
2914                     default:
2915                         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
2916                         break;
2917                 }
2918                 l2cap_free_channel_entry(channel);
2919                 break;
2920 #endif
2921             default:
2922                 break;
2923         }
2924     }
2925 }
2926 #endif
2927 
2928 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
2929 
2930     UNUSED(packet_type); // ok: registered with hci_event_callback_registration
2931     UNUSED(cid);         // ok: there is no channel
2932     UNUSED(size);        // ok: fixed format events read from HCI buffer
2933 
2934 #ifdef ENABLE_CLASSIC
2935     bd_addr_t address;
2936     gap_security_level_t security_level;
2937 #endif
2938 #ifdef L2CAP_USES_CHANNELS
2939     hci_con_handle_t handle;
2940 #endif
2941 
2942     switch(hci_event_packet_get_type(packet)){
2943 
2944         // Notify channel packet handler if they can send now
2945         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2946         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
2947         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
2948             l2cap_call_notify_channel_in_run = true;
2949             break;
2950 
2951         case HCI_EVENT_COMMAND_STATUS:
2952 #ifdef ENABLE_CLASSIC
2953             // check command status for create connection for errors
2954             if (hci_event_command_status_get_command_opcode(packet) == HCI_OPCODE_HCI_CREATE_CONNECTION){
2955                 // cache outgoing address and reset
2956                 (void)memcpy(address, l2cap_outgoing_classic_addr, 6);
2957                 memset(l2cap_outgoing_classic_addr, 0, 6);
2958                 // error => outgoing connection failed
2959                 uint8_t status = hci_event_command_status_get_status(packet);
2960                 if (status){
2961                     l2cap_handle_connection_failed_for_addr(address, status);
2962                 }
2963             }
2964 #endif
2965             l2cap_run();    // try sending signaling packets first
2966             break;
2967 
2968 #ifdef ENABLE_CLASSIC
2969         // handle connection complete events
2970         case HCI_EVENT_CONNECTION_COMPLETE:
2971             reverse_bd_addr(&packet[5], address);
2972             if (packet[2] == 0){
2973                 handle = little_endian_read_16(packet, 3);
2974                 l2cap_handle_connection_success_for_addr(address, handle);
2975             } else {
2976                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
2977             }
2978             break;
2979 
2980         // handle successful create connection cancel command
2981         case HCI_EVENT_COMMAND_COMPLETE:
2982             if (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_CREATE_CONNECTION_CANCEL) {
2983                 if (packet[5] == 0){
2984                     reverse_bd_addr(&packet[6], address);
2985                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
2986                     l2cap_handle_connection_failed_for_addr(address, 0x16);
2987                 }
2988             }
2989             l2cap_run();    // try sending signaling packets first
2990             break;
2991 #endif
2992 
2993 #ifdef L2CAP_USES_CHANNELS
2994         // handle disconnection complete events
2995         case HCI_EVENT_DISCONNECTION_COMPLETE:
2996             handle = little_endian_read_16(packet, 3);
2997             l2cap_handle_disconnection_complete(handle);
2998             break;
2999 #endif
3000 
3001         // HCI Connection Timeouts
3002 #ifdef ENABLE_CLASSIC
3003         case L2CAP_EVENT_TIMEOUT_CHECK:
3004             handle = little_endian_read_16(packet, 2);
3005             l2cap_check_classic_timeout(handle);
3006             break;
3007 
3008         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
3009         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
3010             handle = little_endian_read_16(packet, 3);
3011             l2cap_handle_features_complete(handle);
3012             break;
3013 
3014         case GAP_EVENT_SECURITY_LEVEL:
3015             handle = little_endian_read_16(packet, 2);
3016             security_level = (gap_security_level_t) packet[4];
3017             l2cap_handle_security_level(handle, security_level);
3018             break;
3019 #endif
3020         default:
3021             break;
3022     }
3023 
3024     l2cap_run();
3025 }
3026 
3027 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t cid, uint16_t data){
3028     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indicates the connection was refused."
3029     if (l2cap_signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
3030         l2cap_signaling_responses[l2cap_signaling_responses_pending].handle = handle;
3031         l2cap_signaling_responses[l2cap_signaling_responses_pending].code = code;
3032         l2cap_signaling_responses[l2cap_signaling_responses_pending].sig_id = sig_id;
3033         l2cap_signaling_responses[l2cap_signaling_responses_pending].cid = cid;
3034         l2cap_signaling_responses[l2cap_signaling_responses_pending].data = data;
3035         l2cap_signaling_responses_pending++;
3036         l2cap_run();
3037     }
3038 }
3039 
3040 #ifdef ENABLE_CLASSIC
3041 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
3042     switch (channel->state){
3043         case L2CAP_STATE_CONFIG:
3044         case L2CAP_STATE_OPEN:
3045         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
3046         case L2CAP_STATE_WAIT_DISCONNECT:
3047             break;
3048         default:
3049             // ignore in other states
3050             return;
3051     }
3052 
3053     channel->remote_sig_id = identifier;
3054     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
3055     l2cap_run();
3056 }
3057 
3058 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
3059 
3060     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
3061     l2cap_service_t *service = l2cap_get_service(psm);
3062     if (!service) {
3063         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CONNECTION_RESULT_PSM_NOT_SUPPORTED);
3064         return;
3065     }
3066 
3067     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
3068     if (!hci_connection) {
3069         //
3070         log_error("no hci_connection for handle %u", handle);
3071         return;
3072     }
3073 
3074     // alloc structure
3075     gap_security_level_t required_level = service->required_security_level;
3076     if (gap_get_secure_connections_only_mode() && (required_level != LEVEL_0)){
3077         required_level = LEVEL_4;
3078     }
3079     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, hci_connection->address, BD_ADDR_TYPE_ACL,
3080     psm, service->mtu, required_level);
3081     if (!channel){
3082         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE);
3083         return;
3084     }
3085 
3086     channel->con_handle = handle;
3087     channel->remote_cid = source_cid;
3088     channel->remote_sig_id = sig_id;
3089 
3090     // limit local mtu to max acl packet length - l2cap header
3091     if (channel->local_mtu > l2cap_max_mtu()) {
3092         channel->local_mtu = l2cap_max_mtu();
3093     }
3094 
3095     // set initial state
3096     channel->state =     L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
3097     channel->state_var = L2CAP_CHANNEL_STATE_VAR_INCOMING;
3098 
3099     // add to connections list
3100     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
3101 
3102     //
3103     if (required_level > LEVEL_0){
3104         // send conn resp pending if remote supported features have not been received yet
3105         if (hci_remote_features_available(handle)) {
3106             l2cap_handle_remote_supported_features_received(channel);
3107         } else {
3108             channel->state_var |= L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND;
3109             hci_remote_features_query(handle);
3110         }
3111     } else {
3112         l2cap_handle_security_level_incoming_sufficient(channel);
3113     }
3114 }
3115 
3116 void l2cap_accept_connection(uint16_t local_cid){
3117     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
3118     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3119     if (!channel) {
3120         log_error("accept called but local_cid 0x%x not found", local_cid);
3121         return;
3122     }
3123 
3124 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3125     // configure L2CAP Basic mode
3126     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
3127 #endif
3128 
3129     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
3130 
3131     // process
3132     l2cap_run();
3133 }
3134 
3135 void l2cap_decline_connection(uint16_t local_cid){
3136     log_info("decline local_cid 0x%x", local_cid);
3137     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
3138     if (!channel) {
3139         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
3140         return;
3141     }
3142     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
3143     channel->reason = L2CAP_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE;
3144     l2cap_run();
3145 }
3146 
3147 // @pre command len is valid, see check in l2cap_signaling_handler_channel
3148 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
3149 
3150 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3151     uint8_t use_fcs = 1;
3152 #endif
3153 
3154     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
3155 
3156     uint16_t flags = little_endian_read_16(command, 6);
3157     if (flags & 1) {
3158         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
3159     }
3160 
3161     // accept the other's configuration options
3162     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3163     uint16_t pos     = 8;
3164     while (pos < end_pos){
3165         uint8_t option_hint = command[pos] >> 7;
3166         uint8_t option_type = command[pos] & 0x7f;
3167         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
3168         pos++;
3169         uint8_t length = command[pos++];
3170         // MTU { type(8): 1, len(8):2, MTU(16) }
3171         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) && (length == 2)){
3172             channel->remote_mtu = little_endian_read_16(command, pos);
3173             log_info("Remote MTU %u", channel->remote_mtu);
3174             if (channel->remote_mtu > l2cap_max_mtu()){
3175                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
3176                 channel->remote_mtu = l2cap_max_mtu();
3177             }
3178             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
3179         }
3180         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
3181         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT) && (length == 2)){
3182             channel->flush_timeout = little_endian_read_16(command, pos);
3183             log_info("Flush timeout: %u ms", channel->flush_timeout);
3184         }
3185 
3186 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3187         // Retransmission and Flow Control Option
3188         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
3189             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
3190             switch(channel->mode){
3191                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
3192                     // Store remote config
3193                     channel->remote_tx_window_size = command[pos+1];
3194                     channel->remote_max_transmit   = command[pos+2];
3195                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
3196                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
3197                     {
3198                         uint16_t remote_mps = little_endian_read_16(command, pos + 7);
3199                         // optimize our tx buffer configuration based on actual remote mps if remote mps is smaller than planned
3200                         if (remote_mps < channel->remote_mps){
3201                             // get current tx storage
3202                             uint16_t num_bytes_per_tx_buffer_before = sizeof(l2cap_ertm_tx_packet_state_t) + channel->remote_mps;
3203                             uint16_t tx_storage = channel->num_tx_buffers * num_bytes_per_tx_buffer_before;
3204 
3205                             channel->remote_mps = remote_mps;
3206                             uint16_t num_bytes_per_tx_buffer_now = sizeof(l2cap_ertm_tx_packet_state_t) + channel->remote_mps;
3207                             channel->num_tx_buffers = tx_storage / num_bytes_per_tx_buffer_now;
3208                             uint32_t total_storage = (sizeof(l2cap_ertm_rx_packet_state_t) + channel->local_mps) * channel->num_rx_buffers + tx_storage + channel->local_mtu;
3209                             l2cap_ertm_setup_buffers(channel, (uint8_t *) channel->rx_packets_state, total_storage);
3210                         }
3211                         // limit remote mtu by our tx buffers. Include 2 bytes SDU Length
3212                         uint16_t effective_mtu = channel->remote_mps * channel->num_tx_buffers - 2;
3213                         channel->remote_mtu    = btstack_min( effective_mtu, channel->remote_mtu);
3214                     }
3215                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
3216                         channel->remote_tx_window_size,
3217                         channel->remote_max_transmit,
3218                         channel->remote_retransmission_timeout_ms,
3219                         channel->remote_monitor_timeout_ms,
3220                         channel->remote_mps);
3221                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
3222                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3223                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3224                     } else {
3225                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
3226                     }
3227                     break;
3228                 case L2CAP_CHANNEL_MODE_BASIC:
3229                     switch (mode){
3230                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
3231                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
3232                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
3233                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3234                             }
3235                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
3236                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
3237                             break;
3238                         default: // case L2CAP_CHANNEL_MODE_BASIC:
3239                             // TODO store and evaluate configuration
3240                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
3241                             break;
3242                     }
3243                     break;
3244                 default:
3245                     break;
3246             }
3247         }
3248         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
3249             use_fcs = command[pos];
3250         }
3251 #endif
3252         // check for unknown options
3253         if ((option_hint == 0) && ((option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) || (option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE))){
3254             log_info("l2cap cid %u, unknown option 0x%02x", channel->local_cid, option_type);
3255             channel->unknown_option = option_type;
3256             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
3257         }
3258         pos += length;
3259     }
3260 
3261 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3262         // "FCS" has precedence over "No FCS"
3263         uint8_t update = channel->fcs_option || use_fcs;
3264         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
3265         channel->fcs_option = update;
3266         // If ERTM mandatory, but remote didn't send Retransmission and Flowcontrol options -> disconnect
3267         if (((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM) == 0) & (channel->ertm_mandatory)){
3268             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3269         }
3270 #endif
3271 }
3272 
3273 // @pre command len is valid, see check in l2cap_signaling_handler_channel
3274 static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
3275     log_info("l2cap_signaling_handle_configure_response");
3276 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3277     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3278     uint16_t pos     = 10;
3279     while (pos < end_pos){
3280         uint8_t option_hint = command[pos] >> 7;
3281         uint8_t option_type = command[pos] & 0x7f;
3282         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
3283         pos++;
3284         uint8_t length = command[pos++];
3285 
3286         // Retransmission and Flow Control Option
3287         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
3288             switch (channel->mode){
3289                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
3290                     if (channel->ertm_mandatory){
3291                         // ??
3292                     } else {
3293                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
3294                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
3295                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3296                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3297                         }
3298                     }
3299                     break;
3300                 case L2CAP_CHANNEL_MODE_BASIC:
3301                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
3302                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
3303                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3304                     }
3305                     break;
3306                 default:
3307                     break;
3308             }
3309         }
3310 
3311         // check for unknown options
3312         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
3313             log_info("l2cap cid %u, unknown option 0x%02x", channel->local_cid, option_type);
3314             channel->unknown_option = option_type;
3315             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
3316         }
3317 
3318         pos += length;
3319     }
3320 #else
3321     UNUSED(channel);  // ok: no code
3322     UNUSED(result);   // ok: no code
3323     UNUSED(command);  // ok: no code
3324 #endif
3325 }
3326 
3327 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
3328     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
3329     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
3330     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
3331     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
3332     if (channel->state == L2CAP_STATE_OPEN) return 0;
3333     return 1;
3334 }
3335 
3336 
3337 // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
3338 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
3339 
3340     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3341     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
3342     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3343     uint16_t result = 0;
3344 
3345     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
3346 
3347     // handle DISCONNECT REQUESTS seperately
3348     if (code == DISCONNECTION_REQUEST){
3349         l2cap_handle_disconnect_request(channel, identifier);
3350         return;
3351     }
3352 
3353     // @STATEMACHINE(l2cap)
3354     switch (channel->state) {
3355 
3356         case L2CAP_STATE_WAIT_CONNECT_RSP:
3357             switch (code){
3358                 case CONNECTION_RESPONSE:
3359                     if (cmd_len < 8){
3360                         // command imcomplete
3361                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3362                         break;
3363                     }
3364                     l2cap_stop_rtx(channel);
3365                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3366                     switch (result) {
3367                         case 0:
3368                             // successful connection
3369                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3370                             channel->state = L2CAP_STATE_CONFIG;
3371                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
3372                             break;
3373                         case 1:
3374                             // connection pending. get some coffee, but start the ERTX
3375                             l2cap_start_ertx(channel);
3376                             break;
3377                         default:
3378                             // channel closed
3379                             channel->state = L2CAP_STATE_CLOSED;
3380                             // map l2cap connection response result to BTstack status enumeration
3381                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
3382 
3383                             // drop link key if security block
3384                             if ((L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result) == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
3385                                 gap_drop_link_key_for_bd_addr(channel->address);
3386                             }
3387 
3388                             // discard channel
3389                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3390                             l2cap_free_channel_entry(channel);
3391                             break;
3392                     }
3393                     break;
3394 
3395                 default:
3396                     //@TODO: implement other signaling packets
3397                     break;
3398             }
3399             break;
3400 
3401         case L2CAP_STATE_CONFIG:
3402             switch (code) {
3403                 case CONFIGURE_REQUEST:
3404                     if (cmd_len < 4){
3405                         // command incomplete
3406                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3407                         break;
3408                     }
3409                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
3410                     l2cap_signaling_handle_configure_request(channel, command);
3411                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
3412                         // only done if continuation not set
3413                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
3414                     }
3415                     break;
3416                 case CONFIGURE_RESPONSE:
3417                     if (cmd_len < 6){
3418                         // command incomplete
3419                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3420                         break;
3421                     }
3422                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3423                     l2cap_stop_rtx(channel);
3424                     l2cap_signaling_handle_configure_response(channel, result, command);
3425                     switch (result){
3426                         case 0: // success
3427                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
3428                             break;
3429                         case 4: // pending
3430                             l2cap_start_ertx(channel);
3431                             break;
3432                         default:
3433 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3434                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
3435                                 // remote does not offer ertm but it's required
3436                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3437                                 break;
3438                             }
3439 #endif
3440                             // retry on negative result
3441                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
3442                             break;
3443                     }
3444                     break;
3445                 default:
3446                     break;
3447             }
3448             if (l2cap_channel_ready_for_open(channel)){
3449 
3450 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3451                 // assert that packet can be stored in fragment buffers in ertm
3452                 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3453                     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
3454                     uint16_t usable_mtu = channel->num_tx_buffers == 1 ? effective_mps : channel->num_tx_buffers * effective_mps - 2;
3455                     if (usable_mtu < channel->remote_mtu){
3456                         log_info("Remote MTU %u > max storable ERTM packet, only using MTU = %u", channel->remote_mtu, usable_mtu);
3457                         channel->remote_mtu = usable_mtu;
3458                     }
3459                 }
3460 #endif
3461                 // for open:
3462                 channel->state = L2CAP_STATE_OPEN;
3463                 l2cap_emit_channel_opened(channel, 0);
3464             }
3465             break;
3466 
3467         case L2CAP_STATE_WAIT_DISCONNECT:
3468             switch (code) {
3469                 case DISCONNECTION_RESPONSE:
3470                     l2cap_finalize_channel_close(channel);
3471                     break;
3472                 default:
3473                     //@TODO: implement other signaling packets
3474                     break;
3475             }
3476             break;
3477 
3478         case L2CAP_STATE_CLOSED:
3479             // @TODO handle incoming requests
3480             break;
3481 
3482         case L2CAP_STATE_OPEN:
3483             //@TODO: implement other signaling packets, e.g. re-configure
3484             break;
3485         default:
3486             break;
3487     }
3488     // log_info("new state %u", channel->state);
3489 }
3490 
3491 #ifdef ENABLE_CLASSIC
3492 static void l2cap_handle_information_request_complete(hci_connection_t * connection){
3493 
3494     connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
3495 
3496     // emit event
3497     uint8_t event[8];
3498     event[0] = L2CAP_EVENT_INFORMATION_RESPONSE;
3499     event[1] = sizeof(event) - 2;
3500     little_endian_store_16(event, 2, connection->con_handle);
3501     little_endian_store_16(event, 4, connection->l2cap_state.extended_feature_mask);
3502     little_endian_store_16(event, 6, connection->l2cap_state.fixed_channels_supported);
3503     l2cap_emit_event(event, sizeof(event));
3504 
3505     // trigger connection request
3506     btstack_linked_list_iterator_t it;
3507     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3508     while (btstack_linked_list_iterator_has_next(&it)){
3509         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3510         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3511         if (channel->con_handle != connection->con_handle) continue;
3512 
3513         // incoming connection: information request was triggered after user has accepted connection,
3514         // now: verify channel configuration, esp. if ertm will be mandatory
3515         if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
3516             // default: continue
3517             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
3518 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3519             if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
3520                 // ERTM not possible, select basic mode and release buffer
3521                 channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3522                 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3523 
3524                 // bail if ERTM is mandatory
3525                 if (channel->ertm_mandatory){
3526                     // We chose 'no resources available' for "ERTM mandatory but you don't even know ERTM exists"
3527                     log_info("ERTM mandatory -> reject connection");
3528                     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
3529                     channel->reason = L2CAP_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE;
3530                 }  else {
3531                     log_info("ERTM not supported by remote -> use Basic mode");
3532                 }
3533             }
3534 #endif
3535             continue;
3536         }
3537 
3538         // outgoing connection: information request is triggered before connection request
3539         if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
3540 
3541 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3542             // if ERTM was requested, but is not listed in extended feature mask:
3543             if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
3544 
3545                 if (channel->ertm_mandatory){
3546                     // bail if ERTM is mandatory
3547                     channel->state = L2CAP_STATE_CLOSED;
3548                     // map l2cap connection response result to BTstack status enumeration
3549                     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
3550                     // discard channel
3551                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3552                     l2cap_free_channel_entry(channel);
3553                     continue;
3554 
3555                 } else {
3556                     // fallback to Basic mode
3557                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3558                     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3559                 }
3560             }
3561 #endif
3562 
3563             // respond to connection request
3564             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
3565             continue;
3566         }
3567     }
3568 }
3569 #endif
3570 
3571 // @pre command len is valid, see check in l2cap_acl_classic_handler
3572 static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
3573 
3574     hci_connection_t * connection;
3575     btstack_linked_list_iterator_t it;
3576 
3577     // get code, signal identifier and command len
3578     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3579     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
3580     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3581 
3582     // general commands without an assigned channel
3583     switch(code) {
3584 
3585         case CONNECTION_REQUEST:
3586             if (cmd_len == 4){
3587                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3588                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3589                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
3590             } else {
3591                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3592             }
3593             return;
3594 
3595         case ECHO_REQUEST:
3596             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
3597             return;
3598 
3599         case INFORMATION_REQUEST:
3600             if (cmd_len == 2) {
3601                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3602                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
3603                 return;
3604             }
3605             break;
3606 
3607         case INFORMATION_RESPONSE:
3608             connection = hci_connection_for_handle(handle);
3609             if (!connection) return;
3610             switch (connection->l2cap_state.information_state){
3611                 case L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE:
3612                     // get extended features from response if valid
3613                     if (cmd_len >= 6) {
3614                         uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3615                         uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3616                         if (result == 0 && info_type == L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) {
3617                             connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3618                         }
3619                         log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
3620                         if ((connection->l2cap_state.extended_feature_mask & 0x80) != 0){
3621                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_FIXED_CHANNELS_REQUEST;
3622                         } else {
3623                             // information request complete
3624                             l2cap_handle_information_request_complete(connection);
3625                         }
3626                     }
3627                     break;
3628                 case L2CAP_INFORMATION_STATE_W4_FIXED_CHANNELS_RESPONSE:
3629                     if (cmd_len >= 12) {
3630                         uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3631                         uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3632                         if (result == 0 && info_type == L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED) {
3633                             connection->l2cap_state.fixed_channels_supported = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3634                         }
3635                         log_info("fixed channels mask 0x%02x", connection->l2cap_state.fixed_channels_supported);
3636                         // information request complete
3637                         l2cap_handle_information_request_complete(connection);
3638                     }
3639                     break;
3640                 default:
3641                     break;
3642             }
3643             return;
3644 
3645 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
3646         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
3647         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
3648         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
3649         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
3650             l2cap_ecbm_signaling_handler_dispatch(handle, L2CAP_CID_SIGNALING, command, sig_id);
3651             return;
3652         case L2CAP_FLOW_CONTROL_CREDIT_INDICATION:
3653             // return if valid
3654             if (l2cap_credit_based_handle_credit_indication(handle, command, cmd_len)) return;
3655             break;
3656 
3657         case COMMAND_REJECT:
3658             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3659             while (btstack_linked_list_iterator_has_next(&it)) {
3660                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3661                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3662                 if (channel->con_handle != handle) continue;
3663                 if (channel->local_sig_id != sig_id) continue;
3664                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE) continue;
3665 
3666                 // open failed
3667                 channel->state = L2CAP_STATE_CLOSED;
3668                 l2cap_ecbm_emit_channel_opened(channel,
3669                                                ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES);
3670                 // drop failed channel
3671                 btstack_linked_list_iterator_remove(&it);
3672                 l2cap_free_channel_entry(channel);
3673             }
3674             break;
3675 #endif
3676 
3677         default:
3678             break;
3679     }
3680 
3681     // Get potential destination CID
3682     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3683 
3684     // Find channel for this sig_id and connection handle
3685     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3686     while (btstack_linked_list_iterator_has_next(&it)){
3687         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3688         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3689         if (channel->con_handle != handle) continue;
3690         if (code & 1) {
3691             // match odd commands (responses) by previous signaling identifier
3692             if (channel->local_sig_id == sig_id) {
3693                 l2cap_signaling_handler_channel(channel, command);
3694                 return;
3695             }
3696         } else {
3697             // match even commands (requests) by local channel id
3698             if (channel->local_cid == dest_cid) {
3699                 l2cap_signaling_handler_channel(channel, command);
3700                 return;
3701             }
3702         }
3703     }
3704 
3705     // send command reject
3706     l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3707 }
3708 #endif
3709 
3710 #ifdef L2CAP_USES_CHANNELS
3711 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3712     btstack_linked_list_iterator_t it;
3713     btstack_linked_list_iterator_init(&it, services);
3714     while (btstack_linked_list_iterator_has_next(&it)){
3715         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
3716         if ( service->psm == psm){
3717             return service;
3718         };
3719     }
3720     return NULL;
3721 }
3722 #endif
3723 
3724 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
3725 
3726 static uint8_t l2cap_ecbm_setup_channels(btstack_linked_list_t * channels,
3727                                          btstack_packet_handler_t packet_handler, uint8_t num_channels,
3728                                          hci_connection_t * connection, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
3729     uint8_t i;
3730     uint8_t status = ERROR_CODE_SUCCESS;
3731     for (i=0;i<num_channels;i++){
3732         l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_ECBM, connection->address, connection->address_type, psm, mtu, security_level);
3733         if (!channel) {
3734             status = BTSTACK_MEMORY_ALLOC_FAILED;
3735             break;
3736         }
3737         channel->con_handle = connection->con_handle;
3738         btstack_linked_list_add_tail(channels, (btstack_linked_item_t *) channel);
3739     }
3740 
3741     // free channels if not all allocated
3742     if (status != ERROR_CODE_SUCCESS){
3743         while (true) {
3744             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_pop(channels);
3745             if (channel == NULL) break;
3746             l2cap_free_channel_entry(channel);
3747         }
3748     }
3749 
3750     return status;
3751 }
3752 
3753 static inline l2cap_service_t * l2cap_ecbm_get_service(uint16_t spsm){
3754     return l2cap_get_service_internal(&l2cap_enhanced_services, spsm);
3755 }
3756 
3757 static inline uint8_t l2cap_ecbm_status_for_result(uint16_t result) {
3758     switch (result) {
3759         case L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS:
3760             return ERROR_CODE_SUCCESS;
3761         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_SPSM_NOT_SUPPORTED:
3762             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_PSM;
3763         case L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INSUFFICIENT_RESOURCES_AVAILABLE:
3764             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_RESOURCES;
3765         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHENTICATION:
3766         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHORIZATION:
3767         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_ENCYRPTION_KEY_SIZE_TOO_SHORT:
3768         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_ENCRYPTION:
3769             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY;
3770         default:
3771             // invalid Source CID, Source CID already allocated, unacceptable parameters
3772             return L2CAP_CONNECTION_RESPONSE_UNKNOWN_ERROR;
3773     }
3774 }
3775 
3776 static int l2cap_ecbm_signaling_handler_dispatch(hci_con_handle_t handle, uint16_t signaling_cid, uint8_t *command,
3777                                                  uint8_t sig_id) {
3778 
3779     hci_connection_t *connection;
3780     btstack_linked_list_iterator_t it;
3781     l2cap_service_t *service;
3782     uint16_t spsm;
3783     uint8_t num_channels;
3784     uint16_t num_channels_and_signaling_cid;
3785     uint8_t i;
3786     uint16_t new_mtu;
3787     uint16_t new_mps;
3788     uint16_t initial_credits;
3789     uint16_t result;
3790     uint8_t status;
3791 
3792     uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3793     uint16_t len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3794     log_info("enhanced dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
3795 
3796     switch (code) {
3797         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
3798             // check size
3799             if (len < 10u) return 0u;
3800 
3801             // get hci connection, bail if not found (must not happen)
3802             connection = hci_connection_for_handle(handle);
3803             btstack_assert(connection != NULL);
3804 
3805             // get num channels to establish
3806             num_channels = (len - 8) / sizeof(uint16_t);
3807 
3808             // combine signaling cid and number channels for l2cap_register_signaling_response
3809             num_channels_and_signaling_cid = (num_channels << 8) | signaling_cid;
3810 
3811             // check if service registered
3812             spsm = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3813             service = l2cap_ecbm_get_service(spsm);
3814 
3815             if (service) {
3816 
3817                 uint16_t remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3818                 uint16_t remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3819                 uint16_t credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
3820 
3821                 // param: check remote mtu
3822                 if (service->mtu > remote_mtu) {
3823                     l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3824                                                       num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INVALID_PARAMETERS);
3825                     return 1;
3826                 }
3827 
3828                 // security: check authentication
3829                 if (service->required_security_level >= LEVEL_3) {
3830                     if (!gap_authenticated(handle)) {
3831                         l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3832                                                           num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHENTICATION);
3833                         return 1;
3834                     }
3835                 }
3836 
3837                 // security: check encryption
3838                 // L2CAP.TS.p31 does not check for Connection refused - insufficient encryption which might be send for no encryption
3839                 if (service->required_security_level >= LEVEL_2) {
3840                     if (gap_encryption_key_size(handle) < 16) {
3841                         l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3842                                                           num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_ENCYRPTION_KEY_SIZE_TOO_SHORT);
3843                         return 1;
3844                     }
3845                 }
3846 
3847                 // report the last result code != 0
3848                 result = 0;
3849                 // store one of the local cids for the event
3850                 uint16_t a_local_cid = 0;
3851                 for (i = 0; i < num_channels; i++) {
3852 
3853                     // check source cids
3854                     uint16_t source_cid = little_endian_read_16(command, 12 + (i * 2));
3855                     if (source_cid < 0x40u) {
3856                         result = L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INVALID_SOURCE_CID;
3857                         continue;
3858                     }
3859 
3860                     // go through list of channels for this ACL connection and check if we get a match
3861                     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3862                     bool source_cid_allocated = false;
3863                     while (btstack_linked_list_iterator_has_next(&it)) {
3864                         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3865                         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3866                         if (channel->con_handle != handle) continue;
3867                         if (channel->remote_cid != source_cid) continue;
3868                         source_cid_allocated = true;
3869                         break;
3870                     }
3871                     if (source_cid_allocated) {
3872                         result = 0x00a;
3873                         continue;
3874                     }
3875 
3876                     // setup channel
3877                     l2cap_channel_t *channel = l2cap_create_channel_entry(service->packet_handler,
3878                                                                           L2CAP_CHANNEL_TYPE_CHANNEL_ECBM,
3879                                                                           connection->address,
3880                                                                           connection->address_type, spsm,
3881                                                                           service->mtu,
3882                                                                           service->required_security_level);
3883 
3884                     if (channel == NULL) {
3885                         // Some connections refused – insufficient resources available
3886                         result = 0x004;
3887                         continue;
3888                     }
3889 
3890                     // setup state
3891                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
3892                     channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
3893                     channel->con_handle = connection->con_handle;
3894                     channel->remote_sig_id = sig_id;
3895                     channel->remote_cid = source_cid;
3896                     channel->remote_mtu = remote_mtu;
3897                     channel->remote_mps = remote_mps;
3898                     channel->credits_outgoing = credits_outgoing;
3899                     channel->cid_index = i;
3900                     channel->num_cids = num_channels;
3901 
3902                     // if more than one error, we can report any of them
3903                     channel->reason = result;
3904 
3905                     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
3906 
3907                     a_local_cid = channel->local_cid;
3908                 }
3909 
3910                 // if no channels have been created, all have been refused, and we can respond right away
3911                 if (a_local_cid == 0) {
3912                     l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3913                                                       num_channels_and_signaling_cid, result);
3914                     return 1;
3915                 }
3916 
3917                 // emit incoming data connection event
3918                 uint8_t event[16];
3919                 event[0] = L2CAP_EVENT_ECBM_INCOMING_CONNECTION;
3920                 event[1] = sizeof(event) - 2;
3921                 event[2] = connection->address_type;
3922                 reverse_bd_addr(connection->address, &event[3]);
3923                 little_endian_store_16(event, 9, connection->con_handle);
3924                 little_endian_store_16(event, 11, spsm);
3925                 event[13] = num_channels;
3926                 little_endian_store_16(event, 14, a_local_cid);
3927                 hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
3928                 (*service->packet_handler)(HCI_EVENT_PACKET, a_local_cid, event, sizeof(event));
3929 
3930             } else {
3931                 l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3932                                                   num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_SPSM_NOT_SUPPORTED);
3933             }
3934             return 1;
3935 
3936         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
3937             // check size
3938             if (len < 10u) return 0u;
3939 
3940             // get hci connection, ignore if not found
3941             connection = hci_connection_for_handle(handle);
3942             if (connection == NULL) return 0;
3943 
3944             // get channel config: mtu, mps, initial credits, result
3945             new_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3946             new_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3947             initial_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3948             result = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
3949             status = l2cap_ecbm_status_for_result(result);
3950 
3951             // get num channels to modify
3952             num_channels = (len - 8) / sizeof(uint16_t);
3953             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3954             while (btstack_linked_list_iterator_has_next(&it)) {
3955                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3956                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3957                 if (channel->con_handle != handle) continue;
3958                 if (channel->local_sig_id != sig_id) continue;
3959                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE) continue;
3960                 if (channel->cid_index < num_channels) {
3961                     uint16_t remote_cid = little_endian_read_16(command, 12 + channel->cid_index * sizeof(uint16_t));
3962                     if (remote_cid != 0) {
3963                         channel->state = L2CAP_STATE_OPEN;
3964                         channel->remote_cid = remote_cid;
3965                         channel->remote_mtu = new_mtu;
3966                         channel->remote_mps = new_mps;
3967                         channel->credits_outgoing = initial_credits;
3968                         l2cap_ecbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
3969                         continue;
3970                     }
3971                 }
3972                 // open failed
3973                 l2cap_ecbm_emit_channel_opened(channel, status);
3974                 // drop failed channel
3975                 btstack_linked_list_iterator_remove(&it);
3976                 btstack_memory_l2cap_channel_free(channel);
3977             }
3978             return 1;
3979 
3980         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
3981             // check minimal size
3982             if (len < 6) return 0u;
3983 
3984             // get hci connection, bail if not found (must not happen)
3985             connection = hci_connection_for_handle(handle);
3986             btstack_assert(connection != NULL);
3987 
3988             // get num channels to modify
3989             num_channels = (len - 4) / sizeof(uint16_t);
3990 
3991             // get new mtu and mps
3992             new_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3993             new_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3994 
3995             // validate request
3996             result = 0;
3997             for (i = 0; i < num_channels; i++) {
3998                 // check cid
3999                 uint16_t remote_cid = little_endian_read_16(command, 8 + (i * sizeof(uint16_t)));
4000                 l2cap_channel_t *channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
4001                 if (channel == NULL) {
4002                     result = L2CAP_ECBM_RECONFIGURE_FAILED_DESTINATION_CID_INVALID;
4003                     break;
4004                 }
4005                 // check MTU is not reduced
4006                 if (channel->remote_mtu > new_mtu) {
4007                     result = L2CAP_ECBM_RECONFIGURE_FAILED_MTU_REDUCTION_NOT_ALLOWED;
4008                     break;
4009                 }
4010                 // check MPS reduction
4011                 if ((num_channels > 1) && (channel->remote_mps > new_mps)) {
4012                     result = L2CAP_ECBM_RECONFIGURE_FAILED_MPS_REDUCTION_MULTIPLE_CHANNELS;
4013                     break;
4014                 }
4015                 // check MPS valid
4016                 if (new_mps < l2cap_enhanced_mps_min) {
4017                     result = L2CAP_ECBM_RECONFIGURE_FAILED_UNACCEPTABLE_PARAMETERS;
4018                     break;
4019                 }
4020             }
4021 
4022             // send reject
4023             if (result != 0) {
4024                 l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST, sig_id, signaling_cid,
4025                                                   result);
4026                 return 1;
4027             }
4028 
4029             // update channels
4030             for (i = 0; i < num_channels; i++) {
4031                 uint16_t remote_cid = little_endian_read_16(command, 8 + (i * sizeof(uint16_t)));
4032                 l2cap_channel_t *channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
4033                 channel->remote_mps = new_mps;
4034                 channel->remote_mtu = new_mtu;
4035                 // emit event
4036                 uint8_t event[8];
4037                 event[0] = L2CAP_EVENT_ECBM_RECONFIGURED;
4038                 event[1] = sizeof(event) - 2;
4039                 little_endian_store_16(event, 2, channel->local_cid);
4040                 little_endian_store_16(event, 4, new_mtu);
4041                 little_endian_store_16(event, 6, new_mps);
4042                 l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
4043             }
4044 
4045             // send accept
4046             l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST, sig_id, signaling_cid, 0);
4047             return 1;
4048 
4049         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
4050             // check size
4051             if (len < 2u) return 0u;
4052 
4053             result = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4054             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4055             while (btstack_linked_list_iterator_has_next(&it)) {
4056                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4057                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4058                 if (channel->con_handle != handle) continue;
4059                 if (channel->local_sig_id != sig_id) continue;
4060                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_RENEGOTIATION_RESPONSE) continue;
4061                 // complete request
4062                 if (result == 0) {
4063                     channel->receive_sdu_buffer = channel->renegotiate_sdu_buffer;
4064                     channel->local_mtu = channel->renegotiate_mtu;
4065                 }
4066                 channel->state = L2CAP_STATE_OPEN;
4067                 // emit event
4068                 l2cap_ecbm_emit_reconfigure_complete(channel, result);
4069             }
4070             break;
4071 
4072         default:
4073             btstack_unreachable();
4074             break;
4075     }
4076     return 0;
4077 }
4078 
4079 #endif
4080 
4081 #ifdef ENABLE_BLE
4082 
4083 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
4084     uint8_t event[6];
4085     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
4086     event[1] = 4;
4087     little_endian_store_16(event, 2, con_handle);
4088     little_endian_store_16(event, 4, result);
4089     l2cap_emit_event(event, sizeof(event));
4090 }
4091 
4092 // @return valid
4093 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
4094     hci_connection_t * connection;
4095     uint16_t result;
4096     uint8_t  event[12];
4097 
4098 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4099     l2cap_channel_t * channel;
4100     btstack_linked_list_iterator_t it;
4101 #endif
4102 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4103     uint16_t local_cid;
4104     uint16_t le_psm;
4105     l2cap_service_t * service;
4106     uint16_t source_cid;
4107 #endif
4108 
4109     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
4110     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
4111     log_info("le dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
4112 
4113     switch (code){
4114 
4115         case CONNECTION_PARAMETER_UPDATE_REQUEST:
4116             // check size
4117             if (len < 8u) return 0u;
4118             connection = hci_connection_for_handle(handle);
4119             if (connection != NULL){
4120                 if (connection->role != HCI_ROLE_MASTER){
4121                     // reject command without notifying upper layer when not in master role
4122                     return 0;
4123                 }
4124                 le_connection_parameter_range_t existing_range;
4125                 gap_get_connection_parameter_range(&existing_range);
4126                 uint16_t le_conn_interval_min   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
4127                 uint16_t le_conn_interval_max   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
4128                 uint16_t le_conn_latency        = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
4129                 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
4130 
4131                 int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
4132                 if (update_parameter){
4133                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
4134                     connection->le_conn_interval_min = le_conn_interval_min;
4135                     connection->le_conn_interval_max = le_conn_interval_max;
4136                     connection->le_conn_latency = le_conn_latency;
4137                     connection->le_supervision_timeout = le_supervision_timeout;
4138                 } else {
4139                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
4140                 }
4141                 connection->le_con_param_update_identifier = sig_id;
4142             }
4143 
4144             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
4145             event[1] = 8;
4146             little_endian_store_16(event, 2, handle);
4147             (void)memcpy(&event[4], &command[4], 8);
4148             l2cap_emit_event(event, sizeof(event));
4149             break;
4150 
4151         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
4152             // check size
4153             if (len < 2u) return 0u;
4154             result = little_endian_read_16(command, 4);
4155             l2cap_emit_connection_parameter_update_response(handle, result);
4156             break;
4157 
4158 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
4159         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
4160         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
4161         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
4162         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
4163             return l2cap_ecbm_signaling_handler_dispatch(handle, L2CAP_CID_SIGNALING_LE, command, sig_id);
4164 #endif
4165 
4166 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4167         case COMMAND_REJECT:
4168             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4169             while (btstack_linked_list_iterator_has_next(&it)){
4170                 channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4171                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4172                 if (channel->con_handle   != handle) continue;
4173                 if (channel->local_sig_id != sig_id) continue;
4174 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4175                 // if received while waiting for le connection response, assume legacy device
4176                 if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
4177                     channel->state = L2CAP_STATE_CLOSED;
4178                     // no official value for this, use: Connection refused – LE_PSM not supported
4179                     l2cap_cbm_emit_channel_opened(channel, L2CAP_CBM_CONNECTION_RESULT_SPSM_NOT_SUPPORTED);
4180 
4181                     // discard channel
4182                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4183                     l2cap_free_channel_entry(channel);
4184                     continue;
4185                 }
4186 #endif
4187 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
4188                 // if received while waiting for le connection response, assume legacy device
4189                 if (channel->state == L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE){
4190                     channel->state = L2CAP_STATE_CLOSED;
4191                     // treat as SPSM not supported
4192                     l2cap_ecbm_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_PSM);
4193 
4194                     // discard channel
4195                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4196                     l2cap_free_channel_entry(channel);
4197                     continue;
4198                 }
4199 #endif
4200             }
4201             break;
4202 #endif
4203 
4204 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4205         case LE_CREDIT_BASED_CONNECTION_REQUEST:
4206             // check size
4207             if (len < 10u) return 0u;
4208 
4209             // get hci connection, bail if not found (must not happen)
4210             connection = hci_connection_for_handle(handle);
4211             if (!connection) return 0;
4212 
4213             // check if service registered
4214             le_psm  = little_endian_read_16(command, 4);
4215             service = l2cap_cbm_get_service(le_psm);
4216             source_cid = little_endian_read_16(command, 6);
4217 
4218             if (service){
4219                 if (source_cid < 0x40u){
4220                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INVALID_SOURCE_CID);
4221                     return 1;
4222                 }
4223 
4224                 // go through list of channels for this ACL connection and check if we get a match
4225                 btstack_linked_list_iterator_init(&it, &l2cap_channels);
4226                 while (btstack_linked_list_iterator_has_next(&it)){
4227                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4228                     if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
4229                     if (a_channel->con_handle != handle) continue;
4230                     if (a_channel->remote_cid != source_cid) continue;
4231                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_SOURCE_CID_ALREADY_ALLOCATED);
4232                     return 1;
4233                 }
4234 
4235                 // security: check encryption
4236                 if (service->required_security_level >= LEVEL_2){
4237                     if (gap_encryption_key_size(handle) == 0){
4238                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_ENCRYPTION);
4239                         return 1;
4240                     }
4241                     // anything less than 16 byte key size is insufficient
4242                     if (gap_encryption_key_size(handle) < 16){
4243                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_ENCYRPTION_KEY_SIZE_TOO_SHORT);
4244                         return 1;
4245                     }
4246                 }
4247 
4248                 // security: check authentication
4249                 if (service->required_security_level >= LEVEL_3){
4250                     if (!gap_authenticated(handle)){
4251                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHENTICATION);
4252                         return 1;
4253                     }
4254                 }
4255 
4256                 // security: check authorization
4257                 if (service->required_security_level >= LEVEL_4){
4258                     if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
4259                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHORIZATION);
4260                         return 1;
4261                     }
4262                 }
4263 
4264                 // allocate channel
4265                 channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_CBM, connection->address,
4266                                                      BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
4267                 if (!channel){
4268                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE);
4269                     return 1;
4270                 }
4271 
4272                 channel->con_handle = handle;
4273                 channel->remote_cid = source_cid;
4274                 channel->remote_sig_id = sig_id;
4275                 channel->remote_mtu = little_endian_read_16(command, 8);
4276                 channel->remote_mps = little_endian_read_16(command, 10);
4277                 channel->credits_outgoing = little_endian_read_16(command, 12);
4278 
4279                 // set initial state
4280                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
4281                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
4282 
4283                 // add to connections list
4284                 btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
4285 
4286                 // post connection request event
4287                 l2cap_cbm_emit_incoming_connection(channel);
4288 
4289             } else {
4290                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_SPSM_NOT_SUPPORTED);
4291             }
4292             break;
4293 
4294         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
4295             // check size
4296             if (len < 10u) return 0u;
4297 
4298             // Find channel for this sig_id and connection handle
4299             channel = NULL;
4300             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4301             while (btstack_linked_list_iterator_has_next(&it)){
4302                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4303                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
4304                 if (a_channel->con_handle   != handle) continue;
4305                 if (a_channel->local_sig_id != sig_id) continue;
4306                 channel = a_channel;
4307                 break;
4308             }
4309             if (!channel) break;
4310 
4311             // cid + 0
4312             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
4313             if (result){
4314                 channel->state = L2CAP_STATE_CLOSED;
4315                 uint8_t status = l2cap_cbm_status_for_result(result);
4316                 l2cap_cbm_emit_channel_opened(channel, status);
4317 
4318                 // discard channel
4319                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4320                 l2cap_free_channel_entry(channel);
4321                 break;
4322             }
4323 
4324             // success
4325             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4326             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
4327             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
4328             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
4329             channel->state = L2CAP_STATE_OPEN;
4330             l2cap_cbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
4331             break;
4332 #endif
4333 
4334 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4335         case L2CAP_FLOW_CONTROL_CREDIT_INDICATION:
4336             return l2cap_credit_based_handle_credit_indication(handle, command, len) ? 1 : 0;
4337 
4338         case DISCONNECTION_REQUEST:
4339 
4340             // check size
4341             if (len < 4u) return 0u;
4342 
4343             // find channel
4344             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4345             channel = l2cap_get_channel_for_local_cid_and_handle(local_cid, handle);
4346             if (!channel) {
4347                 log_error("credit: no channel for cid 0x%02x", local_cid);
4348                 break;
4349             }
4350             channel->remote_sig_id = sig_id;
4351             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
4352             break;
4353 
4354         case DISCONNECTION_RESPONSE:
4355             // check size
4356             if (len < 4u) return 0u;
4357 
4358             // find channel
4359             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4360             channel = l2cap_get_channel_for_local_cid_and_handle(local_cid, handle);
4361             if (!channel) break;
4362             if (channel->local_sig_id == sig_id) {
4363                 if (channel->state == L2CAP_STATE_WAIT_DISCONNECT){
4364                     l2cap_finalize_channel_close(channel);
4365                 }
4366             }
4367             break;
4368 #endif
4369 
4370         default:
4371             // command unknown -> reject command
4372             return 0;
4373     }
4374     return 1;
4375 }
4376 #endif
4377 
4378 #ifdef ENABLE_CLASSIC
4379 static void l2cap_acl_classic_handler_for_channel(l2cap_channel_t * l2cap_channel, uint8_t * packet, uint16_t size){
4380 
4381     // forward data only in OPEN state
4382     if (l2cap_channel->state != L2CAP_STATE_OPEN) return;
4383 
4384 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4385     if (l2cap_channel->channel_type == L2CAP_CHANNEL_TYPE_CHANNEL_ECBM){
4386         l2cap_credit_based_handle_pdu(l2cap_channel, packet, size);
4387         return;
4388     }
4389 #endif
4390 
4391 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
4392     if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
4393 
4394         int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
4395 
4396         // assert control + FCS fields are inside
4397         if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) return;
4398 
4399         if (l2cap_channel->fcs_option){
4400             // verify FCS (required if one side requested it)
4401             uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
4402             uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
4403 
4404 #ifdef L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL
4405             // simulate fcs error
4406             static int counter = 0;
4407             if (++counter == L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL) {
4408                 log_info("Simulate fcs error");
4409                 fcs_calculated++;
4410                 counter = 0;
4411             }
4412 #endif
4413 
4414             if (fcs_calculated == fcs_packet){
4415                 log_info("Packet FCS 0x%04x verified", fcs_packet);
4416             } else {
4417                 log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
4418                 // ERTM State Machine in Bluetooth Spec does not handle 'I-Frame with invalid FCS'
4419                 return;
4420             }
4421         }
4422 
4423         // switch on packet type
4424         uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
4425         uint8_t  req_seq = (control >> 8) & 0x3f;
4426         int final = (control >> 7) & 0x01;
4427         if (control & 1){
4428             // S-Frame
4429             int poll  = (control >> 4) & 0x01;
4430             l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
4431             log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
4432             l2cap_ertm_tx_packet_state_t * tx_state;
4433             switch (s){
4434                 case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
4435                     log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
4436                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4437                     if (poll && final){
4438                         // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
4439                         log_error("P=F=1 in S-Frame");
4440                         break;
4441                     }
4442                     if (poll){
4443                         // check if we did request selective retransmission before <==> we have stored SDU segments
4444                         int i;
4445                         int num_stored_out_of_order_packets = 0;
4446                         for (i=0;i<l2cap_channel->num_rx_buffers;i++){
4447                             int index = l2cap_channel->rx_store_index + i;
4448                             if (index >= l2cap_channel->num_rx_buffers){
4449                                 index -= l2cap_channel->num_rx_buffers;
4450                             }
4451                             l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
4452                             if (!rx_state->valid) continue;
4453                             num_stored_out_of_order_packets++;
4454                         }
4455                         if (num_stored_out_of_order_packets){
4456                             l2cap_channel->send_supervisor_frame_selective_reject = 1;
4457                         } else {
4458                             l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
4459                         }
4460                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
4461                     }
4462                     if (final){
4463                         // Stop-MonitorTimer
4464                         l2cap_ertm_stop_monitor_timer(l2cap_channel);
4465                         // If UnackedFrames > 0 then Start-RetransTimer
4466                         if (l2cap_channel->unacked_frames){
4467                             l2cap_ertm_start_retransmission_timer(l2cap_channel);
4468                         }
4469                         // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
4470                         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4471                     }
4472                     break;
4473                 case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
4474                     log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
4475                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4476                     // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
4477                     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4478                     break;
4479                 case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
4480                     log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
4481                     break;
4482                 case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
4483                     log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
4484                     if (poll){
4485                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4486                     }
4487                     // find requested i-frame
4488                     tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
4489                     if (tx_state){
4490                         log_info("Retransmission for tx_seq %u requested", req_seq);
4491                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
4492                         tx_state->retransmission_requested = 1;
4493                         l2cap_channel->srej_active = 1;
4494                     }
4495                     break;
4496                 default:
4497                     break;
4498             }
4499         } else {
4500             // I-Frame
4501             // get control
4502             l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
4503             uint8_t tx_seq = (control >> 1) & 0x3f;
4504             log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
4505             log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
4506             log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
4507             l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4508             if (final){
4509                 // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
4510                 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4511             }
4512 
4513             // get SDU
4514             const uint8_t * payload_data = &packet[COMPLETE_L2CAP_HEADER+2];
4515             uint16_t        payload_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
4516 
4517             // assert SDU size is smaller or equal to our buffers
4518             uint16_t max_payload_size = 0;
4519             switch (sar){
4520                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
4521                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
4522                     // SDU Length + MPS
4523                     max_payload_size = l2cap_channel->local_mps + 2;
4524                     break;
4525                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
4526                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
4527                     max_payload_size = l2cap_channel->local_mps;
4528                     break;
4529                 default:
4530                     btstack_assert(false);
4531                     break;
4532             }
4533             if (payload_len > max_payload_size){
4534                 log_info("payload len %u > max payload %u -> drop packet", payload_len, max_payload_size);
4535                 return;
4536             }
4537 
4538             // check ordering
4539             if (l2cap_channel->expected_tx_seq == tx_seq){
4540                 log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
4541                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
4542                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
4543 
4544                 // process SDU
4545                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, payload_data, payload_len);
4546 
4547                 // process stored segments
4548                 while (true){
4549                     int index = l2cap_channel->rx_store_index;
4550                     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
4551                     if (!rx_state->valid) break;
4552 
4553                     log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
4554                     l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
4555                     l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
4556 
4557                     rx_state->valid = 0;
4558                     l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
4559 
4560                     // update rx store index
4561                     index++;
4562                     if (index >= l2cap_channel->num_rx_buffers){
4563                         index = 0;
4564                     }
4565                     l2cap_channel->rx_store_index = index;
4566                 }
4567 
4568                 //
4569                 l2cap_channel->send_supervisor_frame_receiver_ready = 1;
4570 
4571             } else {
4572                 int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
4573                 if (delta < 2){
4574                     // store segment
4575                     l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, payload_data, payload_len);
4576 
4577                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
4578                     l2cap_channel->send_supervisor_frame_selective_reject = 1;
4579                 } else {
4580                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
4581                     l2cap_channel->send_supervisor_frame_reject = 1;
4582                 }
4583             }
4584         }
4585         return;
4586     }
4587 #endif
4588 
4589     // check size
4590     uint16_t payload_size = size - COMPLETE_L2CAP_HEADER;
4591     if (l2cap_channel->local_mtu < payload_size) return;
4592 
4593     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], payload_size);
4594 }
4595 #endif
4596 
4597 static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
4598 #ifdef ENABLE_CLASSIC
4599     l2cap_channel_t * l2cap_channel;
4600     l2cap_fixed_channel_t * l2cap_fixed_channel;
4601 
4602     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
4603     uint8_t  broadcast_flag = READ_ACL_FLAGS(packet) >> 2;
4604     switch (channel_id) {
4605 
4606         case L2CAP_CID_SIGNALING: {
4607             if (broadcast_flag != 0) break;
4608             uint32_t command_offset = 8;
4609             while ((command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET) < size) {
4610                 // assert signaling command is fully inside packet
4611                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
4612                 uint32_t next_command_offset = command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
4613                 if (next_command_offset > size){
4614                     log_error("l2cap signaling command len invalid -> drop");
4615                     break;
4616                 }
4617                 // handle signaling command
4618                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
4619                 // go to next command
4620                 command_offset = next_command_offset;
4621             }
4622             break;
4623         }
4624 
4625         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
4626             if (broadcast_flag == 0) break;
4627             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL);
4628             if (!l2cap_fixed_channel) break;
4629             if (!l2cap_fixed_channel->packet_handler) break;
4630             (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4631             break;
4632 
4633 #ifdef ENABLE_BLE
4634         case L2CAP_CID_BR_EDR_SECURITY_MANAGER:
4635             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
4636             if ((l2cap_fixed_channel == NULL) || (l2cap_fixed_channel->packet_handler == NULL)){
4637                 // Pairing Failed
4638                 l2cap_register_signaling_response(handle, (uint8_t) SM_PAIRING_FAILED, 0, L2CAP_CID_BR_EDR_SECURITY_MANAGER, SM_REASON_PAIRING_NOT_SUPPORTED);
4639             } else {
4640                 (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4641             }
4642             break;
4643 #endif
4644 
4645         default:
4646             if (broadcast_flag != 0) break;
4647             // Find channel for this channel_id and connection handle
4648             l2cap_channel = l2cap_get_channel_for_local_cid_and_handle(channel_id, handle);
4649             if (l2cap_channel != NULL){
4650                 l2cap_acl_classic_handler_for_channel(l2cap_channel, packet, size);
4651             }
4652             break;
4653     }
4654 #else
4655     UNUSED(handle); // ok: no code
4656     UNUSED(packet); // ok: no code
4657     UNUSED(size);   // ok: no code
4658 #endif
4659 }
4660 
4661 static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
4662 #ifdef ENABLE_BLE
4663 
4664     l2cap_fixed_channel_t * l2cap_fixed_channel;
4665 
4666 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4667     l2cap_channel_t * l2cap_channel;
4668 #endif
4669     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
4670     switch (channel_id) {
4671 
4672         case L2CAP_CID_SIGNALING_LE: {
4673             uint8_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
4674             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
4675             if ((COMPLETE_L2CAP_HEADER + 4u + len) > size) break;
4676             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
4677             if (!valid){
4678                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
4679             }
4680             break;
4681         }
4682 
4683         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
4684             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL);
4685             if (!l2cap_fixed_channel) break;
4686             if (!l2cap_fixed_channel->packet_handler) break;
4687             (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4688             break;
4689 
4690         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
4691             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
4692             if ((l2cap_fixed_channel == NULL) || (l2cap_fixed_channel->packet_handler == NULL)){
4693                 // Pairing Failed
4694                 l2cap_register_signaling_response(handle, (uint8_t) SM_PAIRING_FAILED, 0, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, SM_REASON_PAIRING_NOT_SUPPORTED);
4695             } else {
4696                 (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4697             }
4698             break;
4699 
4700         default:
4701 
4702 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4703             l2cap_channel = l2cap_get_channel_for_local_cid_and_handle(channel_id, handle);
4704             if (l2cap_channel != NULL) {
4705                 l2cap_credit_based_handle_pdu(l2cap_channel, packet, size);
4706             }
4707 #endif
4708             break;
4709     }
4710 #else
4711     UNUSED(handle); // ok: no code
4712     UNUSED(packet); // ok: no code
4713     UNUSED(size);   // ok: no code
4714 #endif
4715 }
4716 
4717 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
4718     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
4719     UNUSED(channel);        // ok: there is no channel
4720 
4721     // Assert full L2CAP header present
4722     if (size < COMPLETE_L2CAP_HEADER) return;
4723 
4724     // Dispatch to Classic or LE handler (SCO packets are not dispatched to L2CAP)
4725     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
4726     hci_connection_t *conn = hci_connection_for_handle(handle);
4727     if (!conn) return;
4728     if (conn->address_type == BD_ADDR_TYPE_ACL){
4729         l2cap_acl_classic_handler(handle, packet, size);
4730     } else {
4731         l2cap_acl_le_handler(handle, packet, size);
4732     }
4733 
4734     l2cap_run();
4735 }
4736 
4737 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
4738 void l2cap_register_fixed_channel(btstack_packet_handler_t packet_handler, uint16_t channel_id) {
4739     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
4740     if (!channel) return;
4741     channel->packet_handler = packet_handler;
4742 }
4743 
4744 #ifdef L2CAP_USES_CHANNELS
4745 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
4746 void l2cap_finalize_channel_close(l2cap_channel_t * channel){
4747     channel->state = L2CAP_STATE_CLOSED;
4748     l2cap_handle_channel_closed(channel);
4749     // discard channel
4750     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4751     l2cap_free_channel_entry(channel);
4752 }
4753 #endif
4754 
4755 #ifdef ENABLE_CLASSIC
4756 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
4757     return l2cap_get_service_internal(&l2cap_services, psm);
4758 }
4759 
4760 static void l2cap_update_minimal_security_level(void){
4761     // update minimal service security level
4762     gap_security_level_t minimal_level = LEVEL_1;
4763     btstack_linked_list_iterator_t it;
4764     btstack_linked_list_iterator_init(&it, &l2cap_services);
4765     while (btstack_linked_list_iterator_has_next(&it)){
4766         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
4767         if (service->required_security_level > minimal_level){
4768             minimal_level = service->required_security_level;
4769         };
4770     }
4771     gap_set_minimal_service_security_level(minimal_level);
4772 }
4773 
4774 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
4775 
4776     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
4777 
4778     // check for alread registered psm
4779     l2cap_service_t *service = l2cap_get_service(psm);
4780     if (service) {
4781         log_error("register: PSM %u already registered", psm);
4782         return L2CAP_SERVICE_ALREADY_REGISTERED;
4783     }
4784 
4785     // alloc structure
4786     service = btstack_memory_l2cap_service_get();
4787     if (!service) {
4788         log_error("register: no memory for l2cap_service_t");
4789         return BTSTACK_MEMORY_ALLOC_FAILED;
4790     }
4791 
4792     // fill in
4793     service->psm = psm;
4794     service->mtu = mtu;
4795     service->packet_handler = service_packet_handler;
4796     service->required_security_level = security_level;
4797 
4798     // add to services list
4799     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
4800 
4801     l2cap_update_minimal_security_level();
4802 
4803 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
4804     // enable page scan
4805     gap_connectable_control(1);
4806 #endif
4807 
4808 
4809     return ERROR_CODE_SUCCESS;
4810 }
4811 
4812 uint8_t l2cap_unregister_service(uint16_t psm){
4813 
4814     log_info("unregister psm 0x%x", psm);
4815 
4816     l2cap_service_t *service = l2cap_get_service(psm);
4817     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
4818     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
4819     btstack_memory_l2cap_service_free(service);
4820 
4821     l2cap_update_minimal_security_level();
4822 
4823 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
4824     // disable page scan when no services registered
4825     if (btstack_linked_list_empty(&l2cap_services)) {
4826         gap_connectable_control(0);
4827     }
4828 #endif
4829 
4830     return ERROR_CODE_SUCCESS;
4831 }
4832 #endif
4833 
4834 
4835 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4836 
4837 static void l2cap_credit_based_send_pdu(l2cap_channel_t *channel) {
4838     btstack_assert(channel != NULL);
4839     btstack_assert(channel->send_sdu_buffer != NULL);
4840     btstack_assert(channel->credits_outgoing > 0);
4841 
4842     // send part of SDU
4843     hci_reserve_packet_buffer();
4844     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
4845     uint8_t *l2cap_payload = acl_buffer + 8;
4846     uint16_t pos = 0;
4847     if (!channel->send_sdu_pos) {
4848         // store SDU len
4849         channel->send_sdu_pos += 2u;
4850         little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
4851         pos += 2u;
4852     }
4853     uint16_t payload_size = btstack_min(channel->send_sdu_len + 2u - channel->send_sdu_pos, channel->remote_mps - pos);
4854     log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size,
4855              channel->credits_outgoing);
4856     (void) memcpy(&l2cap_payload[pos],
4857                   &channel->send_sdu_buffer[channel->send_sdu_pos - 2u],
4858                   payload_size); // -2 for virtual SDU len
4859     pos += payload_size;
4860     channel->send_sdu_pos += payload_size;
4861     l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
4862 
4863     channel->credits_outgoing--;
4864 
4865     // update state (mark SDU as done) before calling hci_send_acl_packet_buffer (trigger l2cap_le_send_pdu again)
4866     bool done = channel->send_sdu_pos >= (channel->send_sdu_len + 2u);
4867     if (done) {
4868         channel->send_sdu_buffer = NULL;
4869     }
4870 
4871     hci_send_acl_packet_buffer(8u + pos);
4872 
4873     if (done) {
4874         // send done event
4875         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_PACKET_SENT);
4876         // inform about can send now
4877         l2cap_credit_based_notify_channel_can_send(channel);
4878     }
4879 }
4880 
4881 static uint8_t l2cap_credit_based_send_data(l2cap_channel_t * channel, const uint8_t * data, uint16_t size){
4882 
4883     if (size > channel->remote_mtu){
4884         log_error("l2cap send, cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
4885         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
4886     }
4887 
4888     if (channel->send_sdu_buffer){
4889         log_info("l2cap send, cid 0x%02x, cannot send", channel->local_cid);
4890         return BTSTACK_ACL_BUFFERS_FULL;
4891     }
4892 
4893     channel->send_sdu_buffer = data;
4894     channel->send_sdu_len    = size;
4895     channel->send_sdu_pos    = 0;
4896 
4897     l2cap_notify_channel_can_send();
4898     return ERROR_CODE_SUCCESS;
4899 }
4900 
4901 static uint8_t l2cap_credit_based_provide_credits(uint16_t local_cid, uint16_t credits){
4902     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4903     if (!channel) {
4904         log_error("le credits no channel for cid 0x%02x", local_cid);
4905         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4906     }
4907 
4908     // check state
4909     if (channel->state != L2CAP_STATE_OPEN){
4910         log_error("le credits but channel 0x%02x not open yet", local_cid);
4911     }
4912 
4913     // ignore if set to automatic credits
4914     if (channel->automatic_credits) return ERROR_CODE_SUCCESS;
4915 
4916     // assert incoming credits + credits <= 0xffff
4917     uint32_t total_credits = channel->credits_incoming;
4918     total_credits += channel->new_credits_incoming;
4919     total_credits += credits;
4920     if (total_credits > 0xffffu){
4921         log_error("le credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
4922                   channel->new_credits_incoming, credits);
4923     }
4924 
4925     // set credits_granted
4926     channel->new_credits_incoming += credits;
4927 
4928     // go
4929     l2cap_run();
4930     return ERROR_CODE_SUCCESS;
4931 }
4932 
4933 static void l2cap_credit_based_send_credits(l2cap_channel_t *channel) {
4934     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
4935     channel->local_sig_id = l2cap_next_sig_id();
4936     uint16_t new_credits = channel->new_credits_incoming;
4937     channel->new_credits_incoming = 0;
4938     channel->credits_incoming += new_credits;
4939     uint16_t signaling_cid = channel->address_type == BD_ADDR_TYPE_ACL ? L2CAP_CID_SIGNALING : L2CAP_CID_SIGNALING_LE;
4940     l2cap_send_general_signaling_packet(channel->con_handle, signaling_cid, L2CAP_FLOW_CONTROL_CREDIT_INDICATION, channel->local_sig_id, channel->local_cid, new_credits);
4941 }
4942 
4943 // @return valid
4944 static bool l2cap_credit_based_handle_credit_indication(hci_con_handle_t handle, const uint8_t * command, uint16_t len){
4945     // check size
4946     if (len < 4u) return false;
4947 
4948     // find channel
4949     uint16_t remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4950     l2cap_channel_t * channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
4951     if (!channel) {
4952         log_error("credit: no channel for handle 0x%04x/cid 0x%02x", handle, remote_cid);
4953         return true;
4954     }
4955     uint16_t new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
4956     uint16_t credits_before = channel->credits_outgoing;
4957     channel->credits_outgoing += new_credits;
4958     // check for credit overrun
4959     if (credits_before > channel->credits_outgoing) {
4960         log_error("credit: new credits caused overrrun for cid 0x%02x, disconnecting", channel->local_cid);
4961         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4962         return true;
4963     }
4964     log_info("credit: %u credits for 0x%02x, now %u", new_credits, channel->local_cid, channel->credits_outgoing);
4965     l2cap_call_notify_channel_in_run = true;
4966     return true;
4967 }
4968 
4969 static void l2cap_credit_based_handle_pdu(l2cap_channel_t * l2cap_channel, const uint8_t * packet, uint16_t size){
4970     // ignore empty packets
4971     if (size == COMPLETE_L2CAP_HEADER) return;
4972 
4973     // credit counting
4974     if (l2cap_channel->credits_incoming == 0u){
4975         log_info("(e)CBM: packet received but no incoming credits");
4976         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4977         return;
4978     }
4979     l2cap_channel->credits_incoming--;
4980 
4981     // automatic credits
4982     if ((l2cap_channel->credits_incoming < L2CAP_CREDIT_BASED_FLOW_CONTROL_MODE_AUTOMATIC_CREDITS_WATERMARK) && l2cap_channel->automatic_credits){
4983         l2cap_channel->new_credits_incoming = L2CAP_CREDIT_BASED_FLOW_CONTROL_MODE_AUTOMATIC_CREDITS_INCREMENT;
4984     }
4985 
4986     // first fragment
4987     uint16_t pos = 0;
4988     if (!l2cap_channel->receive_sdu_len){
4989         if (size < (COMPLETE_L2CAP_HEADER + 2)) return;
4990         uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
4991         if(sdu_len > l2cap_channel->local_mtu) return;   // SDU would be larger than our buffer
4992         l2cap_channel->receive_sdu_len = sdu_len;
4993         l2cap_channel->receive_sdu_pos = 0;
4994         pos  += 2u;
4995         size -= 2u;
4996     }
4997     uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
4998     uint16_t remaining_space = l2cap_channel->local_mtu - l2cap_channel->receive_sdu_pos;
4999     if (fragment_size > remaining_space) return;         // SDU would cause buffer overrun
5000     (void)memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos],
5001                  &packet[COMPLETE_L2CAP_HEADER + pos],
5002                  fragment_size);
5003     l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
5004     // done?
5005     log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
5006     if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
5007         l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
5008         l2cap_channel->receive_sdu_len = 0;
5009     }
5010 }
5011 
5012 static void l2cap_credit_based_notify_channel_can_send(l2cap_channel_t *channel){
5013     if (!channel->waiting_for_can_send_now) return;
5014     if (channel->send_sdu_buffer) return;
5015     channel->waiting_for_can_send_now = 0;
5016     log_debug("le can send now, local_cid 0x%x", channel->local_cid);
5017     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CAN_SEND_NOW);
5018 }
5019 #endif
5020 
5021 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
5022 // 1BH2222
5023 static void l2cap_cbm_emit_incoming_connection(l2cap_channel_t *channel) {
5024     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",
5025              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
5026     uint8_t event[19];
5027     event[0] = L2CAP_EVENT_CBM_INCOMING_CONNECTION;
5028     event[1] = sizeof(event) - 2u;
5029     event[2] = channel->address_type;
5030     reverse_bd_addr(channel->address, &event[3]);
5031     little_endian_store_16(event,  9, channel->con_handle);
5032     little_endian_store_16(event, 11, channel->psm);
5033     little_endian_store_16(event, 13, channel->local_cid);
5034     little_endian_store_16(event, 15, channel->remote_cid);
5035     little_endian_store_16(event, 17, channel->remote_mtu);
5036     hci_dump_packet( HCI_EVENT_PACKET, 1, event, sizeof(event));
5037     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
5038 }
5039 // 11BH22222
5040 static void l2cap_cbm_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
5041     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",
5042              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
5043              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
5044     uint8_t event[23];
5045     event[0] = L2CAP_EVENT_CBM_CHANNEL_OPENED;
5046     event[1] = sizeof(event) - 2u;
5047     event[2] = status;
5048     event[3] = channel->address_type;
5049     reverse_bd_addr(channel->address, &event[4]);
5050     little_endian_store_16(event, 10, channel->con_handle);
5051     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
5052     little_endian_store_16(event, 13, channel->psm);
5053     little_endian_store_16(event, 15, channel->local_cid);
5054     little_endian_store_16(event, 17, channel->remote_cid);
5055     little_endian_store_16(event, 19, channel->local_mtu);
5056     little_endian_store_16(event, 21, channel->remote_mtu);
5057     hci_dump_packet( HCI_EVENT_PACKET, 1, event, sizeof(event));
5058     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
5059 }
5060 
5061 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
5062 void l2cap_cbm_finialize_channel_close(l2cap_channel_t * channel){
5063     channel->state = L2CAP_STATE_CLOSED;
5064     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
5065     // discard channel
5066     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
5067     l2cap_free_channel_entry(channel);
5068 }
5069 
5070 static inline l2cap_service_t * l2cap_cbm_get_service(uint16_t le_psm){
5071     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
5072 }
5073 
5074 uint8_t l2cap_cbm_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
5075 
5076     log_info("l2cap_cbm_register_service psm 0x%x", psm);
5077 
5078     // check for alread registered psm
5079     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5080     if (service) {
5081         return L2CAP_SERVICE_ALREADY_REGISTERED;
5082     }
5083 
5084     // alloc structure
5085     service = btstack_memory_l2cap_service_get();
5086     if (!service) {
5087         log_error("register: no memory for l2cap_service_t");
5088         return BTSTACK_MEMORY_ALLOC_FAILED;
5089     }
5090 
5091     // fill in
5092     service->psm = psm;
5093     service->mtu = 0;
5094     service->packet_handler = packet_handler;
5095     service->required_security_level = security_level;
5096 
5097     // add to services list
5098     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
5099 
5100     // done
5101     return ERROR_CODE_SUCCESS;
5102 }
5103 
5104 uint8_t l2cap_cbm_unregister_service(uint16_t psm) {
5105     log_info("l2cap_cbm_unregister_service psm 0x%x", psm);
5106     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5107     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
5108 
5109     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
5110     btstack_memory_l2cap_service_free(service);
5111     return ERROR_CODE_SUCCESS;
5112 }
5113 
5114 uint8_t l2cap_cbm_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
5115     // get channel
5116     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5117     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5118 
5119     // validate state
5120     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
5121         return ERROR_CODE_COMMAND_DISALLOWED;
5122     }
5123 
5124     // set state accept connection
5125     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
5126     channel->receive_sdu_buffer = receive_sdu_buffer;
5127     channel->local_mtu = mtu;
5128     channel->new_credits_incoming = initial_credits;
5129     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5130 
5131     // go
5132     l2cap_run();
5133     return ERROR_CODE_SUCCESS;
5134 }
5135 
5136 uint8_t l2cap_cbm_decline_connection(uint16_t local_cid, uint16_t result) {
5137     // get channel
5138     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5139     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5140 
5141     // validate state
5142     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
5143         return ERROR_CODE_COMMAND_DISALLOWED;
5144     }
5145 
5146     // set state decline connection
5147     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
5148     channel->reason = result;
5149     l2cap_run();
5150     return ERROR_CODE_SUCCESS;
5151 }
5152 
5153 static gap_security_level_t l2cap_cbm_security_level_for_connection(hci_con_handle_t con_handle){
5154     uint8_t encryption_key_size = gap_encryption_key_size(con_handle);
5155     if (encryption_key_size == 0) return LEVEL_0;
5156 
5157     bool authenticated = gap_authenticated(con_handle);
5158     if (!authenticated) return LEVEL_2;
5159 
5160     return encryption_key_size == 16 ? LEVEL_4 : LEVEL_3;
5161 }
5162 
5163 // used to handle pairing complete after triggering to increase
5164 static void l2cap_cbm_sm_packet_handler(uint8_t packet_type, uint16_t channel_nr, uint8_t *packet, uint16_t size) {
5165     UNUSED(channel_nr);
5166     UNUSED(size);
5167     UNUSED(packet_type);
5168     btstack_assert(packet_type == HCI_EVENT_PACKET);
5169     if (hci_event_packet_get_type(packet) != SM_EVENT_PAIRING_COMPLETE) return;
5170     hci_con_handle_t con_handle = sm_event_pairing_complete_get_handle(packet);
5171     btstack_linked_list_iterator_t it;
5172     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5173     while (btstack_linked_list_iterator_has_next(&it)) {
5174         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5175         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5176         if (channel->con_handle != con_handle) continue;
5177         if (channel->state != L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE) continue;
5178 
5179         // found channel, check security level
5180         if (l2cap_cbm_security_level_for_connection(con_handle) < channel->required_security_level){
5181             // pairing failed or wasn't good enough, inform user
5182             l2cap_cbm_emit_channel_opened(channel, ERROR_CODE_INSUFFICIENT_SECURITY);
5183             // discard channel
5184             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
5185             l2cap_free_channel_entry(channel);
5186         } else {
5187             // send conn request now
5188             channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5189             l2cap_run();
5190         }
5191     }
5192 }
5193 
5194 uint8_t l2cap_cbm_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5195     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
5196     uint16_t * out_local_cid) {
5197 
5198     static btstack_packet_callback_registration_t sm_event_callback_registration;
5199     static bool sm_callback_registered = false;
5200 
5201     log_info("create, handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
5202 
5203     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5204     if (!connection) {
5205         log_error("no hci_connection for handle 0x%04x", con_handle);
5206         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5207     }
5208 
5209     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_CBM, connection->address, connection->address_type, psm, mtu, security_level);
5210     if (!channel) {
5211         return BTSTACK_MEMORY_ALLOC_FAILED;
5212     }
5213     log_info("created %p", channel);
5214 
5215     // store local_cid
5216     if (out_local_cid){
5217        *out_local_cid = channel->local_cid;
5218     }
5219 
5220     // setup channel entry
5221     channel->con_handle = con_handle;
5222     channel->receive_sdu_buffer = receive_sdu_buffer;
5223     channel->new_credits_incoming = initial_credits;
5224     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5225 
5226     // add to connections list
5227     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
5228 
5229     // check security level
5230     if (l2cap_cbm_security_level_for_connection(con_handle) < channel->required_security_level){
5231         if (!sm_callback_registered){
5232             sm_callback_registered = true;
5233             // lazy registration for SM events
5234             sm_event_callback_registration.callback = &l2cap_cbm_sm_packet_handler;
5235             sm_add_event_handler(&sm_event_callback_registration);
5236         }
5237 
5238         // start pairing
5239         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
5240         sm_request_pairing(con_handle);
5241     } else {
5242         // send conn request right away
5243         channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5244         l2cap_run();
5245     }
5246 
5247     return ERROR_CODE_SUCCESS;
5248 }
5249 
5250 uint8_t l2cap_cbm_provide_credits(uint16_t local_cid, uint16_t credits){
5251     return l2cap_credit_based_provide_credits(local_cid, credits);
5252 }
5253 #endif
5254 
5255 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
5256 
5257 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){
5258 
5259     // check for already registered psm
5260     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5261     if (service) {
5262         return L2CAP_SERVICE_ALREADY_REGISTERED;
5263     }
5264 
5265     // alloc structure
5266     service = btstack_memory_l2cap_service_get();
5267     if (!service) {
5268         log_error("register: no memory for l2cap_service_t");
5269         return BTSTACK_MEMORY_ALLOC_FAILED;
5270     }
5271 
5272     // fill in
5273     service->psm = psm;
5274     service->mtu = min_remote_mtu;
5275     service->packet_handler = packet_handler;
5276     service->required_security_level = security_level;
5277 
5278     // add to services list
5279     btstack_linked_list_add(&l2cap_enhanced_services, (btstack_linked_item_t *) service);
5280 
5281     // done
5282     return ERROR_CODE_SUCCESS;
5283 }
5284 
5285 uint8_t l2cap_ecbm_unregister_service(uint16_t psm) {
5286     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5287     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
5288 
5289     btstack_linked_list_remove(&l2cap_enhanced_services, (btstack_linked_item_t *) service);
5290     btstack_memory_l2cap_service_free(service);
5291     return ERROR_CODE_SUCCESS;
5292 }
5293 
5294 void l2cap_ecbm_mps_set_min(uint16_t mps_min){
5295     l2cap_enhanced_mps_min = mps_min;
5296 }
5297 
5298 void l2cap_ecbm_mps_set_max(uint16_t mps_max){
5299     l2cap_enhanced_mps_max = mps_max;
5300 }
5301 
5302 uint8_t l2cap_ecbm_create_channels(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5303                                        gap_security_level_t security_level,
5304                                        uint16_t psm, uint8_t num_channels, uint16_t initial_credits, uint16_t mtu,
5305                                        uint8_t ** receive_sdu_buffers, uint16_t * out_local_cid){
5306 
5307     log_info("create enhanced, handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
5308 
5309     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5310     if (!connection) {
5311         log_error("no hci_connection for handle 0x%04x", con_handle);
5312         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5313     }
5314 
5315     // setup all channels
5316     btstack_linked_list_t channels = NULL;
5317     uint8_t status = l2cap_ecbm_setup_channels(&channels, packet_handler, num_channels, connection, psm, mtu,
5318                                                security_level);
5319 
5320     // add to connections list and set state + local_sig_id
5321     l2cap_channel_t * channel;
5322     uint8_t i = 0;
5323     uint8_t local_sig_id = l2cap_next_sig_id();
5324     while (true) {
5325         channel = (l2cap_channel_t *) btstack_linked_list_pop(&channels);
5326         if (channel == NULL) break;
5327         channel->state              = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST;
5328         channel->local_sig_id       = local_sig_id;
5329         channel->cid_index = i;
5330         channel->num_cids = num_channels;
5331         channel->credits_incoming   = initial_credits;
5332         channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5333         channel->receive_sdu_buffer = receive_sdu_buffers[i];
5334         // store local_cid
5335         if (out_local_cid){
5336             out_local_cid[i] = channel->local_cid;
5337         }
5338         btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
5339         i++;
5340     }
5341 
5342 #if 0
5343     // check security level
5344     if (l2cap_le_security_level_for_connection(con_handle) < channel->required_security_level){
5345         if (!sm_callback_registered){
5346             sm_callback_registered = true;
5347             // lazy registration for SM events
5348             sm_event_callback_registration.callback = &l2cap_sm_packet_handler;
5349             sm_add_event_handler(&sm_event_callback_registration);
5350         }
5351 
5352         // start pairing
5353         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
5354         sm_request_pairing(con_handle);
5355     } else {
5356         // send conn request right away
5357         channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5358         l2cap_run();
5359     }
5360 #endif
5361 
5362     l2cap_run();
5363 
5364     return status;
5365 }
5366 
5367 uint8_t l2cap_ecbm_accept_channels(uint16_t local_cid, uint8_t num_channels, uint16_t initial_credits,
5368                                             uint16_t receive_buffer_size, uint8_t ** receive_buffers, uint16_t * out_local_cids){
5369 
5370     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5371     if (!channel) {
5372 
5373         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5374     }
5375     //
5376     hci_con_handle_t  con_handle    = channel->con_handle;
5377     uint8_t           local_sig_id  = channel->local_sig_id;
5378     uint8_t           channel_index = 0;
5379     btstack_linked_list_iterator_t it;
5380     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5381     while (btstack_linked_list_iterator_has_next(&it)) {
5382         channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5383         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5384         if (channel->con_handle != con_handle) continue;
5385         if (channel->local_sig_id != local_sig_id) continue;
5386         if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT) continue;
5387 
5388         if (channel_index < num_channels){
5389             // assign buffer and cid
5390             out_local_cids[channel_index] = channel->local_cid;
5391             channel->receive_sdu_buffer = receive_buffers[channel_index];
5392             channel->local_mtu = receive_buffer_size;
5393             channel->credits_incoming   = initial_credits;
5394             channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5395             channel_index++;
5396         } else {
5397             // clear local cid for response packet
5398             channel->local_cid = 0;
5399             channel->reason = L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INSUFFICIENT_RESOURCES_AVAILABLE;
5400         }
5401         // update state
5402         channel->state = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE;
5403     }
5404     l2cap_run();
5405     return ERROR_CODE_SUCCESS;
5406 }
5407 
5408 uint8_t l2cap_ecbm_decline_channels(uint16_t local_cid, uint16_t result){
5409     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5410     if (!channel) {
5411         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5412     }
5413     //
5414     hci_con_handle_t  con_handle    = channel->con_handle;
5415     uint8_t           local_sig_id  = channel->local_sig_id;
5416     btstack_linked_list_iterator_t it;
5417     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5418     while (btstack_linked_list_iterator_has_next(&it)) {
5419         channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5420         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5421         if (channel->con_handle != con_handle) continue;
5422         if (channel->local_sig_id != local_sig_id) continue;
5423         if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT) continue;
5424 
5425         // prepare response
5426         channel->local_cid = 0;
5427         channel->reason = result;
5428         channel->state = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE;
5429     }
5430     l2cap_run();
5431     return ERROR_CODE_SUCCESS;
5432 }
5433 
5434 uint8_t l2cap_ecbm_reconfigure_channels(uint8_t num_cids, uint16_t * local_cids, int16_t receive_buffer_size, uint8_t ** receive_buffers){
5435     btstack_assert(receive_buffers != NULL);
5436     btstack_assert(local_cids != NULL);
5437 
5438     if (num_cids > L2CAP_ECBM_MAX_CID_ARRAY_SIZE){
5439         return ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS;
5440     }
5441 
5442     // check if all cids exist and have the same con handle
5443     uint8_t i;
5444     hci_con_handle_t con_handle = HCI_CON_HANDLE_INVALID;
5445     for (i = 0 ; i < num_cids ; i++){
5446         l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cids[i]);
5447         if (!channel) {
5448             return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5449         }
5450         if (channel->state != L2CAP_STATE_OPEN){
5451             return ERROR_CODE_COMMAND_DISALLOWED;
5452         }
5453         if (con_handle == HCI_CON_HANDLE_INVALID){
5454             con_handle = channel->con_handle;
5455         } else if (con_handle != channel->con_handle){
5456             return ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS;
5457         }
5458     }
5459     // set renegotiation data and state
5460     uint8_t sig_id = l2cap_next_sig_id();
5461     for (i = 0 ; i < num_cids ; i++){
5462         l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cids[i]);
5463         channel->cid_index = i;
5464         channel->num_cids = num_cids;
5465         channel->local_sig_id = sig_id;
5466         channel->renegotiate_mtu = receive_buffer_size;
5467         channel->renegotiate_sdu_buffer = receive_buffers[i];
5468         channel->state = L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST;
5469     }
5470 
5471 
5472     l2cap_run();
5473     return ERROR_CODE_SUCCESS;
5474 }
5475 
5476 uint8_t l2cap_ecbm_provide_credits(uint16_t local_cid, uint16_t credits){
5477     return l2cap_credit_based_provide_credits(local_cid, credits);
5478 }
5479 #endif
5480 
5481 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
5482 // @deprecated - please use l2cap_ertm_create_channel
5483 uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
5484                                   l2cap_ertm_config_t * ertm_contig, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
5485     log_error("deprecated - please use l2cap_ertm_create_channel");
5486     return l2cap_ertm_create_channel(packet_handler, address, psm, ertm_contig, buffer, size, out_local_cid);
5487 };
5488 
5489 // @deprecated - please use l2cap_ertm_accept_connection
5490 uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, l2cap_ertm_config_t * ertm_contig, uint8_t * buffer, uint32_t size){
5491     log_error("deprecated - please use l2cap_ertm_accept_connection");
5492     return l2cap_ertm_accept_connection(local_cid, ertm_contig, buffer, size);
5493 }
5494 #endif
5495 
5496 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
5497 // @deprecated - please use l2cap_cbm_register_service
5498 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
5499     log_error("deprecated - please use l2cap_cbm_register_service");
5500     return l2cap_cbm_register_service(packet_handler, psm, security_level);
5501 }
5502 
5503 // @deprecated - please use l2cap_cbm_unregister_service
5504 uint8_t l2cap_le_unregister_service(uint16_t psm){
5505     log_error("deprecated - please use l2cap_cbm_unregister_service");
5506     return l2cap_cbm_unregister_service(psm);
5507 }
5508 
5509 // @deprecated - please use l2cap_cbm_accept_connection
5510 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
5511     log_error("deprecated - please use l2cap_cbm_accept_connection");
5512     return l2cap_cbm_accept_connection(local_cid, receive_sdu_buffer, mtu, initial_credits);
5513 }
5514 
5515 // @deprecated - please use l2cap_cbm_decline_connection
5516 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
5517     log_error("deprecated - please use l2cap_cbm_decline_connection");
5518     return l2cap_cbm_decline_connection(local_cid, L2CAP_CBM_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE);
5519 }
5520 
5521 // @deprecated - please use l2cap_cbm_create_channel
5522 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5523                                 uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
5524                                 uint16_t * out_local_cid){
5525     log_error("deprecated - please use l2cap_cbm_create_channel");
5526     return l2cap_cbm_create_channel(packet_handler, con_handle, psm, receive_sdu_buffer, mtu, initial_credits, security_level, out_local_cid);
5527 }
5528 
5529 // @deprecated - please use l2cap_cbm_provide_credits
5530 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
5531     log_error("deprecated - please use l2cap_cbm_provide_credits");
5532     return l2cap_cbm_provide_credits(local_cid, credits);
5533 }
5534 
5535 // @deprecated - please use l2cap_can_send_packet_now
5536 bool l2cap_le_can_send_now(uint16_t local_cid){
5537     log_error("deprecated - please use l2cap_can_send_packet_now");
5538     return l2cap_can_send_packet_now(local_cid);
5539 }
5540 
5541 // @deprecated - please use l2cap_request_can_send_now_event
5542 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
5543     log_error("deprecated - please use l2cap_request_can_send_now_event");
5544     return l2cap_request_can_send_now_event(local_cid);
5545 }
5546 
5547 // @deprecated - please use l2cap_cbm_send_data
5548 uint8_t l2cap_le_send_data(uint16_t local_cid, const uint8_t * data, uint16_t size){
5549     log_error("deprecated - please use l2cap_cbm_send_data");
5550     return l2cap_send(local_cid, data, size);
5551 }
5552 
5553 // @deprecated - please use l2cap_disconnect
5554 uint8_t l2cap_le_disconnect(uint16_t local_cid){
5555     log_error("deprecated - please use l2cap_disconnect");
5556     return l2cap_disconnect(local_cid);
5557 }
5558 #endif
5559