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