xref: /btstack/src/l2cap.c (revision 0b695730e4e32c2473488afc2e009cccde6f4238)
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 MATTHIAS
24  * RINGWALD 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_LE_DATA_CHANNELS
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_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK 5
126 #define L2CAP_LE_DATA_CHANNELS_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 #if defined(ENABLE_LE_DATA_CHANNELS) || defined(ENABLE_CLASSIC)
135 #define L2CAP_USES_CHANNELS
136 #endif
137 
138 // prototypes
139 static void l2cap_run(void);
140 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
141 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size );
142 static void l2cap_notify_channel_can_send(void);
143 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel);
144 static uint8_t  l2cap_next_sig_id(void);
145 static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid);
146 #ifdef ENABLE_CLASSIC
147 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel);
148 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel);
149 static void l2cap_finialize_channel_close(l2cap_channel_t *channel);
150 static inline l2cap_service_t * l2cap_get_service(uint16_t psm);
151 static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
152 static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
153 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel);
154 static int  l2cap_channel_ready_for_open(l2cap_channel_t *channel);
155 #endif
156 #ifdef ENABLE_LE_DATA_CHANNELS
157 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status);
158 static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel);
159 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel);
160 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel);
161 static void l2cap_le_finialize_channel_close(l2cap_channel_t *channel);
162 static void l2cap_le_send_pdu(l2cap_channel_t *channel);
163 static inline l2cap_service_t * l2cap_le_get_service(uint16_t psm);
164 #endif
165 #ifdef L2CAP_USES_CHANNELS
166 static uint16_t l2cap_next_local_cid(void);
167 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid);
168 static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code);
169 static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size);
170 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,
171         uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level);
172 static void l2cap_free_channel_entry(l2cap_channel_t * channel);
173 #endif
174 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
175 static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel);
176 static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts);
177 static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts);
178 #endif
179 
180 // l2cap_fixed_channel_t entries
181 #ifdef ENABLE_BLE
182 static l2cap_fixed_channel_t l2cap_fixed_channel_att;
183 static l2cap_fixed_channel_t l2cap_fixed_channel_sm;
184 #endif
185 #ifdef ENABLE_CLASSIC
186 static l2cap_fixed_channel_t l2cap_fixed_channel_connectionless;
187 #endif
188 
189 #ifdef ENABLE_CLASSIC
190 static btstack_linked_list_t l2cap_services;
191 static uint8_t require_security_level2_for_outgoing_sdp;
192 static bd_addr_t l2cap_outgoing_classic_addr;
193 #endif
194 
195 #ifdef ENABLE_LE_DATA_CHANNELS
196 static btstack_linked_list_t l2cap_le_services;
197 #endif
198 
199 // single list of channels for Classic Channels, LE Data Channels, Classic Connectionless, ATT, and SM
200 static btstack_linked_list_t l2cap_channels;
201 #ifdef L2CAP_USES_CHANNELS
202 // next channel id for new connections
203 static uint16_t  local_source_cid  = 0x40;
204 #endif
205 // next signaling sequence number
206 static uint8_t   sig_seq_nr  = 0xff;
207 
208 // used to cache l2cap rejects, echo, and informational requests
209 static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
210 static int signaling_responses_pending;
211 static btstack_packet_callback_registration_t hci_event_callback_registration;
212 
213 #ifdef ENABLE_BLE
214 // only used for connection parameter update events
215 static btstack_packet_handler_t l2cap_event_packet_handler;
216 static uint16_t l2cap_le_custom_max_mtu;
217 #endif
218 
219 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
220 
221 // enable for testing
222 // #define L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL 16
223 
224 /*
225  * CRC lookup table for generator polynom D^16 + D^15 + D^2 + 1
226  */
227 static const uint16_t crc16_table[256] = {
228     0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
229     0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841,
230     0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41,
231     0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040,
232     0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441,
233     0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840,
234     0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40,
235     0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041,
236     0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
237     0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840,
238     0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
239     0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041,
240     0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440,
241     0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841,
242     0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41,
243     0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040,
244 };
245 
246 static uint16_t crc16_calc(uint8_t * data, uint16_t len){
247     uint16_t crc = 0;   // initial value = 0
248     while (len--){
249         crc = (crc >> 8) ^ crc16_table[ (crc ^ ((uint16_t) *data++)) & 0x00FF ];
250     }
251     return crc;
252 }
253 
254 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){
255     return (((uint16_t) sar) << 14) | (req_seq << 8) | (final << 7) | (tx_seq << 1) | 0;
256 }
257 
258 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){
259     return (req_seq << 8) | (final << 7) | (poll << 4) | (((int) supervisory_function) << 2) | 1;
260 }
261 
262 static int l2cap_next_ertm_seq_nr(int seq_nr){
263     return (seq_nr + 1) & 0x3f;
264 }
265 
266 static int l2cap_ertm_can_store_packet_now(l2cap_channel_t * channel){
267     // get num free tx buffers
268     int num_free_tx_buffers = channel->num_tx_buffers - channel->num_stored_tx_frames;
269     // calculate num tx buffers for remote MTU
270     int num_tx_buffers_for_max_remote_mtu;
271     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
272     if (channel->remote_mtu <= effective_mps){
273         // MTU fits into single packet
274         num_tx_buffers_for_max_remote_mtu = 1;
275     } else {
276         // include SDU Length
277         num_tx_buffers_for_max_remote_mtu = (channel->remote_mtu + 2 + (effective_mps - 1)) / effective_mps;
278     }
279     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);
280     return num_tx_buffers_for_max_remote_mtu <= num_free_tx_buffers;
281 }
282 
283 static void l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel_t * l2cap_channel){
284     log_info("Retransmit unacknowleged frames");
285     l2cap_channel->unacked_frames = 0;;
286     l2cap_channel->tx_send_index  = l2cap_channel->tx_read_index;
287 }
288 
289 static void l2cap_ertm_next_tx_write_index(l2cap_channel_t * channel){
290     channel->tx_write_index++;
291     if (channel->tx_write_index < channel->num_tx_buffers) return;
292     channel->tx_write_index = 0;
293 }
294 
295 static void l2cap_ertm_start_monitor_timer(l2cap_channel_t * channel){
296     log_info("Start Monitor timer");
297     btstack_run_loop_remove_timer(&channel->monitor_timer);
298     btstack_run_loop_set_timer_handler(&channel->monitor_timer, &l2cap_ertm_monitor_timeout_callback);
299     btstack_run_loop_set_timer_context(&channel->monitor_timer, channel);
300     btstack_run_loop_set_timer(&channel->monitor_timer, channel->local_monitor_timeout_ms);
301     btstack_run_loop_add_timer(&channel->monitor_timer);
302 }
303 
304 static void l2cap_ertm_stop_monitor_timer(l2cap_channel_t * channel){
305     log_info("Stop Monitor timer");
306     btstack_run_loop_remove_timer(&channel->monitor_timer);
307 }
308 
309 static void l2cap_ertm_start_retransmission_timer(l2cap_channel_t * channel){
310     log_info("Start Retransmission timer");
311     btstack_run_loop_remove_timer(&channel->retransmission_timer);
312     btstack_run_loop_set_timer_handler(&channel->retransmission_timer, &l2cap_ertm_retransmission_timeout_callback);
313     btstack_run_loop_set_timer_context(&channel->retransmission_timer, channel);
314     btstack_run_loop_set_timer(&channel->retransmission_timer, channel->local_retransmission_timeout_ms);
315     btstack_run_loop_add_timer(&channel->retransmission_timer);
316 }
317 
318 static void l2cap_ertm_stop_retransmission_timer(l2cap_channel_t * l2cap_channel){
319     log_info("Stop Retransmission timer");
320     btstack_run_loop_remove_timer(&l2cap_channel->retransmission_timer);
321 }
322 
323 static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts){
324     log_info("Monitor timeout");
325     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
326 
327     // TODO: we assume that it's the oldest packet
328     l2cap_ertm_tx_packet_state_t * tx_state;
329     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
330 
331     // check retry count
332     if (tx_state->retry_count < l2cap_channel->remote_max_transmit){
333         // increment retry count
334         tx_state->retry_count++;
335 
336         // start retransmit
337         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
338 
339         // start monitor timer
340         l2cap_ertm_start_monitor_timer(l2cap_channel);
341 
342         // send RR/P=1
343         l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
344     } else {
345         log_info("Monitor timer expired & retry count >= max transmit -> disconnect");
346         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
347     }
348     l2cap_run();
349 }
350 
351 static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts){
352     log_info("Retransmission timeout");
353     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
354 
355     // TODO: we assume that it's the oldest packet
356     l2cap_ertm_tx_packet_state_t * tx_state;
357     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
358 
359     // set retry count = 1
360     tx_state->retry_count = 1;
361 
362     // start retransmit
363     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
364 
365     // start monitor timer
366     l2cap_ertm_start_monitor_timer(l2cap_channel);
367 
368     // send RR/P=1
369     l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
370     l2cap_run();
371 }
372 
373 static int l2cap_ertm_send_information_frame(l2cap_channel_t * channel, int index, int final){
374     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
375     hci_reserve_packet_buffer();
376     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
377     uint16_t control = l2cap_encanced_control_field_for_information_frame(tx_state->tx_seq, final, channel->req_seq, tx_state->sar);
378     log_info("I-Frame: control 0x%04x", control);
379     little_endian_store_16(acl_buffer, 8, control);
380     (void)memcpy(&acl_buffer[8 + 2],
381                  &channel->tx_packets_data[index * channel->local_mps],
382                  tx_state->len);
383     // (re-)start retransmission timer on
384     l2cap_ertm_start_retransmission_timer(channel);
385     // send
386     return l2cap_send_prepared(channel->local_cid, 2 + tx_state->len);
387 }
388 
389 static void l2cap_ertm_store_fragment(l2cap_channel_t * channel, l2cap_segmentation_and_reassembly_t sar, uint16_t sdu_length, uint8_t * data, uint16_t len){
390     // get next index for storing packets
391     int index = channel->tx_write_index;
392 
393     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
394     tx_state->tx_seq = channel->next_tx_seq;
395     tx_state->sar = sar;
396     tx_state->retry_count = 0;
397 
398     uint8_t * tx_packet = &channel->tx_packets_data[index * channel->local_mps];
399     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);
400     int pos = 0;
401     if (sar == L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU){
402         little_endian_store_16(tx_packet, 0, sdu_length);
403         pos += 2;
404     }
405     (void)memcpy(&tx_packet[pos], data, len);
406     tx_state->len = pos + len;
407 
408     // update
409     channel->num_stored_tx_frames++;
410     channel->next_tx_seq = l2cap_next_ertm_seq_nr(channel->next_tx_seq);
411     l2cap_ertm_next_tx_write_index(channel);
412 
413     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);
414 
415 }
416 
417 static int l2cap_ertm_send(l2cap_channel_t * channel, uint8_t * data, uint16_t len){
418     if (len > channel->remote_mtu){
419         log_error("l2cap_ertm_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
420         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
421     }
422 
423     if (!l2cap_ertm_can_store_packet_now(channel)){
424         log_error("l2cap_ertm_send cid 0x%02x, fragment store full", channel->local_cid);
425         return BTSTACK_ACL_BUFFERS_FULL;
426     }
427 
428     // check if it needs to get fragmented
429     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
430     if (len > effective_mps){
431         // fragmentation needed.
432         l2cap_segmentation_and_reassembly_t sar =  L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU;
433         int chunk_len;
434         while (len){
435             switch (sar){
436                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
437                     chunk_len = effective_mps - 2;    // sdu_length
438                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
439                     len -= chunk_len;
440                     sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU;
441                     break;
442                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
443                     chunk_len = effective_mps;
444                     if (chunk_len >= len){
445                         sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU;
446                         chunk_len = len;
447                     }
448                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
449                     len -= chunk_len;
450                     break;
451                 default:
452                     break;
453             }
454         }
455 
456     } else {
457         l2cap_ertm_store_fragment(channel, L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU, 0, data, len);
458     }
459 
460     // try to send
461     l2cap_notify_channel_can_send();
462     return 0;
463 }
464 
465 static uint16_t l2cap_setup_options_ertm_request(l2cap_channel_t * channel, uint8_t * config_options){
466     int pos = 0;
467     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
468     config_options[pos++] = 9;      // length
469     config_options[pos++] = (uint8_t) channel->mode;
470     config_options[pos++] = channel->num_rx_buffers;    // == TxWindows size
471     config_options[pos++] = channel->local_max_transmit;
472     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
473     pos += 2;
474     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
475     pos += 2;
476     little_endian_store_16( config_options, pos, channel->local_mps);
477     pos += 2;
478     //
479     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT;
480     config_options[pos++] = 2;     // length
481     little_endian_store_16(config_options, pos, channel->local_mtu);
482     pos += 2;
483 
484     // Issue: iOS (e.g. 10.2) uses "No FCS" as default while Core 5.0 specifies "FCS" as default
485     // Workaround: try to actively negotiate FCS option
486     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
487     config_options[pos++] = 1;     // length
488     config_options[pos++] = channel->fcs_option;
489     return pos; // 11+4+3=18
490 }
491 
492 static uint16_t l2cap_setup_options_ertm_response(l2cap_channel_t * channel, uint8_t * config_options){
493     int pos = 0;
494     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
495     config_options[pos++] = 9;      // length
496     config_options[pos++] = (uint8_t) channel->mode;
497     // less or equal to remote tx window size
498     config_options[pos++] = btstack_min(channel->num_tx_buffers, channel->remote_tx_window_size);
499     // max transmit in response shall be ignored -> use sender values
500     config_options[pos++] = channel->remote_max_transmit;
501     // A value for the Retransmission time-out shall be sent in a positive Configuration Response
502     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
503     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
504     pos += 2;
505     // A value for the Monitor time-out shall be sent in a positive Configuration Response
506     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
507     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
508     pos += 2;
509     // less or equal to remote mps
510     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
511     little_endian_store_16( config_options, pos, effective_mps);
512     pos += 2;
513     //
514     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
515     config_options[pos++] = 2;     // length
516     little_endian_store_16(config_options, pos, channel->remote_mtu);
517     pos += 2;
518 #if 0
519     //
520     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
521     config_options[pos++] = 1;     // length
522     config_options[pos++] = channel->fcs_option;
523 #endif
524     return pos; // 11+4=15
525 }
526 
527 static int l2cap_ertm_send_supervisor_frame(l2cap_channel_t * channel, uint16_t control){
528     hci_reserve_packet_buffer();
529     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
530     log_info("S-Frame: control 0x%04x", control);
531     little_endian_store_16(acl_buffer, 8, control);
532     return l2cap_send_prepared(channel->local_cid, 2);
533 }
534 
535 static uint8_t l2cap_ertm_validate_local_config(l2cap_ertm_config_t * ertm_config){
536 
537     uint8_t result = ERROR_CODE_SUCCESS;
538     if (ertm_config->max_transmit < 1){
539         log_error("max_transmit must be >= 1");
540         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
541     }
542     if (ertm_config->retransmission_timeout_ms < 2000){
543         log_error("retransmission_timeout_ms must be >= 2000 ms");
544         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
545     }
546     if (ertm_config->monitor_timeout_ms < 12000){
547         log_error("monitor_timeout_ms must be >= 12000 ms");
548         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
549     }
550     if (ertm_config->local_mtu < 48){
551         log_error("local_mtu must be >= 48");
552         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
553     }
554     if (ertm_config->num_rx_buffers < 1){
555         log_error("num_rx_buffers must be >= 1");
556         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
557     }
558     if (ertm_config->num_tx_buffers < 1){
559         log_error("num_rx_buffers must be >= 1");
560         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
561     }
562     return result;
563 }
564 
565 static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
566 
567     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
568     channel->ertm_mandatory = ertm_config->ertm_mandatory;
569     channel->local_max_transmit = ertm_config->max_transmit;
570     channel->local_retransmission_timeout_ms = ertm_config->retransmission_timeout_ms;
571     channel->local_monitor_timeout_ms = ertm_config->monitor_timeout_ms;
572     channel->local_mtu = ertm_config->local_mtu;
573     channel->num_rx_buffers = ertm_config->num_rx_buffers;
574     channel->num_tx_buffers = ertm_config->num_tx_buffers;
575 
576     // align buffer to 16-byte boundary to assert l2cap_ertm_rx_packet_state_t is aligned
577     int bytes_till_alignment = 16 - (((uintptr_t) buffer) & 0x0f);
578     buffer += bytes_till_alignment;
579     size   -= bytes_till_alignment;
580 
581     // setup state buffers - use void cast to avoid -Wcast-align warning
582     uint32_t pos = 0;
583     channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) (void *) &buffer[pos];
584     pos += ertm_config->num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
585     channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) (void *) &buffer[pos];
586     pos += ertm_config->num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
587 
588     // setup reassembly buffer
589     channel->reassembly_buffer = &buffer[pos];
590     pos += ertm_config->local_mtu;
591 
592     // divide rest of data equally
593     channel->local_mps = (size - pos) / (ertm_config->num_rx_buffers + ertm_config->num_tx_buffers);
594     log_info("Local MPS: %u", channel->local_mps);
595     channel->rx_packets_data = &buffer[pos];
596     pos += ertm_config->num_rx_buffers * channel->local_mps;
597     channel->tx_packets_data = &buffer[pos];
598 
599     channel->fcs_option = ertm_config->fcs_option;
600 }
601 
602 uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
603     l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
604 
605     log_info("L2CAP_CREATE_ERTM_CHANNEL addr %s, psm 0x%x, local mtu %u", bd_addr_to_str(address), psm, ertm_config->local_mtu);
606 
607     // validate local config
608     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
609     if (result) return result;
610 
611     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, address, BD_ADDR_TYPE_ACL, psm, ertm_config->local_mtu, LEVEL_0);
612     if (!channel) {
613         return BTSTACK_MEMORY_ALLOC_FAILED;
614     }
615 
616     // configure ERTM
617     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
618 
619     // add to connections list
620     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
621 
622     // store local_cid
623     if (out_local_cid){
624        *out_local_cid = channel->local_cid;
625     }
626 
627     // check if hci connection is already usable
628     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
629     if (conn){
630         log_info("l2cap_create_channel, hci connection already exists");
631         l2cap_handle_connection_complete(conn->con_handle, channel);
632         // check if remote supported fearures are already received
633         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
634             l2cap_handle_remote_supported_features_received(channel);
635         }
636     }
637 
638     l2cap_run();
639 
640     return 0;
641 }
642 
643 static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel){
644     if (l2cap_ertm_can_store_packet_now(channel)){
645         channel->waiting_for_can_send_now = 0;
646         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
647     }
648 }
649 
650 uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
651 
652     log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
653     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
654     if (!channel) {
655         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
656         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
657     }
658 
659     // validate local config
660     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
661     if (result) return result;
662 
663     // configure L2CAP ERTM
664     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
665 
666     // default: continue
667     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
668 
669     // verify remote ERTM support
670     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
671     if (connection == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
672 
673     if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
674         // ERTM not possible, select basic mode and release buffer
675         channel->mode = L2CAP_CHANNEL_MODE_BASIC;
676         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
677 
678         // bail if ERTM is mandatory
679         if (channel->ertm_mandatory){
680             // We chose 'no resources available' for "ERTM mandatory but you don't even know ERTM exists"
681             log_info("ERTM mandatory -> reject connection");
682             channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
683             channel->reason = 0x04; // no resources available
684         }  else {
685             log_info("ERTM not supported by remote -> use Basic mode");
686         }
687     }
688 
689     // process
690     l2cap_run();
691 
692     return ERROR_CODE_SUCCESS;
693 }
694 
695 uint8_t l2cap_ertm_set_busy(uint16_t local_cid){
696     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
697     if (!channel) {
698         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
699         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
700     }
701     if (!channel->local_busy){
702         channel->local_busy = 1;
703         channel->send_supervisor_frame_receiver_not_ready = 1;
704         l2cap_run();
705     }
706     return ERROR_CODE_SUCCESS;
707 }
708 
709 uint8_t l2cap_ertm_set_ready(uint16_t local_cid){
710     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
711     if (!channel) {
712         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
713         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
714     }
715     if (channel->local_busy){
716         channel->local_busy = 0;
717         channel->send_supervisor_frame_receiver_ready_poll = 1;
718         l2cap_run();
719     }
720     return ERROR_CODE_SUCCESS;
721 }
722 
723 // Process-ReqSeq
724 static void l2cap_ertm_process_req_seq(l2cap_channel_t * l2cap_channel, uint8_t req_seq){
725     int num_buffers_acked = 0;
726     l2cap_ertm_tx_packet_state_t * tx_state;
727     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);
728     while (true){
729 
730         // no unack packets left
731         if (l2cap_channel->unacked_frames == 0) {
732             // stop retransmission timer
733             l2cap_ertm_stop_retransmission_timer(l2cap_channel);
734             break;
735         }
736 
737         tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
738         // calc delta
739         int delta = (req_seq - tx_state->tx_seq) & 0x03f;
740         if (delta == 0) break;  // all packets acknowledged
741         if (delta > l2cap_channel->remote_tx_window_size) break;
742 
743         num_buffers_acked++;
744         l2cap_channel->num_stored_tx_frames--;
745         l2cap_channel->unacked_frames--;
746         log_info("RR seq %u => packet with tx_seq %u done", req_seq, tx_state->tx_seq);
747 
748         l2cap_channel->tx_read_index++;
749         if (l2cap_channel->tx_read_index >= l2cap_channel->num_rx_buffers){
750             l2cap_channel->tx_read_index = 0;
751         }
752     }
753     if (num_buffers_acked){
754         log_info("num_buffers_acked %u", num_buffers_acked);
755     l2cap_ertm_notify_channel_can_send(l2cap_channel);
756 }
757 }
758 
759 static l2cap_ertm_tx_packet_state_t * l2cap_ertm_get_tx_state(l2cap_channel_t * l2cap_channel, uint8_t tx_seq){
760     int i;
761     for (i=0;i<l2cap_channel->num_tx_buffers;i++){
762         l2cap_ertm_tx_packet_state_t * tx_state = &l2cap_channel->tx_packets_state[i];
763         if (tx_state->tx_seq == tx_seq) return tx_state;
764     }
765     return NULL;
766 }
767 
768 // @param delta number of frames in the future, >= 1
769 // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
770 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){
771     log_info("Store SDU with delta %u", delta);
772     // get rx state for packet to store
773     int index = l2cap_channel->rx_store_index + delta - 1;
774     if (index > l2cap_channel->num_rx_buffers){
775         index -= l2cap_channel->num_rx_buffers;
776     }
777     log_info("Index of packet to store %u", index);
778     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
779     // check if buffer is free
780     if (rx_state->valid){
781         log_error("Packet buffer already used");
782         return;
783     }
784     rx_state->valid = 1;
785     rx_state->sar = sar;
786     rx_state->len = size;
787     uint8_t * rx_buffer = &l2cap_channel->rx_packets_data[index];
788     (void)memcpy(rx_buffer, payload, size);
789 }
790 
791 // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
792 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){
793     uint16_t reassembly_sdu_length;
794     switch (sar){
795         case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
796             // assert total packet size <= our mtu
797             if (size > l2cap_channel->local_mtu) break;
798             // packet complete -> disapatch
799             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, (uint8_t*) payload, size);
800             break;
801         case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
802             // read SDU len
803             reassembly_sdu_length = little_endian_read_16(payload, 0);
804             payload += 2;
805             size    -= 2;
806             // assert reassembled size <= our mtu
807             if (reassembly_sdu_length > l2cap_channel->local_mtu) break;
808             // store start segment
809             l2cap_channel->reassembly_sdu_length = reassembly_sdu_length;
810             (void)memcpy(&l2cap_channel->reassembly_buffer[0], payload, size);
811             l2cap_channel->reassembly_pos = size;
812             break;
813         case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
814             // assert size of reassembled data <= our mtu
815             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
816             // store continuation segment
817             (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
818                          payload, size);
819             l2cap_channel->reassembly_pos += size;
820             break;
821         case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
822             // assert size of reassembled data <= our mtu
823             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
824             // store continuation segment
825             (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
826                          payload, size);
827             l2cap_channel->reassembly_pos += size;
828             // assert size of reassembled data matches announced sdu length
829             if (l2cap_channel->reassembly_pos != l2cap_channel->reassembly_sdu_length) break;
830             // packet complete -> disapatch
831             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->reassembly_buffer, l2cap_channel->reassembly_pos);
832             l2cap_channel->reassembly_pos = 0;
833             break;
834         default:
835             btstack_assert(false);
836             break;
837     }
838 }
839 
840 static void l2cap_ertm_channel_send_information_frame(l2cap_channel_t * channel){
841     channel->unacked_frames++;
842     int index = channel->tx_send_index;
843     channel->tx_send_index++;
844     if (channel->tx_send_index >= channel->num_tx_buffers){
845         channel->tx_send_index = 0;
846     }
847     l2cap_ertm_send_information_frame(channel, index, 0);   // final = 0
848 }
849 
850 #endif
851 
852 #ifdef L2CAP_USES_CHANNELS
853 static uint16_t l2cap_next_local_cid(void){
854     do {
855         if (local_source_cid == 0xffffu) {
856             local_source_cid = 0x40;
857         } else {
858             local_source_cid++;
859         }
860     } while (l2cap_get_channel_for_local_cid(local_source_cid) != NULL);
861     return local_source_cid;
862 }
863 #endif
864 
865 static uint8_t l2cap_next_sig_id(void){
866     if (sig_seq_nr == 0xffu) {
867         sig_seq_nr = 1;
868     } else {
869         sig_seq_nr++;
870     }
871     return sig_seq_nr;
872 }
873 
874 void l2cap_init(void){
875     signaling_responses_pending = 0;
876 
877     l2cap_channels = NULL;
878 
879 #ifdef ENABLE_CLASSIC
880     l2cap_services = NULL;
881     require_security_level2_for_outgoing_sdp = 0;
882 
883     // Setup Connectionless Channel
884     l2cap_fixed_channel_connectionless.local_cid     = L2CAP_CID_CONNECTIONLESS_CHANNEL;
885     l2cap_fixed_channel_connectionless.channel_type  = L2CAP_CHANNEL_TYPE_CONNECTIONLESS;
886     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_connectionless);
887 #endif
888 
889 #ifdef ENABLE_LE_DATA_CHANNELS
890     l2cap_le_services = NULL;
891 #endif
892 
893 #ifdef ENABLE_BLE
894     l2cap_event_packet_handler = NULL;
895     l2cap_le_custom_max_mtu = 0;
896 
897     // Setup fixed ATT Channel
898     l2cap_fixed_channel_att.local_cid    = L2CAP_CID_ATTRIBUTE_PROTOCOL;
899     l2cap_fixed_channel_att.channel_type = L2CAP_CHANNEL_TYPE_LE_FIXED;
900     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_att);
901 
902     // Setup fixed SM Channel
903     l2cap_fixed_channel_sm.local_cid     = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
904     l2cap_fixed_channel_sm.channel_type  = L2CAP_CHANNEL_TYPE_LE_FIXED;
905     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_sm);
906 #endif
907 
908     //
909     // register callback with HCI
910     //
911     hci_event_callback_registration.callback = &l2cap_hci_event_handler;
912     hci_add_event_handler(&hci_event_callback_registration);
913 
914     hci_register_acl_packet_handler(&l2cap_acl_handler);
915 
916 #ifdef ENABLE_CLASSIC
917     gap_connectable_control(0); // no services yet
918 #endif
919 }
920 
921 void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
922 #ifdef ENABLE_BLE
923     l2cap_event_packet_handler = handler;
924 #else
925     UNUSED(handler);    // ok: no code
926 #endif
927 }
928 
929 void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
930     UNUSED(con_handle);  // ok: there is no con handle
931 
932     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
933     if (!channel) return;
934     channel->waiting_for_can_send_now = 1;
935     l2cap_notify_channel_can_send();
936 }
937 
938 int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
939     UNUSED(channel_id); // ok: only depends on Controller LE buffers
940 
941     return hci_can_send_acl_packet_now(con_handle);
942 }
943 
944 uint8_t *l2cap_get_outgoing_buffer(void){
945     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
946 }
947 
948 // only for L2CAP Basic Channels
949 int l2cap_reserve_packet_buffer(void){
950     return hci_reserve_packet_buffer();
951 }
952 
953 // only for L2CAP Basic Channels
954 void l2cap_release_packet_buffer(void){
955     hci_release_packet_buffer();
956 }
957 
958 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){
959     // 0 - Connection handle : PB=pb : BC=00
960     little_endian_store_16(acl_buffer, 0u, con_handle | (packet_boundary << 12u) | (0u << 14u));
961     // 2 - ACL length
962     little_endian_store_16(acl_buffer, 2u,  len + 4u);
963     // 4 - L2CAP packet length
964     little_endian_store_16(acl_buffer, 4u,  len + 0u);
965     // 6 - L2CAP channel DEST
966     little_endian_store_16(acl_buffer, 6,  remote_cid);
967 }
968 
969 // assumption - only on LE connections
970 int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
971 
972     if (!hci_is_packet_buffer_reserved()){
973         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
974         return BTSTACK_ACL_BUFFERS_FULL;
975     }
976 
977     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
978         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
979         return BTSTACK_ACL_BUFFERS_FULL;
980     }
981 
982     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
983 
984     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
985     l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
986     // send
987     return hci_send_acl_packet_buffer(len+8u);
988 }
989 
990 // assumption - only on LE connections
991 int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
992 
993     if (!hci_can_send_acl_packet_now(con_handle)){
994         log_info("l2cap_send cid 0x%02x, cannot send", cid);
995         return BTSTACK_ACL_BUFFERS_FULL;
996     }
997 
998     hci_reserve_packet_buffer();
999     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1000 
1001     (void)memcpy(&acl_buffer[8], data, len);
1002 
1003     return l2cap_send_prepared_connectionless(con_handle, cid, len);
1004 }
1005 
1006 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
1007     log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
1008     uint8_t event[4];
1009     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
1010     event[1] = sizeof(event) - 2u;
1011     little_endian_store_16(event, 2, channel);
1012     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1013     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
1014 }
1015 
1016 #ifdef L2CAP_USES_CHANNELS
1017 static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
1018     (* (channel->packet_handler))(type, channel->local_cid, data, size);
1019 }
1020 
1021 static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
1022     uint8_t event[4];
1023     event[0] = event_code;
1024     event[1] = sizeof(event) - 2u;
1025     little_endian_store_16(event, 2, channel->local_cid);
1026     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1027     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1028 }
1029 #endif
1030 
1031 #ifdef ENABLE_CLASSIC
1032 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
1033     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",
1034              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
1035              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
1036     uint8_t event[26];
1037     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
1038     event[1] = sizeof(event) - 2;
1039     event[2] = status;
1040     reverse_bd_addr(channel->address, &event[3]);
1041     little_endian_store_16(event,  9, channel->con_handle);
1042     little_endian_store_16(event, 11, channel->psm);
1043     little_endian_store_16(event, 13, channel->local_cid);
1044     little_endian_store_16(event, 15, channel->remote_cid);
1045     little_endian_store_16(event, 17, channel->local_mtu);
1046     little_endian_store_16(event, 19, channel->remote_mtu);
1047     little_endian_store_16(event, 21, channel->flush_timeout);
1048     event[23] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
1049 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1050     log_info("ERTM mode %u, fcs enabled %u", channel->mode, channel->fcs_option);
1051     event[24] = channel->mode;
1052     event[25] = channel->fcs_option;
1053 
1054 #else
1055     event[24] = L2CAP_CHANNEL_MODE_BASIC;
1056     event[25] = 0;
1057 #endif
1058     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1059     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1060 }
1061 
1062 static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
1063     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
1064     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
1065 }
1066 
1067 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
1068     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
1069              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
1070     uint8_t event[16];
1071     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
1072     event[1] = sizeof(event) - 2;
1073     reverse_bd_addr(channel->address, &event[2]);
1074     little_endian_store_16(event,  8, channel->con_handle);
1075     little_endian_store_16(event, 10, channel->psm);
1076     little_endian_store_16(event, 12, channel->local_cid);
1077     little_endian_store_16(event, 14, channel->remote_cid);
1078     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1079     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1080 }
1081 
1082 static void l2cap_handle_channel_open_failed(l2cap_channel_t * channel, uint8_t status){
1083 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1084     // emit ertm buffer released, as it's not needed. if in basic mode, it was either not allocated or already released
1085     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1086         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1087     }
1088 #endif
1089     l2cap_emit_channel_opened(channel, status);
1090 }
1091 
1092 static void l2cap_handle_channel_closed(l2cap_channel_t * channel){
1093 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1094     // emit ertm buffer released, as it's not needed anymore. if in basic mode, it was either not allocated or already released
1095     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1096         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1097     }
1098 #endif
1099     l2cap_emit_channel_closed(channel);
1100 }
1101 #endif
1102 
1103 static l2cap_fixed_channel_t * l2cap_channel_item_by_cid(uint16_t cid){
1104     btstack_linked_list_iterator_t it;
1105     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1106     while (btstack_linked_list_iterator_has_next(&it)){
1107         l2cap_fixed_channel_t * channel = (l2cap_fixed_channel_t*) btstack_linked_list_iterator_next(&it);
1108         if (channel->local_cid == cid) {
1109             return channel;
1110         }
1111     }
1112     return NULL;
1113 }
1114 
1115 // used for fixed channels in LE (ATT/SM) and Classic (Connectionless Channel). CID < 0x04
1116 static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid){
1117     if (local_cid >= 0x40u) return NULL;
1118     return (l2cap_fixed_channel_t*) l2cap_channel_item_by_cid(local_cid);
1119 }
1120 
1121 // used for Classic Channels + LE Data Channels. local_cid >= 0x40
1122 #ifdef L2CAP_USES_CHANNELS
1123 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
1124     if (local_cid < 0x40u) return NULL;
1125     return (l2cap_channel_t*) l2cap_channel_item_by_cid(local_cid);
1126 }
1127 
1128 void l2cap_request_can_send_now_event(uint16_t local_cid){
1129     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1130     if (!channel) return;
1131     channel->waiting_for_can_send_now = 1;
1132 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1133     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1134         l2cap_ertm_notify_channel_can_send(channel);
1135         return;
1136     }
1137 #endif
1138     l2cap_notify_channel_can_send();
1139 }
1140 
1141 int  l2cap_can_send_packet_now(uint16_t local_cid){
1142     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1143     if (!channel) return 0;
1144 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1145     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1146         return l2cap_ertm_can_store_packet_now(channel);
1147     }
1148 #endif
1149     return hci_can_send_acl_packet_now(channel->con_handle);
1150 }
1151 
1152 int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
1153     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1154     if (!channel) return 0;
1155 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1156     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1157         return 0;
1158     }
1159 #endif
1160     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
1161 }
1162 
1163 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
1164     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1165     if (channel) {
1166         return channel->remote_mtu;
1167     }
1168     return 0;
1169 }
1170 #endif
1171 
1172 #ifdef L2CAP_USES_CHANNELS
1173 static int l2cap_is_dynamic_channel_type(l2cap_channel_type_t channel_type){
1174     switch (channel_type){
1175         case L2CAP_CHANNEL_TYPE_CLASSIC:
1176         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
1177             return 1;
1178         default:
1179             return 0;
1180     }
1181 }
1182 #endif
1183 
1184 #ifdef ENABLE_CLASSIC
1185 // RTX Timer only exist for dynamic channels
1186 static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
1187     btstack_linked_list_iterator_t it;
1188     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1189     while (btstack_linked_list_iterator_has_next(&it)){
1190         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1191         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
1192         if (&channel->rtx == ts) {
1193             return channel;
1194         }
1195     }
1196     return NULL;
1197 }
1198 
1199 static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
1200     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
1201     if (!channel) return;
1202 
1203     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
1204 
1205     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
1206     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
1207     // notify client
1208     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
1209 
1210     // discard channel
1211     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1212     l2cap_free_channel_entry(channel);
1213 }
1214 
1215 #endif
1216 
1217 #ifdef L2CAP_USES_CHANNELS
1218 static void l2cap_stop_rtx(l2cap_channel_t * channel){
1219     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
1220     btstack_run_loop_remove_timer(&channel->rtx);
1221 }
1222 #endif
1223 
1224 #ifdef ENABLE_CLASSIC
1225 
1226 static void l2cap_start_rtx(l2cap_channel_t * channel){
1227     l2cap_stop_rtx(channel);
1228     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
1229     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1230     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
1231     btstack_run_loop_add_timer(&channel->rtx);
1232 }
1233 
1234 static void l2cap_start_ertx(l2cap_channel_t * channel){
1235     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
1236     l2cap_stop_rtx(channel);
1237     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1238     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
1239     btstack_run_loop_add_timer(&channel->rtx);
1240 }
1241 
1242 void l2cap_require_security_level_2_for_outgoing_sdp(void){
1243     require_security_level2_for_outgoing_sdp = 1;
1244 }
1245 
1246 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
1247     return (psm == BLUETOOTH_PSM_SDP) && (!require_security_level2_for_outgoing_sdp);
1248 }
1249 
1250 static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1251     if (!hci_can_send_acl_packet_now(handle)){
1252         log_info("l2cap_send_signaling_packet, cannot send");
1253         return BTSTACK_ACL_BUFFERS_FULL;
1254     }
1255 
1256     // log_info("l2cap_send_signaling_packet type %u", cmd);
1257     hci_reserve_packet_buffer();
1258     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1259     va_list argptr;
1260     va_start(argptr, identifier);
1261     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
1262     va_end(argptr);
1263     // log_info("l2cap_send_signaling_packet con %u!", handle);
1264     return hci_send_acl_packet_buffer(len);
1265 }
1266 
1267 // assumption - only on Classic connections
1268 // cannot be used for L2CAP ERTM
1269 int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
1270 
1271     if (!hci_is_packet_buffer_reserved()){
1272         log_error("l2cap_send_prepared called without reserving packet first");
1273         return BTSTACK_ACL_BUFFERS_FULL;
1274     }
1275 
1276     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1277     if (!channel) {
1278         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
1279         return -1;   // TODO: define error
1280     }
1281 
1282     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
1283         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
1284         return BTSTACK_ACL_BUFFERS_FULL;
1285     }
1286 
1287     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
1288 
1289     int fcs_size = 0;
1290 
1291 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1292     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->fcs_option){
1293         fcs_size = 2;
1294     }
1295 #endif
1296 
1297     // set non-flushable packet boundary flag if supported on Controller
1298     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1299     uint8_t packet_boundary_flag = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
1300     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
1301 
1302 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1303     if (fcs_size){
1304         // calculate FCS over l2cap data
1305         uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
1306         log_info("I-Frame: fcs 0x%04x", fcs);
1307         little_endian_store_16(acl_buffer, 8 + len, fcs);
1308     }
1309 #endif
1310 
1311     // send
1312     return hci_send_acl_packet_buffer(len+8+fcs_size);
1313 }
1314 
1315 // assumption - only on Classic connections
1316 int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
1317     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1318     if (!channel) {
1319         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
1320         return -1;   // TODO: define error
1321     }
1322 
1323 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1324     // send in ERTM
1325     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1326         return l2cap_ertm_send(channel, data, len);
1327     }
1328 #endif
1329 
1330     if (len > channel->remote_mtu){
1331         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
1332         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
1333     }
1334 
1335     if (!hci_can_send_acl_packet_now(channel->con_handle)){
1336         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
1337         return BTSTACK_ACL_BUFFERS_FULL;
1338     }
1339 
1340     hci_reserve_packet_buffer();
1341     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1342     (void)memcpy(&acl_buffer[8], data, len);
1343     return l2cap_send_prepared(local_cid, len);
1344 }
1345 
1346 int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
1347     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
1348 }
1349 
1350 static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
1351     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
1352 }
1353 
1354 static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
1355     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
1356 }
1357 #endif
1358 
1359 
1360 #ifdef ENABLE_BLE
1361 static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1362 
1363     if (!hci_can_send_acl_packet_now(handle)){
1364         log_info("l2cap_send_le_signaling_packet, cannot send");
1365         return BTSTACK_ACL_BUFFERS_FULL;
1366     }
1367 
1368     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
1369     hci_reserve_packet_buffer();
1370     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1371     va_list argptr;
1372     va_start(argptr, identifier);
1373     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
1374     va_end(argptr);
1375     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
1376     return hci_send_acl_packet_buffer(len);
1377 }
1378 #endif
1379 
1380 uint16_t l2cap_max_mtu(void){
1381     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
1382 }
1383 
1384 #ifdef ENABLE_BLE
1385 uint16_t l2cap_max_le_mtu(void){
1386     if (l2cap_le_custom_max_mtu != 0u) return l2cap_le_custom_max_mtu;
1387     return l2cap_max_mtu();
1388 }
1389 
1390 void l2cap_set_max_le_mtu(uint16_t max_mtu){
1391     if (max_mtu < l2cap_max_mtu()){
1392         l2cap_le_custom_max_mtu = max_mtu;
1393     }
1394 }
1395 #endif
1396 
1397 #ifdef ENABLE_CLASSIC
1398 
1399 static uint16_t l2cap_setup_options_mtu(uint8_t * config_options, uint16_t mtu){
1400     config_options[0] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
1401     config_options[1] = 2; // len param
1402     little_endian_store_16(config_options, 2, mtu);
1403     return 4;
1404 }
1405 
1406 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1407 static int l2cap_ertm_mode(l2cap_channel_t * channel){
1408     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
1409     return ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE)
1410         &&  (connection->l2cap_state.extended_feature_mask & 0x08));
1411 }
1412 #endif
1413 
1414 static uint16_t l2cap_setup_options_request(l2cap_channel_t * channel, uint8_t * config_options){
1415 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1416     // use ERTM options if supported by remote and channel ready to use it
1417     if (l2cap_ertm_mode(channel) && channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1418         return l2cap_setup_options_ertm_request(channel, config_options);
1419     }
1420 #endif
1421     uint16_t mtu = channel->local_mtu;
1422     return l2cap_setup_options_mtu(config_options, mtu);
1423 }
1424 
1425 static uint16_t l2cap_setup_options_mtu_response(l2cap_channel_t * channel, uint8_t * config_options){
1426     uint16_t mtu = btstack_min(channel->local_mtu, channel->remote_mtu);
1427     return l2cap_setup_options_mtu(config_options, mtu);
1428 }
1429 
1430 static uint32_t l2cap_extended_features_mask(void){
1431     // extended features request supported, features: fixed channels, unicast connectionless data reception
1432     uint32_t features = 0x280;
1433 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1434     features |= 0x0028;
1435 #endif
1436     return features;
1437 }
1438 #endif
1439 
1440 //
1441 #ifdef ENABLE_CLASSIC
1442 
1443 // returns true if channel was finalized
1444 static bool l2cap_run_for_classic_channel(l2cap_channel_t * channel){
1445 
1446 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1447     uint8_t  config_options[18];
1448 #else
1449     uint8_t  config_options[10];
1450 #endif
1451 
1452     switch (channel->state){
1453 
1454         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1455         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
1456             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1457             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
1458                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
1459                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
1460             }
1461             break;
1462 
1463         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1464             if (!hci_can_send_command_packet_now()) break;
1465             // send connection request - set state first
1466             channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
1467             // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
1468             (void)memcpy(l2cap_outgoing_classic_addr, channel->address, 6);
1469             hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_get_allow_role_switch());
1470             break;
1471 
1472         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
1473             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1474             channel->state = L2CAP_STATE_INVALID;
1475             l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
1476             // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1477             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1478             l2cap_free_channel_entry(channel);
1479             channel = NULL;
1480             break;
1481 
1482         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
1483             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1484             channel->state = L2CAP_STATE_CONFIG;
1485             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1486             l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
1487             break;
1488 
1489         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
1490             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1491             // success, start l2cap handshake
1492             channel->local_sig_id = l2cap_next_sig_id();
1493             channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
1494             l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
1495             l2cap_start_rtx(channel);
1496             break;
1497 
1498         case L2CAP_STATE_CONFIG:
1499             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1500 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1501             // fallback to basic mode if ERTM requested but not not supported by remote
1502             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1503                 if (!l2cap_ertm_mode(channel)){
1504                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1505                     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
1506                 }
1507             }
1508 #endif
1509             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
1510                 uint16_t flags = 0;
1511                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1512                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
1513                     flags = 1;
1514                 } else {
1515                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1516                 }
1517                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
1518                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1519                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS, 0, NULL);
1520 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1521                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
1522                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1523                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1524                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1525                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS, options_size, &config_options);
1526                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM){
1527                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
1528                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1529                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1530                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, options_size, &config_options);
1531 #endif
1532                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
1533                     channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1534                     uint16_t options_size = l2cap_setup_options_mtu_response(channel, config_options);
1535                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, options_size, &config_options);
1536                 } else {
1537                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
1538                 }
1539                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1540             }
1541             else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
1542                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1543                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
1544                 channel->local_sig_id = l2cap_next_sig_id();
1545                 uint16_t options_size = l2cap_setup_options_request(channel, config_options);
1546                 l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options);
1547                 l2cap_start_rtx(channel);
1548             }
1549             if (l2cap_channel_ready_for_open(channel)){
1550                 channel->state = L2CAP_STATE_OPEN;
1551                 l2cap_emit_channel_opened(channel, 0);  // success
1552             }
1553             break;
1554 
1555         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1556             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1557             channel->state = L2CAP_STATE_INVALID;
1558             l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1559             // 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 :)
1560             l2cap_finialize_channel_close(channel);  // -- remove from list
1561             channel = NULL;
1562             break;
1563 
1564         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1565             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1566             channel->local_sig_id = l2cap_next_sig_id();
1567             channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1568             l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1569             break;
1570         default:
1571             break;
1572     }
1573 
1574     // handle channel finalize on L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE and L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE
1575     return channel == NULL;
1576 }
1577 
1578 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1579 static void l2cap_run_for_classic_channel_ertm(l2cap_channel_t * channel){
1580 
1581     // ERTM mode
1582     if (channel->mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) return;
1583 
1584     // check if we can still send
1585     if (channel->con_handle == HCI_CON_HANDLE_INVALID) return;
1586     if (!hci_can_send_acl_packet_now(channel->con_handle)) return;
1587 
1588     if (channel->send_supervisor_frame_receiver_ready){
1589         channel->send_supervisor_frame_receiver_ready = 0;
1590         log_info("Send S-Frame: RR %u, final %u", channel->req_seq, channel->set_final_bit_after_packet_with_poll_bit_set);
1591         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);
1592         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1593         l2cap_ertm_send_supervisor_frame(channel, control);
1594         return;
1595     }
1596     if (channel->send_supervisor_frame_receiver_ready_poll){
1597         channel->send_supervisor_frame_receiver_ready_poll = 0;
1598         log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
1599         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
1600         l2cap_ertm_send_supervisor_frame(channel, control);
1601         return;
1602     }
1603     if (channel->send_supervisor_frame_receiver_not_ready){
1604         channel->send_supervisor_frame_receiver_not_ready = 0;
1605         log_info("Send S-Frame: RNR %u", channel->req_seq);
1606         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
1607         l2cap_ertm_send_supervisor_frame(channel, control);
1608         return;
1609     }
1610     if (channel->send_supervisor_frame_reject){
1611         channel->send_supervisor_frame_reject = 0;
1612         log_info("Send S-Frame: REJ %u", channel->req_seq);
1613         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 0, 0, channel->req_seq);
1614         l2cap_ertm_send_supervisor_frame(channel, control);
1615         return;
1616     }
1617     if (channel->send_supervisor_frame_selective_reject){
1618         channel->send_supervisor_frame_selective_reject = 0;
1619         log_info("Send S-Frame: SREJ %u", channel->expected_tx_seq);
1620         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);
1621         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1622         l2cap_ertm_send_supervisor_frame(channel, control);
1623         return;
1624     }
1625 
1626     if (channel->srej_active){
1627         int i;
1628         for (i=0;i<channel->num_tx_buffers;i++){
1629             l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
1630             if (tx_state->retransmission_requested) {
1631                 tx_state->retransmission_requested = 0;
1632                 uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set;
1633                 channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1634                 l2cap_ertm_send_information_frame(channel, i, final);
1635                 break;
1636             }
1637         }
1638         if (i == channel->num_tx_buffers){
1639             // no retransmission request found
1640             channel->srej_active = 0;
1641         } else {
1642             // packet was sent
1643             return;
1644         }
1645     }
1646 }
1647 #endif /* ERTM */
1648 #endif /* Classic */
1649 
1650 static void l2cap_run_signaling_response(void) {
1651 
1652     // check pending signaling responses
1653     while (signaling_responses_pending){
1654 
1655         hci_con_handle_t handle = signaling_responses[0].handle;
1656 
1657         if (!hci_can_send_acl_packet_now(handle)) break;
1658 
1659         uint8_t  sig_id        = signaling_responses[0].sig_id;
1660         uint8_t  response_code = signaling_responses[0].code;
1661         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
1662 #ifdef ENABLE_CLASSIC
1663         uint16_t info_type     = signaling_responses[0].data;  // INFORMATION_REQUEST
1664         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
1665 #endif
1666 
1667         // remove first item before sending (to avoid sending response mutliple times)
1668         signaling_responses_pending--;
1669         int i;
1670         for (i=0; i < signaling_responses_pending; i++){
1671             (void)memcpy(&signaling_responses[i],
1672                          &signaling_responses[i + 1],
1673                          sizeof(l2cap_signaling_response_t));
1674         }
1675 
1676         switch (response_code){
1677 #ifdef ENABLE_CLASSIC
1678             case CONNECTION_REQUEST:
1679                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
1680                 // also disconnect if result is 0x0003 - security blocked
1681                 if (result == 0x0003){
1682                     hci_disconnect_security_block(handle);
1683                 }
1684                 break;
1685             case ECHO_REQUEST:
1686                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
1687                 break;
1688             case INFORMATION_REQUEST:
1689                 switch (info_type){
1690                     case L2CAP_INFO_TYPE_CONNECTIONLESS_MTU: {
1691                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
1692                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(connectionless_mtu), &connectionless_mtu);
1693                         }
1694                         break;
1695                     case L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED: {
1696                             uint32_t features = l2cap_extended_features_mask();
1697                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(features), &features);
1698                         }
1699                         break;
1700                     case L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED: {
1701                             uint8_t map[8];
1702                             memset(map, 0, 8);
1703                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
1704                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(map), &map);
1705                         }
1706                         break;
1707                     default:
1708                         // all other types are not supported
1709                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 1, 0, NULL);
1710                         break;
1711                 }
1712                 break;
1713             case COMMAND_REJECT:
1714                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
1715                 break;
1716 #endif
1717 #ifdef ENABLE_BLE
1718             case LE_CREDIT_BASED_CONNECTION_REQUEST:
1719                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
1720                 break;
1721             case COMMAND_REJECT_LE:
1722                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
1723                 break;
1724 #endif
1725             default:
1726                 // should not happen
1727                 break;
1728         }
1729     }
1730 }
1731 
1732 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1733 static bool l2ap_run_ertm(void){
1734     // send l2cap information request if neccessary
1735     btstack_linked_list_iterator_t it;
1736     hci_connections_get_iterator(&it);
1737     while(btstack_linked_list_iterator_has_next(&it)){
1738         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1739         if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST){
1740             if (!hci_can_send_acl_packet_now(connection->con_handle)) break;
1741             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
1742             uint8_t sig_id = l2cap_next_sig_id();
1743             uint8_t info_type = L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED;
1744             l2cap_send_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
1745             return true;
1746         }
1747     }
1748     return false;
1749 }
1750 #endif
1751 
1752 #ifdef ENABLE_LE_DATA_CHANNELS
1753 static void l2cap_run_le_data_channels(void){
1754     btstack_linked_list_iterator_t it;
1755     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1756     while (btstack_linked_list_iterator_has_next(&it)){
1757         uint16_t mps;
1758         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1759 
1760         if (channel->channel_type != L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL) continue;
1761 
1762         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1763         switch (channel->state){
1764             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
1765                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1766                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
1767                 // le psm, source cid, mtu, mps, initial credits
1768                 channel->local_sig_id = l2cap_next_sig_id();
1769                 channel->credits_incoming =  channel->new_credits_incoming;
1770                 channel->new_credits_incoming = 0;
1771                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
1772                 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);
1773                 break;
1774             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
1775                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1776                 // TODO: support larger MPS
1777                 channel->state = L2CAP_STATE_OPEN;
1778                 channel->credits_incoming =  channel->new_credits_incoming;
1779                 channel->new_credits_incoming = 0;
1780                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
1781                 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);
1782                 // notify client
1783                 l2cap_emit_le_channel_opened(channel, 0);
1784                 break;
1785             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
1786                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1787                 channel->state = L2CAP_STATE_INVALID;
1788                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
1789                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1790                 btstack_linked_list_iterator_remove(&it);
1791                 l2cap_free_channel_entry(channel);
1792                 break;
1793             case L2CAP_STATE_OPEN:
1794                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1795 
1796                 // send credits
1797                 if (channel->new_credits_incoming){
1798                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
1799                     channel->local_sig_id = l2cap_next_sig_id();
1800                     uint16_t new_credits = channel->new_credits_incoming;
1801                     channel->new_credits_incoming = 0;
1802                     channel->credits_incoming += new_credits;
1803                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
1804                 }
1805                 break;
1806 
1807             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1808                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1809                 channel->local_sig_id = l2cap_next_sig_id();
1810                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1811                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1812                 break;
1813             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1814                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1815                 channel->state = L2CAP_STATE_INVALID;
1816                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1817                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
1818                 break;
1819             default:
1820                 break;
1821         }
1822     }
1823 }
1824 #endif
1825 
1826 // MARK: L2CAP_RUN
1827 // process outstanding signaling tasks
1828 static void l2cap_run(void){
1829 
1830     // log_info("l2cap_run: entered");
1831     l2cap_run_signaling_response();
1832 
1833 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1834     bool done = l2ap_run_ertm();
1835     if (done) return;
1836 #endif
1837 
1838 #if defined(ENABLE_CLASSIC) || defined(ENABLE_BLE)
1839     btstack_linked_list_iterator_t it;
1840 #endif
1841 
1842 #ifdef ENABLE_CLASSIC
1843     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1844     while (btstack_linked_list_iterator_has_next(&it)){
1845 
1846         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1847 
1848         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CLASSIC) continue;
1849 
1850         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1851         bool finalized = l2cap_run_for_classic_channel(channel);
1852 
1853         if (!finalized) {
1854 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1855             l2cap_run_for_classic_channel_ertm(channel);
1856 #endif
1857         }
1858     }
1859 #endif
1860 
1861 #ifdef ENABLE_LE_DATA_CHANNELS
1862     l2cap_run_le_data_channels();
1863 #endif
1864 
1865 #ifdef ENABLE_BLE
1866     // send l2cap con paramter update if necessary
1867     hci_connections_get_iterator(&it);
1868     while(btstack_linked_list_iterator_has_next(&it)){
1869         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1870         if ((connection->address_type != BD_ADDR_TYPE_LE_PUBLIC) && (connection->address_type != BD_ADDR_TYPE_LE_RANDOM)) continue;
1871         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
1872         switch (connection->le_con_parameter_update_state){
1873             case CON_PARAMETER_UPDATE_SEND_REQUEST:
1874                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1875                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, l2cap_next_sig_id(),
1876                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
1877                 break;
1878             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
1879                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
1880                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
1881                 break;
1882             case CON_PARAMETER_UPDATE_DENY:
1883                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1884                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
1885                 break;
1886             default:
1887                 break;
1888         }
1889     }
1890 #endif
1891 
1892     // log_info("l2cap_run: exit");
1893 }
1894 
1895 #ifdef ENABLE_CLASSIC
1896 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
1897     if ((channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE) || (channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION)) {
1898         log_info("connection complete con_handle %04x - for channel %p cid 0x%04x", (int) con_handle, channel, channel->local_cid);
1899         // success, start l2cap handshake
1900         channel->con_handle = con_handle;
1901         // check remote SSP feature first
1902         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
1903     }
1904 }
1905 
1906 static void l2cap_ready_to_connect(l2cap_channel_t * channel){
1907 
1908 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1909     // assumption: outgoing connection
1910     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
1911     if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
1912         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
1913         channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
1914         return;
1915     }
1916 #endif
1917 
1918     // fine, go ahead
1919     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
1920 }
1921 
1922 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
1923     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
1924 
1925     // we have been waiting for remote supported features
1926     if (channel->required_security_level > LEVEL_0){
1927         // request security level
1928         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
1929         gap_request_security_level(channel->con_handle, channel->required_security_level);
1930         return;
1931     }
1932 
1933     l2cap_ready_to_connect(channel);
1934 }
1935 #endif
1936 
1937 #ifdef L2CAP_USES_CHANNELS
1938 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,
1939     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
1940 
1941     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1942     if (!channel) {
1943         return NULL;
1944     }
1945 
1946     // fill in
1947     channel->packet_handler = packet_handler;
1948     channel->channel_type   = channel_type;
1949     bd_addr_copy(channel->address, address);
1950     channel->address_type = address_type;
1951     channel->psm = psm;
1952     channel->local_mtu  = local_mtu;
1953     channel->remote_mtu = L2CAP_DEFAULT_MTU;
1954     channel->required_security_level = security_level;
1955 
1956     //
1957     channel->local_cid = l2cap_next_local_cid();
1958     channel->con_handle = HCI_CON_HANDLE_INVALID;
1959 
1960     // set initial state
1961     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
1962     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
1963     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
1964     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
1965 
1966     log_info("create channel %p, local_cid 0x%04x", channel, channel->local_cid);
1967 
1968     return channel;
1969 }
1970 
1971 static void l2cap_free_channel_entry(l2cap_channel_t * channel){
1972     log_info("free channel %p, local_cid 0x%04x", channel, channel->local_cid);
1973     // assert all timers are stopped
1974     l2cap_stop_rtx(channel);
1975 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1976     l2cap_ertm_stop_retransmission_timer(channel);
1977     l2cap_ertm_stop_monitor_timer(channel);
1978 #endif
1979     // free  memory
1980     btstack_memory_l2cap_channel_free(channel);
1981 }
1982 #endif
1983 
1984 #ifdef ENABLE_CLASSIC
1985 
1986 /**
1987  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
1988  * @param packet_handler
1989  * @param address
1990  * @param psm
1991  * @param mtu
1992  * @param local_cid
1993  */
1994 
1995 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){
1996     // limit MTU to the size of our outgoing HCI buffer
1997     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1998 
1999 	// determine security level based on psm
2000 	const gap_security_level_t security_level = l2cap_security_level_0_allowed_for_PSM(psm) ? LEVEL_0 : gap_get_security_level();
2001 	log_info("L2CAP_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);
2002 
2003     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);
2004     if (!channel) {
2005         return BTSTACK_MEMORY_ALLOC_FAILED;
2006     }
2007 
2008 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2009     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2010 #endif
2011 
2012     // add to connections list
2013     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2014 
2015     // store local_cid
2016     if (out_local_cid){
2017        *out_local_cid = channel->local_cid;
2018     }
2019 
2020 	// state: L2CAP_STATE_WILL_SEND_CREATE_CONNECTION
2021 
2022     // check if hci connection is already usable,
2023     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
2024     if (conn && conn->con_handle != HCI_CON_HANDLE_INVALID){
2025     	// simulate connection complete
2026 	    l2cap_handle_connection_complete(conn->con_handle, channel);
2027 
2028 		// state: L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES
2029 
2030         // check if remote supported features are already received
2031         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
2032         	// simulate remote features received
2033             l2cap_handle_remote_supported_features_received(channel);
2034         }
2035     }
2036 
2037     l2cap_run();
2038 
2039     return ERROR_CODE_SUCCESS;
2040 }
2041 
2042 void l2cap_disconnect(uint16_t local_cid, uint8_t reason){
2043     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
2044     // find channel for local_cid
2045     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2046     if (channel) {
2047         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2048     }
2049     // process
2050     l2cap_run();
2051 }
2052 
2053 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
2054     // mark all channels before emitting open events as these could trigger new connetion requests to the same device
2055     btstack_linked_list_iterator_t it;
2056     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2057     while (btstack_linked_list_iterator_has_next(&it)){
2058         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2059         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2060         if (bd_addr_cmp( channel->address, address) != 0) continue;
2061         // channel for this address found
2062         switch (channel->state){
2063             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2064             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2065                 channel->state = L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD;
2066                 break;
2067             default:
2068                 break;
2069         }
2070     }
2071     // emit and free marked entries. restart loop to deal with list changes
2072     int done = 0;
2073     while (!done) {
2074         done = 1;
2075         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2076         while (btstack_linked_list_iterator_has_next(&it)){
2077             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2078             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2079             if (channel->state == L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD){
2080                 done = 0;
2081                 // failure, forward error code
2082                 l2cap_handle_channel_open_failed(channel, status);
2083                 // discard channel
2084                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2085                 l2cap_free_channel_entry(channel);
2086                 break;
2087             }
2088         }
2089     }
2090 
2091 }
2092 
2093 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
2094     btstack_linked_list_iterator_t it;
2095     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2096     while (btstack_linked_list_iterator_has_next(&it)){
2097         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2098         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2099         if ( ! bd_addr_cmp( channel->address, address) ){
2100             l2cap_handle_connection_complete(handle, channel);
2101         }
2102     }
2103     // process
2104     l2cap_run();
2105 }
2106 #endif
2107 
2108 static bool l2cap_channel_ready_to_send(l2cap_channel_t * channel){
2109     switch (channel->channel_type){
2110 #ifdef ENABLE_CLASSIC
2111         case L2CAP_CHANNEL_TYPE_CLASSIC:
2112 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2113             // send if we have more data and remote windows isn't full yet
2114             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2115                 if (channel->unacked_frames >= btstack_min(channel->num_stored_tx_frames, channel->remote_tx_window_size)) return false;
2116                 return hci_can_send_acl_classic_packet_now() != 0;
2117             }
2118 #endif
2119             if (!channel->waiting_for_can_send_now) return false;
2120             return (hci_can_send_acl_classic_packet_now() != 0);
2121         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2122             if (!channel->waiting_for_can_send_now) return false;
2123             return hci_can_send_acl_classic_packet_now() != 0;
2124 #endif
2125 #ifdef ENABLE_BLE
2126         case L2CAP_CHANNEL_TYPE_LE_FIXED:
2127             if (!channel->waiting_for_can_send_now) return false;
2128             return hci_can_send_acl_le_packet_now() != 0;
2129 #ifdef ENABLE_LE_DATA_CHANNELS
2130         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
2131             if (channel->send_sdu_buffer == NULL) return false;
2132             if (channel->credits_outgoing == 0u) return false;
2133             return hci_can_send_acl_le_packet_now() != 0;
2134 #endif
2135 #endif
2136         default:
2137             return false;
2138     }
2139 }
2140 
2141 static void l2cap_channel_trigger_send(l2cap_channel_t * channel){
2142     switch (channel->channel_type){
2143 #ifdef ENABLE_CLASSIC
2144         case L2CAP_CHANNEL_TYPE_CLASSIC:
2145 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2146             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2147                 l2cap_ertm_channel_send_information_frame(channel);
2148                 return;
2149             }
2150 #endif
2151             channel->waiting_for_can_send_now = 0;
2152             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2153             break;
2154         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2155             channel->waiting_for_can_send_now = 0;
2156             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2157             break;
2158 #endif
2159 #ifdef ENABLE_BLE
2160         case L2CAP_CHANNEL_TYPE_LE_FIXED:
2161             channel->waiting_for_can_send_now = 0;
2162             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2163             break;
2164 #ifdef ENABLE_LE_DATA_CHANNELS
2165         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
2166             l2cap_le_send_pdu(channel);
2167             break;
2168 #endif
2169 #endif
2170         default:
2171             break;
2172     }
2173 }
2174 
2175 static void l2cap_notify_channel_can_send(void){
2176     bool done = false;
2177     while (!done){
2178         done = true;
2179         btstack_linked_list_iterator_t it;
2180         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2181         while (btstack_linked_list_iterator_has_next(&it)){
2182             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2183             bool ready = l2cap_channel_ready_to_send(channel);
2184             if (!ready) continue;
2185 
2186             // requeue channel for fairness
2187             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2188             btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2189 
2190             // trigger sending
2191             l2cap_channel_trigger_send(channel);
2192 
2193             // exit inner loop as we just broke the iterator, but try again
2194             done = false;
2195             break;
2196         }
2197     }
2198 }
2199 
2200 #ifdef L2CAP_USES_CHANNELS
2201 
2202 static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){
2203     // open cannot fail for for incoming connections
2204     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0;
2205 
2206     // check state
2207     switch (channel->state){
2208         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2209         case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2210         case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES:
2211         case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2212         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
2213         case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES:
2214         case L2CAP_STATE_WAIT_CONNECT_RSP:
2215         case L2CAP_STATE_CONFIG:
2216         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
2217         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
2218         case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE:
2219         case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD:
2220             return 1;
2221 
2222         case L2CAP_STATE_OPEN:
2223         case L2CAP_STATE_CLOSED:
2224         case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES:
2225         case L2CAP_STATE_WAIT_DISCONNECT:
2226         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY:
2227         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
2228         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
2229         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2230         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
2231         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
2232         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
2233         case L2CAP_STATE_INVALID:
2234         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2235             return 0;
2236 
2237         default:
2238             // get a "warning" about new states
2239             btstack_assert(false);
2240             return 0;
2241     }
2242 }
2243 #endif
2244 
2245 #ifdef ENABLE_CLASSIC
2246 static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){
2247     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2248         l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2249     } else {
2250         l2cap_handle_channel_closed(channel);
2251     }
2252     l2cap_free_channel_entry(channel);
2253 }
2254 #endif
2255 
2256 #ifdef ENABLE_LE_DATA_CHANNELS
2257 static void l2cap_handle_hci_le_disconnect_event(l2cap_channel_t * channel){
2258     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2259         l2cap_emit_le_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2260     } else {
2261         l2cap_emit_le_channel_closed(channel);
2262     }
2263     l2cap_free_channel_entry(channel);
2264 }
2265 #endif
2266 
2267 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
2268 
2269     UNUSED(packet_type); // ok: registered with hci_event_callback_registration
2270     UNUSED(cid);         // ok: there is no channel
2271     UNUSED(size);        // ok: fixed format events read from HCI buffer
2272 
2273 #ifdef ENABLE_CLASSIC
2274     bd_addr_t address;
2275     hci_connection_t * hci_connection;
2276     int hci_con_used;
2277 #endif
2278 #ifdef L2CAP_USES_CHANNELS
2279     hci_con_handle_t handle;
2280     btstack_linked_list_iterator_t it;
2281 #endif
2282 
2283     switch(hci_event_packet_get_type(packet)){
2284 
2285         // Notify channel packet handler if they can send now
2286         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2287         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
2288         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
2289             l2cap_run();    // try sending signaling packets first
2290             l2cap_notify_channel_can_send();
2291             break;
2292 
2293         case HCI_EVENT_COMMAND_STATUS:
2294 #ifdef ENABLE_CLASSIC
2295             // check command status for create connection for errors
2296             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
2297                 // cache outgoing address and reset
2298                 (void)memcpy(address, l2cap_outgoing_classic_addr, 6);
2299                 memset(l2cap_outgoing_classic_addr, 0, 6);
2300                 // error => outgoing connection failed
2301                 uint8_t status = hci_event_command_status_get_status(packet);
2302                 if (status){
2303                     l2cap_handle_connection_failed_for_addr(address, status);
2304                 }
2305             }
2306 #endif
2307             l2cap_run();    // try sending signaling packets first
2308             break;
2309 
2310 #ifdef ENABLE_CLASSIC
2311         // handle connection complete events
2312         case HCI_EVENT_CONNECTION_COMPLETE:
2313             reverse_bd_addr(&packet[5], address);
2314             if (packet[2] == 0){
2315                 handle = little_endian_read_16(packet, 3);
2316                 l2cap_handle_connection_success_for_addr(address, handle);
2317             } else {
2318                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
2319             }
2320             break;
2321 
2322         // handle successful create connection cancel command
2323         case HCI_EVENT_COMMAND_COMPLETE:
2324             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
2325                 if (packet[5] == 0){
2326                     reverse_bd_addr(&packet[6], address);
2327                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
2328                     l2cap_handle_connection_failed_for_addr(address, 0x16);
2329                 }
2330             }
2331             l2cap_run();    // try sending signaling packets first
2332             break;
2333 #endif
2334 
2335 #ifdef L2CAP_USES_CHANNELS
2336         // handle disconnection complete events
2337         case HCI_EVENT_DISCONNECTION_COMPLETE:
2338             handle = little_endian_read_16(packet, 3);
2339             // send l2cap open failed or closed events for all channels on this handle and free them
2340             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2341             while (btstack_linked_list_iterator_has_next(&it)){
2342                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2343                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2344                 if (channel->con_handle != handle) continue;
2345                 btstack_linked_list_iterator_remove(&it);
2346                 switch(channel->channel_type){
2347 #ifdef ENABLE_CLASSIC
2348                     case L2CAP_CHANNEL_TYPE_CLASSIC:
2349                         l2cap_handle_hci_disconnect_event(channel);
2350                         break;
2351 #endif
2352 #ifdef ENABLE_LE_DATA_CHANNELS
2353                     case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
2354                         l2cap_handle_hci_le_disconnect_event(channel);
2355                         break;
2356 #endif
2357                     default:
2358                         break;
2359                 }
2360             }
2361             break;
2362 #endif
2363 
2364 
2365         // HCI Connection Timeouts
2366 #ifdef ENABLE_CLASSIC
2367         case L2CAP_EVENT_TIMEOUT_CHECK:
2368             handle = little_endian_read_16(packet, 2);
2369             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
2370             if (hci_authentication_active_for_handle(handle)) break;
2371             hci_con_used = 0;
2372             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2373             while (btstack_linked_list_iterator_has_next(&it)){
2374                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2375                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2376                 if (channel->con_handle != handle) continue;
2377                 hci_con_used = 1;
2378                 break;
2379             }
2380             if (hci_con_used) break;
2381             if (!hci_can_send_command_packet_now()) break;
2382             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
2383             break;
2384 
2385         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2386         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
2387             handle = little_endian_read_16(packet, 3);
2388             hci_connection = hci_connection_for_handle(handle);
2389             if (hci_connection == NULL) break;
2390             if ((hci_connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) == 0) break;
2391             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2392             while (btstack_linked_list_iterator_has_next(&it)){
2393                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2394                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2395                 if (channel->con_handle != handle) continue;
2396                 log_info("remote supported features, channel %p, cid %04x - state %u", channel, channel->local_cid, channel->state);
2397                 l2cap_handle_remote_supported_features_received(channel);
2398             }
2399             break;
2400 
2401         case GAP_EVENT_SECURITY_LEVEL:
2402             handle = little_endian_read_16(packet, 2);
2403             log_info("l2cap - security level update for handle 0x%04x", handle);
2404             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2405             while (btstack_linked_list_iterator_has_next(&it)){
2406                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2407                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2408                 if (channel->con_handle != handle) continue;
2409 
2410                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
2411                 gap_security_level_t required_level = channel->required_security_level;
2412 
2413                 log_info("channel %p, cid %04x - state %u: actual %u >= required %u?", channel, channel->local_cid, channel->state, actual_level, required_level);
2414 
2415                 switch (channel->state){
2416                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2417                         if (actual_level >= required_level){
2418 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2419                             // we need to know if ERTM is supported before sending a config response
2420                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
2421                             if (connection->l2cap_state.information_state != L2CAP_INFORMATION_STATE_DONE){
2422                                 connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2423                                 channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
2424                                 break;
2425                             }
2426 #endif
2427                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2428                             l2cap_emit_incoming_connection(channel);
2429                         } else {
2430                             channel->reason = 0x0003; // security block
2431                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2432                         }
2433                         break;
2434 
2435                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2436                         if (actual_level >= required_level){
2437                             l2cap_ready_to_connect(channel);
2438                         } else {
2439                             // disconnnect, authentication not good enough
2440                             hci_disconnect_security_block(handle);
2441                         }
2442                         break;
2443 
2444                     default:
2445                         break;
2446                 }
2447             }
2448             break;
2449 #endif
2450 
2451         default:
2452             break;
2453     }
2454 
2455     l2cap_run();
2456 }
2457 
2458 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t cid, uint16_t data){
2459     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused."
2460     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
2461         signaling_responses[signaling_responses_pending].handle = handle;
2462         signaling_responses[signaling_responses_pending].code = code;
2463         signaling_responses[signaling_responses_pending].sig_id = sig_id;
2464         signaling_responses[signaling_responses_pending].cid = cid;
2465         signaling_responses[signaling_responses_pending].data = data;
2466         signaling_responses_pending++;
2467         l2cap_run();
2468     }
2469 }
2470 
2471 #ifdef ENABLE_CLASSIC
2472 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
2473     channel->remote_sig_id = identifier;
2474     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
2475     l2cap_run();
2476 }
2477 
2478 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
2479 
2480     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
2481     l2cap_service_t *service = l2cap_get_service(psm);
2482     if (!service) {
2483         // 0x0002 PSM not supported
2484         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2485         return;
2486     }
2487 
2488     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
2489     if (!hci_connection) {
2490         //
2491         log_error("no hci_connection for handle %u", handle);
2492         return;
2493     }
2494 
2495     // alloc structure
2496     // log_info("l2cap_handle_connection_request register channel");
2497     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, hci_connection->address, BD_ADDR_TYPE_ACL,
2498     psm, service->mtu, service->required_security_level);
2499     if (!channel){
2500         // 0x0004 No resources available
2501         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2502         return;
2503     }
2504 
2505     channel->con_handle = handle;
2506     channel->remote_cid = source_cid;
2507     channel->remote_sig_id = sig_id;
2508 
2509     // limit local mtu to max acl packet length - l2cap header
2510     if (channel->local_mtu > l2cap_max_mtu()) {
2511         channel->local_mtu = l2cap_max_mtu();
2512     }
2513 
2514     // set initial state
2515     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
2516     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
2517 
2518     // add to connections list
2519     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2520 
2521     // assert security requirements
2522     gap_request_security_level(handle, channel->required_security_level);
2523 }
2524 
2525 void l2cap_accept_connection(uint16_t local_cid){
2526     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
2527     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2528     if (!channel) {
2529         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
2530         return;
2531     }
2532 
2533 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2534     // configure L2CAP Basic mode
2535     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
2536 #endif
2537 
2538     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
2539 
2540     // process
2541     l2cap_run();
2542 }
2543 
2544 void l2cap_decline_connection(uint16_t local_cid){
2545     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
2546     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
2547     if (!channel) {
2548         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
2549         return;
2550     }
2551     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2552     channel->reason = 0x04; // no resources available
2553     l2cap_run();
2554 }
2555 
2556 // @pre command len is valid, see check in l2cap_signaling_handler_channel
2557 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
2558 
2559 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2560     uint8_t use_fcs = 1;
2561 #endif
2562 
2563     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2564 
2565     uint16_t flags = little_endian_read_16(command, 6);
2566     if (flags & 1) {
2567         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
2568     }
2569 
2570     // accept the other's configuration options
2571     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2572     uint16_t pos     = 8;
2573     while (pos < end_pos){
2574         uint8_t option_hint = command[pos] >> 7;
2575         uint8_t option_type = command[pos] & 0x7f;
2576         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
2577         pos++;
2578         uint8_t length = command[pos++];
2579         // MTU { type(8): 1, len(8):2, MTU(16) }
2580         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) && (length == 2)){
2581             channel->remote_mtu = little_endian_read_16(command, pos);
2582             log_info("Remote MTU %u", channel->remote_mtu);
2583             if (channel->remote_mtu > l2cap_max_mtu()){
2584                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
2585                 channel->remote_mtu = l2cap_max_mtu();
2586             }
2587             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
2588         }
2589         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
2590         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT) && (length == 2)){
2591             channel->flush_timeout = little_endian_read_16(command, pos);
2592             log_info("Flush timeout: %u ms", channel->flush_timeout);
2593         }
2594 
2595 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2596         // Retransmission and Flow Control Option
2597         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2598             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
2599             switch(channel->mode){
2600                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2601                     // Store remote config
2602                     channel->remote_tx_window_size = command[pos+1];
2603                     channel->remote_max_transmit   = command[pos+2];
2604                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
2605                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
2606                     channel->remote_mps = little_endian_read_16(command, pos + 7);
2607                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
2608                         channel->remote_tx_window_size,
2609                         channel->remote_max_transmit,
2610                         channel->remote_retransmission_timeout_ms,
2611                         channel->remote_monitor_timeout_ms,
2612                         channel->remote_mps);
2613                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
2614                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
2615                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2616                     } else {
2617                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2618                     }
2619                     break;
2620                 case L2CAP_CHANNEL_MODE_BASIC:
2621                     switch (mode){
2622                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2623                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
2624                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
2625                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2626                             }
2627                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
2628                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
2629                             break;
2630                         default: // case L2CAP_CHANNEL_MODE_BASIC:
2631                             // TODO store and evaluate configuration
2632                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2633                             break;
2634                     }
2635                     break;
2636                 default:
2637                     break;
2638             }
2639         }
2640         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
2641             use_fcs = command[pos];
2642         }
2643 #endif
2644         // check for unknown options
2645         if ((option_hint == 0) && ((option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) || (option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE))){
2646             log_info("l2cap cid %u, unknown options", channel->local_cid);
2647             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
2648         }
2649         pos += length;
2650     }
2651 
2652 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2653         // "FCS" has precedence over "No FCS"
2654         uint8_t update = channel->fcs_option || use_fcs;
2655         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
2656         channel->fcs_option = update;
2657         // If ERTM mandatory, but remote didn't send Retransmission and Flowcontrol options -> disconnect
2658         if (((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM) == 0) & (channel->ertm_mandatory)){
2659             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2660         }
2661 #endif
2662 }
2663 
2664 // @pre command len is valid, see check in l2cap_signaling_handler_channel
2665 static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
2666     log_info("l2cap_signaling_handle_configure_response");
2667 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2668     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2669     uint16_t pos     = 10;
2670     while (pos < end_pos){
2671         uint8_t option_hint = command[pos] >> 7;
2672         uint8_t option_type = command[pos] & 0x7f;
2673         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
2674         pos++;
2675         uint8_t length = command[pos++];
2676 
2677         // Retransmission and Flow Control Option
2678         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2679             switch (channel->mode){
2680                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2681                     if (channel->ertm_mandatory){
2682                         // ??
2683                     } else {
2684                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
2685                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2686                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
2687                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2688                         }
2689                     }
2690                     break;
2691                 case L2CAP_CHANNEL_MODE_BASIC:
2692                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2693                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
2694                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2695                     }
2696                     break;
2697                 default:
2698                     break;
2699             }
2700         }
2701 
2702         // check for unknown options
2703         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
2704             log_info("l2cap cid %u, unknown options", channel->local_cid);
2705             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
2706         }
2707 
2708         pos += length;
2709     }
2710 #else
2711     UNUSED(channel);  // ok: no code
2712     UNUSED(result);   // ok: no code
2713     UNUSED(command);  // ok: no code
2714 #endif
2715 }
2716 
2717 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
2718     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
2719     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
2720     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
2721     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
2722     if (channel->state == L2CAP_STATE_OPEN) return 0;
2723     return 1;
2724 }
2725 
2726 
2727 // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
2728 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
2729 
2730     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2731     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2732     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2733     uint16_t result = 0;
2734 
2735     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
2736 
2737     // handle DISCONNECT REQUESTS seperately
2738     if (code == DISCONNECTION_REQUEST){
2739         switch (channel->state){
2740             case L2CAP_STATE_CONFIG:
2741             case L2CAP_STATE_OPEN:
2742             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2743             case L2CAP_STATE_WAIT_DISCONNECT:
2744                 l2cap_handle_disconnect_request(channel, identifier);
2745                 break;
2746 
2747             default:
2748                 // ignore in other states
2749                 break;
2750         }
2751         return;
2752     }
2753 
2754     // @STATEMACHINE(l2cap)
2755     switch (channel->state) {
2756 
2757         case L2CAP_STATE_WAIT_CONNECT_RSP:
2758             switch (code){
2759                 case CONNECTION_RESPONSE:
2760                     if (cmd_len < 8){
2761                         // command imcomplete
2762                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2763                         break;
2764                     }
2765                     l2cap_stop_rtx(channel);
2766                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2767                     switch (result) {
2768                         case 0:
2769                             // successful connection
2770                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2771                             channel->state = L2CAP_STATE_CONFIG;
2772                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2773                             break;
2774                         case 1:
2775                             // connection pending. get some coffee, but start the ERTX
2776                             l2cap_start_ertx(channel);
2777                             break;
2778                         default:
2779                             // channel closed
2780                             channel->state = L2CAP_STATE_CLOSED;
2781                             // map l2cap connection response result to BTstack status enumeration
2782                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
2783 
2784                             // drop link key if security block
2785                             if ((L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result) == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
2786                                 gap_drop_link_key_for_bd_addr(channel->address);
2787                             }
2788 
2789                             // discard channel
2790                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2791                             l2cap_free_channel_entry(channel);
2792                             break;
2793                     }
2794                     break;
2795 
2796                 default:
2797                     //@TODO: implement other signaling packets
2798                     break;
2799             }
2800             break;
2801 
2802         case L2CAP_STATE_CONFIG:
2803             switch (code) {
2804                 case CONFIGURE_REQUEST:
2805                     if (cmd_len < 4){
2806                         // command incomplete
2807                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2808                         break;
2809                     }
2810                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
2811                     l2cap_signaling_handle_configure_request(channel, command);
2812                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
2813                         // only done if continuation not set
2814                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
2815                     }
2816                     break;
2817                 case CONFIGURE_RESPONSE:
2818                     if (cmd_len < 6){
2819                         // command incomplete
2820                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2821                         break;
2822                     }
2823                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2824                     l2cap_stop_rtx(channel);
2825                     l2cap_signaling_handle_configure_response(channel, result, command);
2826                     switch (result){
2827                         case 0: // success
2828                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
2829                             break;
2830                         case 4: // pending
2831                             l2cap_start_ertx(channel);
2832                             break;
2833                         default:
2834 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2835                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
2836                                 // remote does not offer ertm but it's required
2837                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2838                                 break;
2839                             }
2840 #endif
2841                             // retry on negative result
2842                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2843                             break;
2844                     }
2845                     break;
2846                 default:
2847                     break;
2848             }
2849             if (l2cap_channel_ready_for_open(channel)){
2850 
2851 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2852                 // assert that packet can be stored in fragment buffers in ertm
2853                 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
2854                     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
2855                     uint16_t usable_mtu = channel->num_tx_buffers == 1 ? effective_mps : channel->num_tx_buffers * effective_mps - 2;
2856                     if (usable_mtu < channel->remote_mtu){
2857                         log_info("Remote MTU %u > max storable ERTM packet, only using MTU = %u", channel->remote_mtu, usable_mtu);
2858                         channel->remote_mtu = usable_mtu;
2859                     }
2860                 }
2861 #endif
2862                 // for open:
2863                 channel->state = L2CAP_STATE_OPEN;
2864                 l2cap_emit_channel_opened(channel, 0);
2865             }
2866             break;
2867 
2868         case L2CAP_STATE_WAIT_DISCONNECT:
2869             switch (code) {
2870                 case DISCONNECTION_RESPONSE:
2871                     l2cap_finialize_channel_close(channel);
2872                     break;
2873                 default:
2874                     //@TODO: implement other signaling packets
2875                     break;
2876             }
2877             break;
2878 
2879         case L2CAP_STATE_CLOSED:
2880             // @TODO handle incoming requests
2881             break;
2882 
2883         case L2CAP_STATE_OPEN:
2884             //@TODO: implement other signaling packets, e.g. re-configure
2885             break;
2886         default:
2887             break;
2888     }
2889     // log_info("new state %u", channel->state);
2890 }
2891 
2892 
2893 // @pre command len is valid, see check in l2cap_acl_classic_handler
2894 static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
2895 
2896     btstack_linked_list_iterator_t it;
2897 
2898     // get code, signalind identifier and command len
2899     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2900     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2901     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2902 
2903     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
2904     if ((code < 1) || (code == ECHO_RESPONSE) || (code > INFORMATION_RESPONSE)){
2905         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2906         return;
2907     }
2908 
2909     // general commands without an assigned channel
2910     switch(code) {
2911 
2912         case CONNECTION_REQUEST:
2913             if (cmd_len == 4){
2914                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2915                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
2916                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
2917             } else {
2918                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2919             }
2920             return;
2921 
2922         case ECHO_REQUEST:
2923             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
2924             return;
2925 
2926         case INFORMATION_REQUEST:
2927             if (cmd_len == 2) {
2928                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2929                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
2930             } else {
2931                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2932             }
2933             return;
2934 
2935 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2936         case INFORMATION_RESPONSE: {
2937             hci_connection_t * connection = hci_connection_for_handle(handle);
2938             if (!connection) return;
2939             if (connection->l2cap_state.information_state != L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE) return;
2940 
2941             // get extended features from response if valid
2942             connection->l2cap_state.extended_feature_mask = 0;
2943             if (cmd_len >= 6) {
2944                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2945                 uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
2946                 if (result == 0 && info_type == L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) {
2947                     connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2948                 }
2949             }
2950             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
2951             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
2952 
2953             // trigger connection request
2954             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2955             while (btstack_linked_list_iterator_has_next(&it)){
2956                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2957                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2958                 if (channel->con_handle != handle) continue;
2959 
2960                 // incoming connection: ask user for channel configuration, esp. if ertm will be mandatory
2961                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
2962                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2963                     l2cap_emit_incoming_connection(channel);
2964                     continue;
2965                 }
2966 
2967                 // outgoing connection
2968                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
2969 
2970                     // if ERTM was requested, but is not listed in extended feature mask:
2971                     if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2972 
2973                         if (channel->ertm_mandatory){
2974                             // bail if ERTM is mandatory
2975                             channel->state = L2CAP_STATE_CLOSED;
2976                             // map l2cap connection response result to BTstack status enumeration
2977                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
2978                             // discard channel
2979                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2980                             l2cap_free_channel_entry(channel);
2981                             continue;
2982 
2983                         } else {
2984                             // fallback to Basic mode
2985                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
2986                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2987                         }
2988                     }
2989 
2990                     // respond to connection request
2991                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
2992                     continue;
2993                 }
2994             }
2995             return;
2996         }
2997 #endif
2998 
2999         default:
3000             break;
3001     }
3002 
3003     // Get potential destination CID
3004     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3005 
3006     // Find channel for this sig_id and connection handle
3007     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3008     while (btstack_linked_list_iterator_has_next(&it)){
3009         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3010         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3011         if (channel->con_handle != handle) continue;
3012         if (code & 1) {
3013             // match odd commands (responses) by previous signaling identifier
3014             if (channel->local_sig_id == sig_id) {
3015                 l2cap_signaling_handler_channel(channel, command);
3016                 break;
3017             }
3018         } else {
3019             // match even commands (requests) by local channel id
3020             if (channel->local_cid == dest_cid) {
3021                 l2cap_signaling_handler_channel(channel, command);
3022                 break;
3023             }
3024         }
3025     }
3026 }
3027 #endif
3028 
3029 #ifdef ENABLE_BLE
3030 
3031 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
3032     uint8_t event[6];
3033     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
3034     event[1] = 4;
3035     little_endian_store_16(event, 2, con_handle);
3036     little_endian_store_16(event, 4, result);
3037     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3038     if (!l2cap_event_packet_handler) return;
3039     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
3040 }
3041 
3042 // @returns valid
3043 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
3044     hci_connection_t * connection;
3045     uint16_t result;
3046     uint8_t  event[12];
3047 
3048 #ifdef ENABLE_LE_DATA_CHANNELS
3049     btstack_linked_list_iterator_t it;
3050     l2cap_channel_t * channel;
3051     uint16_t local_cid;
3052     uint16_t le_psm;
3053     uint16_t new_credits;
3054     uint16_t credits_before;
3055     l2cap_service_t * service;
3056     uint16_t source_cid;
3057 #endif
3058 
3059     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3060     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3061     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
3062 
3063     switch (code){
3064 
3065         case CONNECTION_PARAMETER_UPDATE_REQUEST:
3066             // check size
3067             if (len < 8u) return 0u;
3068             connection = hci_connection_for_handle(handle);
3069             if (connection){
3070                 if (connection->role != HCI_ROLE_MASTER){
3071                     // reject command without notifying upper layer when not in master role
3072                     return 0;
3073                 }
3074                 le_connection_parameter_range_t existing_range;
3075                 gap_get_connection_parameter_range(&existing_range);
3076                 uint16_t le_conn_interval_min   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3077                 uint16_t le_conn_interval_max   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3078                 uint16_t le_conn_latency        = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3079                 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
3080 
3081                 int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
3082                 if (update_parameter){
3083                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
3084                     connection->le_conn_interval_min = le_conn_interval_min;
3085                     connection->le_conn_interval_max = le_conn_interval_max;
3086                     connection->le_conn_latency = le_conn_latency;
3087                     connection->le_supervision_timeout = le_supervision_timeout;
3088                 } else {
3089                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
3090                 }
3091                 connection->le_con_param_update_identifier = sig_id;
3092             }
3093 
3094             if (!l2cap_event_packet_handler) break;
3095 
3096             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
3097             event[1] = 8;
3098             little_endian_store_16(event, 2, handle);
3099             (void)memcpy(&event[4], &command[4], 8);
3100             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3101             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
3102             break;
3103 
3104         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
3105             // check size
3106             if (len < 2u) return 0u;
3107             result = little_endian_read_16(command, 4);
3108             l2cap_emit_connection_parameter_update_response(handle, result);
3109             break;
3110 
3111 #ifdef ENABLE_LE_DATA_CHANNELS
3112 
3113         case COMMAND_REJECT:
3114             // Find channel for this sig_id and connection handle
3115             channel = NULL;
3116             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3117             while (btstack_linked_list_iterator_has_next(&it)){
3118                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3119                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
3120                 if (a_channel->con_handle   != handle) continue;
3121                 if (a_channel->local_sig_id != sig_id) continue;
3122                 channel = a_channel;
3123                 break;
3124             }
3125             if (!channel) break;
3126 
3127             // if received while waiting for le connection response, assume legacy device
3128             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
3129                 channel->state = L2CAP_STATE_CLOSED;
3130                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
3131                 l2cap_emit_le_channel_opened(channel, 0x0002);
3132 
3133                 // discard channel
3134                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3135                 l2cap_free_channel_entry(channel);
3136                 break;
3137             }
3138             break;
3139 
3140         case LE_CREDIT_BASED_CONNECTION_REQUEST:
3141             // check size
3142             if (len < 10u) return 0u;
3143 
3144             // get hci connection, bail if not found (must not happen)
3145             connection = hci_connection_for_handle(handle);
3146             if (!connection) return 0;
3147 
3148             // check if service registered
3149             le_psm  = little_endian_read_16(command, 4);
3150             service = l2cap_le_get_service(le_psm);
3151             source_cid = little_endian_read_16(command, 6);
3152 
3153             if (service){
3154                 if (source_cid < 0x40u){
3155                     // 0x0009 Connection refused - Invalid Source CID
3156                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
3157                     return 1;
3158                 }
3159 
3160                 // go through list of channels for this ACL connection and check if we get a match
3161                 btstack_linked_list_iterator_init(&it, &l2cap_channels);
3162                 while (btstack_linked_list_iterator_has_next(&it)){
3163                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3164                     if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
3165                     if (a_channel->con_handle != handle) continue;
3166                     if (a_channel->remote_cid != source_cid) continue;
3167                     // 0x000a Connection refused - Source CID already allocated
3168                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
3169                     return 1;
3170                 }
3171 
3172                 // security: check encryption
3173                 if (service->required_security_level >= LEVEL_2){
3174                     if (gap_encryption_key_size(handle) == 0){
3175                         // 0x0008 Connection refused - insufficient encryption
3176                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
3177                         return 1;
3178                     }
3179                     // anything less than 16 byte key size is insufficient
3180                     if (gap_encryption_key_size(handle) < 16){
3181                         // 0x0007 Connection refused – insufficient encryption key size
3182                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
3183                         return 1;
3184                     }
3185                 }
3186 
3187                 // security: check authencation
3188                 if (service->required_security_level >= LEVEL_3){
3189                     if (!gap_authenticated(handle)){
3190                         // 0x0005 Connection refused – insufficient authentication
3191                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
3192                         return 1;
3193                     }
3194                 }
3195 
3196                 // security: check authorization
3197                 if (service->required_security_level >= LEVEL_4){
3198                     if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
3199                         // 0x0006 Connection refused – insufficient authorization
3200                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
3201                         return 1;
3202                     }
3203                 }
3204 
3205                 // allocate channel
3206                 channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL, connection->address,
3207                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
3208                 if (!channel){
3209                     // 0x0004 Connection refused – no resources available
3210                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
3211                     return 1;
3212                 }
3213 
3214                 channel->con_handle = handle;
3215                 channel->remote_cid = source_cid;
3216                 channel->remote_sig_id = sig_id;
3217                 channel->remote_mtu = little_endian_read_16(command, 8);
3218                 channel->remote_mps = little_endian_read_16(command, 10);
3219                 channel->credits_outgoing = little_endian_read_16(command, 12);
3220 
3221                 // set initial state
3222                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
3223                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
3224 
3225                 // add to connections list
3226                 btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
3227 
3228                 // post connection request event
3229                 l2cap_emit_le_incoming_connection(channel);
3230 
3231             } else {
3232                 // Connection refused – LE_PSM not supported
3233                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
3234             }
3235             break;
3236 
3237         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
3238             // check size
3239             if (len < 10u) return 0u;
3240 
3241             // Find channel for this sig_id and connection handle
3242             channel = NULL;
3243             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3244             while (btstack_linked_list_iterator_has_next(&it)){
3245                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3246                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
3247                 if (a_channel->con_handle   != handle) continue;
3248                 if (a_channel->local_sig_id != sig_id) continue;
3249                 channel = a_channel;
3250                 break;
3251             }
3252             if (!channel) break;
3253 
3254             // cid + 0
3255             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
3256             if (result){
3257                 channel->state = L2CAP_STATE_CLOSED;
3258                 // map l2cap connection response result to BTstack status enumeration
3259                 l2cap_emit_le_channel_opened(channel, result);
3260 
3261                 // discard channel
3262                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3263                 l2cap_free_channel_entry(channel);
3264                 break;
3265             }
3266 
3267             // success
3268             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3269             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3270             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3271             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
3272             channel->state = L2CAP_STATE_OPEN;
3273             l2cap_emit_le_channel_opened(channel, result);
3274             break;
3275 
3276         case LE_FLOW_CONTROL_CREDIT:
3277             // check size
3278             if (len < 4u) return 0u;
3279 
3280             // find channel
3281             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3282             channel = l2cap_get_channel_for_local_cid(local_cid);
3283             if (!channel) {
3284                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
3285                 break;
3286             }
3287             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3288             credits_before = channel->credits_outgoing;
3289             channel->credits_outgoing += new_credits;
3290             // check for credit overrun
3291             if (credits_before > channel->credits_outgoing){
3292                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
3293                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3294                 break;
3295             }
3296             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
3297             break;
3298 
3299         case DISCONNECTION_REQUEST:
3300 
3301             // check size
3302             if (len < 4u) return 0u;
3303 
3304             // find channel
3305             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3306             channel = l2cap_get_channel_for_local_cid(local_cid);
3307             if (!channel) {
3308                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
3309                 break;
3310             }
3311             channel->remote_sig_id = sig_id;
3312             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
3313             break;
3314 
3315 #endif
3316 
3317         case DISCONNECTION_RESPONSE:
3318             break;
3319 
3320         default:
3321             // command unknown -> reject command
3322             return 0;
3323     }
3324     return 1;
3325 }
3326 #endif
3327 
3328 #ifdef ENABLE_CLASSIC
3329 static void l2cap_acl_classic_handler_for_channel(l2cap_channel_t * l2cap_channel, uint8_t * packet, uint16_t size){
3330 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3331     if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3332 
3333         int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
3334 
3335         // assert control + FCS fields are inside
3336         if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) return;
3337 
3338         if (l2cap_channel->fcs_option){
3339             // verify FCS (required if one side requested it)
3340             uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
3341             uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
3342 
3343 #ifdef L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL
3344             // simulate fcs error
3345                         static int counter = 0;
3346                         if (++counter == L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL) {
3347                             log_info("Simulate fcs error");
3348                             fcs_calculated++;
3349                             counter = 0;
3350                         }
3351 #endif
3352 
3353             if (fcs_calculated == fcs_packet){
3354                 log_info("Packet FCS 0x%04x verified", fcs_packet);
3355             } else {
3356                 log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
3357                 // ERTM State Machine in Bluetooth Spec does not handle 'I-Frame with invalid FCS'
3358                 return;
3359             }
3360         }
3361 
3362         // switch on packet type
3363         uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3364         uint8_t  req_seq = (control >> 8) & 0x3f;
3365         int final = (control >> 7) & 0x01;
3366         if (control & 1){
3367             // S-Frame
3368             int poll  = (control >> 4) & 0x01;
3369             l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
3370             log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
3371             l2cap_ertm_tx_packet_state_t * tx_state;
3372             switch (s){
3373                 case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
3374                     log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
3375                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3376                     if (poll && final){
3377                         // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
3378                         log_error("P=F=1 in S-Frame");
3379                         break;
3380                     }
3381                     if (poll){
3382                         // check if we did request selective retransmission before <==> we have stored SDU segments
3383                         int i;
3384                         int num_stored_out_of_order_packets = 0;
3385                         for (i=0;i<l2cap_channel->num_rx_buffers;i++){
3386                             int index = l2cap_channel->rx_store_index + i;
3387                             if (index >= l2cap_channel->num_rx_buffers){
3388                                 index -= l2cap_channel->num_rx_buffers;
3389                             }
3390                             l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3391                             if (!rx_state->valid) continue;
3392                             num_stored_out_of_order_packets++;
3393                         }
3394                         if (num_stored_out_of_order_packets){
3395                             l2cap_channel->send_supervisor_frame_selective_reject = 1;
3396                         } else {
3397                             l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
3398                         }
3399                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
3400                     }
3401                     if (final){
3402                         // Stop-MonitorTimer
3403                         l2cap_ertm_stop_monitor_timer(l2cap_channel);
3404                         // If UnackedFrames > 0 then Start-RetransTimer
3405                         if (l2cap_channel->unacked_frames){
3406                             l2cap_ertm_start_retransmission_timer(l2cap_channel);
3407                         }
3408                         // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3409                         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
3410                     }
3411                     break;
3412                 case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
3413                     log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
3414                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3415                     // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
3416                     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
3417                     break;
3418                 case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
3419                     log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
3420                     break;
3421                 case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
3422                     log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
3423                     if (poll){
3424                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3425                     }
3426                     // find requested i-frame
3427                     tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
3428                     if (tx_state){
3429                         log_info("Retransmission for tx_seq %u requested", req_seq);
3430                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
3431                         tx_state->retransmission_requested = 1;
3432                         l2cap_channel->srej_active = 1;
3433                     }
3434                     break;
3435                 default:
3436                     break;
3437             }
3438         } else {
3439             // I-Frame
3440             // get control
3441             l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
3442             uint8_t tx_seq = (control >> 1) & 0x3f;
3443             log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
3444             log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
3445             log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
3446             l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3447             if (final){
3448                 // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3449                 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
3450             }
3451 
3452             // get SDU
3453             const uint8_t * payload_data = &packet[COMPLETE_L2CAP_HEADER+2];
3454             uint16_t        payload_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
3455 
3456             // assert SDU size is smaller or equal to our buffers
3457             uint16_t max_payload_size = 0;
3458             switch (sar){
3459                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
3460                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
3461                     // SDU Length + MPS
3462                     max_payload_size = l2cap_channel->local_mps + 2;
3463                     break;
3464                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
3465                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
3466                     max_payload_size = l2cap_channel->local_mps;
3467                     break;
3468                 default:
3469                     btstack_assert(false);
3470                     break;
3471             }
3472             if (payload_len > max_payload_size){
3473                 log_info("payload len %u > max payload %u -> drop packet", payload_len, max_payload_size);
3474                 return;
3475             }
3476 
3477             // check ordering
3478             if (l2cap_channel->expected_tx_seq == tx_seq){
3479                 log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
3480                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3481                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3482 
3483                 // process SDU
3484                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, payload_data, payload_len);
3485 
3486                 // process stored segments
3487                 while (true){
3488                     int index = l2cap_channel->rx_store_index;
3489                     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3490                     if (!rx_state->valid) break;
3491 
3492                     log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
3493                     l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3494                     l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3495 
3496                     rx_state->valid = 0;
3497                     l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
3498 
3499                     // update rx store index
3500                     index++;
3501                     if (index >= l2cap_channel->num_rx_buffers){
3502                         index = 0;
3503                     }
3504                     l2cap_channel->rx_store_index = index;
3505                 }
3506 
3507                 //
3508                 l2cap_channel->send_supervisor_frame_receiver_ready = 1;
3509 
3510             } else {
3511                 int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
3512                 if (delta < 2){
3513                     // store segment
3514                     l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, payload_data, payload_len);
3515 
3516                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
3517                     l2cap_channel->send_supervisor_frame_selective_reject = 1;
3518                 } else {
3519                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
3520                     l2cap_channel->send_supervisor_frame_reject = 1;
3521                 }
3522             }
3523         }
3524         return;
3525     }
3526 #endif
3527     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3528 
3529 }
3530 #endif
3531 
3532 static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3533 #ifdef ENABLE_CLASSIC
3534     l2cap_channel_t * l2cap_channel;
3535     l2cap_fixed_channel_t * l2cap_fixed_channel;
3536 
3537     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3538     switch (channel_id) {
3539 
3540         case L2CAP_CID_SIGNALING: {
3541             uint32_t command_offset = 8;
3542             while ((command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET) < size) {
3543                 // assert signaling command is fully inside packet
3544                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3545                 uint32_t next_command_offset = command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
3546                 if (next_command_offset > size){
3547                     log_error("l2cap signaling command len invalid -> drop");
3548                     break;
3549                 }
3550                 // handle signaling command
3551                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
3552                 // go to next command
3553                 command_offset = next_command_offset;
3554             }
3555             break;
3556         }
3557         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
3558             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL);
3559             if (!l2cap_fixed_channel) break;
3560             if (!l2cap_fixed_channel->packet_handler) break;
3561             (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3562             break;
3563 
3564         default:
3565             // Find channel for this channel_id and connection handle
3566             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
3567             if (l2cap_channel) {
3568                 l2cap_acl_classic_handler_for_channel(l2cap_channel, packet, size);
3569             }
3570             break;
3571     }
3572 #else
3573     UNUSED(handle); // ok: no code
3574     UNUSED(packet); // ok: no code
3575     UNUSED(size);   // ok: no code
3576 #endif
3577 }
3578 
3579 static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3580 #ifdef ENABLE_BLE
3581 
3582     l2cap_fixed_channel_t * l2cap_fixed_channel;
3583 
3584 #ifdef ENABLE_LE_DATA_CHANNELS
3585     l2cap_channel_t * l2cap_channel;
3586 #endif
3587     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3588     switch (channel_id) {
3589 
3590         case L2CAP_CID_SIGNALING_LE: {
3591             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
3592             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
3593             if ((COMPLETE_L2CAP_HEADER + 4u + len) > size) break;
3594             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
3595             if (!valid){
3596                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3597             }
3598             break;
3599         }
3600 
3601         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
3602             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL);
3603             if (!l2cap_fixed_channel) break;
3604             if (!l2cap_fixed_channel->packet_handler) break;
3605             (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3606             break;
3607 
3608         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
3609             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
3610             if (!l2cap_fixed_channel) break;
3611             if (!l2cap_fixed_channel->packet_handler) break;
3612             (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3613             break;
3614 
3615         default:
3616 
3617 #ifdef ENABLE_LE_DATA_CHANNELS
3618             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
3619             if (l2cap_channel) {
3620                 // credit counting
3621                 if (l2cap_channel->credits_incoming == 0u){
3622                     log_error("LE Data Channel packet received but no incoming credits");
3623                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3624                     break;
3625                 }
3626                 l2cap_channel->credits_incoming--;
3627 
3628                 // automatic credits
3629                 if ((l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK) && l2cap_channel->automatic_credits){
3630                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
3631                 }
3632 
3633                 // first fragment
3634                 uint16_t pos = 0;
3635                 if (!l2cap_channel->receive_sdu_len){
3636                     uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3637                     if(sdu_len > l2cap_channel->local_mtu) break;   // SDU would be larger than our buffer
3638                     l2cap_channel->receive_sdu_len = sdu_len;
3639                     l2cap_channel->receive_sdu_pos = 0;
3640                     pos  += 2u;
3641                     size -= 2u;
3642                 }
3643                 uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
3644                 uint16_t remaining_space = l2cap_channel->local_mtu - l2cap_channel->receive_sdu_pos;
3645                 if (fragment_size > remaining_space) break;         // SDU would cause buffer overrun
3646                 (void)memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos],
3647                              &packet[COMPLETE_L2CAP_HEADER + pos],
3648                              fragment_size);
3649                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
3650                 // done?
3651                 log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
3652                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
3653                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
3654                     l2cap_channel->receive_sdu_len = 0;
3655                 }
3656             } else {
3657                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
3658             }
3659 #endif
3660             break;
3661     }
3662 #else
3663     UNUSED(handle); // ok: no code
3664     UNUSED(packet); // ok: no code
3665     UNUSED(size);   // ok: no code
3666 #endif
3667 }
3668 
3669 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
3670     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
3671     UNUSED(channel);        // ok: there is no channel
3672 
3673     // Assert full L2CAP header present
3674     if (size < COMPLETE_L2CAP_HEADER) return;
3675 
3676     // Dispatch to Classic or LE handler (SCO packets are not dispatched to L2CAP)
3677     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
3678     hci_connection_t *conn = hci_connection_for_handle(handle);
3679     if (!conn) return;
3680     if (conn->address_type == BD_ADDR_TYPE_ACL){
3681         l2cap_acl_classic_handler(handle, packet, size);
3682     } else {
3683         l2cap_acl_le_handler(handle, packet, size);
3684     }
3685 
3686     l2cap_run();
3687 }
3688 
3689 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
3690 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
3691     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
3692     if (!channel) return;
3693     channel->packet_handler = the_packet_handler;
3694 }
3695 
3696 #ifdef ENABLE_CLASSIC
3697 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
3698 void l2cap_finialize_channel_close(l2cap_channel_t * channel){
3699     channel->state = L2CAP_STATE_CLOSED;
3700     l2cap_handle_channel_closed(channel);
3701     // discard channel
3702     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3703     l2cap_free_channel_entry(channel);
3704 }
3705 #endif
3706 
3707 #ifdef L2CAP_USES_CHANNELS
3708 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3709     btstack_linked_list_iterator_t it;
3710     btstack_linked_list_iterator_init(&it, services);
3711     while (btstack_linked_list_iterator_has_next(&it)){
3712         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
3713         if ( service->psm == psm){
3714             return service;
3715         };
3716     }
3717     return NULL;
3718 }
3719 #endif
3720 
3721 #ifdef ENABLE_CLASSIC
3722 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
3723     return l2cap_get_service_internal(&l2cap_services, psm);
3724 }
3725 
3726 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
3727 
3728     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
3729 
3730     // check for alread registered psm
3731     l2cap_service_t *service = l2cap_get_service(psm);
3732     if (service) {
3733         log_error("l2cap_register_service: PSM %u already registered", psm);
3734         return L2CAP_SERVICE_ALREADY_REGISTERED;
3735     }
3736 
3737     // alloc structure
3738     service = btstack_memory_l2cap_service_get();
3739     if (!service) {
3740         log_error("l2cap_register_service: no memory for l2cap_service_t");
3741         return BTSTACK_MEMORY_ALLOC_FAILED;
3742     }
3743 
3744     // fill in
3745     service->psm = psm;
3746     service->mtu = mtu;
3747     service->packet_handler = service_packet_handler;
3748     service->required_security_level = security_level;
3749 
3750     // add to services list
3751     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
3752 
3753     // enable page scan
3754     gap_connectable_control(1);
3755 
3756     return ERROR_CODE_SUCCESS;
3757 }
3758 
3759 uint8_t l2cap_unregister_service(uint16_t psm){
3760 
3761     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
3762 
3763     l2cap_service_t *service = l2cap_get_service(psm);
3764     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3765     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
3766     btstack_memory_l2cap_service_free(service);
3767 
3768     // disable page scan when no services registered
3769     if (btstack_linked_list_empty(&l2cap_services)) {
3770         gap_connectable_control(0);
3771     }
3772     return ERROR_CODE_SUCCESS;
3773 }
3774 #endif
3775 
3776 
3777 #ifdef ENABLE_LE_DATA_CHANNELS
3778 
3779 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
3780     if (!channel->waiting_for_can_send_now) return;
3781     if (channel->send_sdu_buffer) return;
3782     channel->waiting_for_can_send_now = 0;
3783     log_debug("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
3784     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
3785 }
3786 
3787 // 1BH2222
3788 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
3789     log_info("L2CAP_EVENT_LE_INCOMING_CONNECTION addr_type %u, addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x, remote_mtu %u",
3790              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
3791     uint8_t event[19];
3792     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
3793     event[1] = sizeof(event) - 2u;
3794     event[2] = channel->address_type;
3795     reverse_bd_addr(channel->address, &event[3]);
3796     little_endian_store_16(event,  9, channel->con_handle);
3797     little_endian_store_16(event, 11, channel->psm);
3798     little_endian_store_16(event, 13, channel->local_cid);
3799     little_endian_store_16(event, 15, channel->remote_cid);
3800     little_endian_store_16(event, 17, channel->remote_mtu);
3801     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3802     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3803 }
3804 // 11BH22222
3805 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
3806     log_info("L2CAP_EVENT_LE_CHANNEL_OPENED 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",
3807              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
3808              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
3809     uint8_t event[23];
3810     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
3811     event[1] = sizeof(event) - 2u;
3812     event[2] = status;
3813     event[3] = channel->address_type;
3814     reverse_bd_addr(channel->address, &event[4]);
3815     little_endian_store_16(event, 10, channel->con_handle);
3816     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
3817     little_endian_store_16(event, 13, channel->psm);
3818     little_endian_store_16(event, 15, channel->local_cid);
3819     little_endian_store_16(event, 17, channel->remote_cid);
3820     little_endian_store_16(event, 19, channel->local_mtu);
3821     little_endian_store_16(event, 21, channel->remote_mtu);
3822     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3823     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3824 }
3825 // 2
3826 static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel){
3827     log_info("L2CAP_EVENT_LE_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
3828     uint8_t event[4];
3829     event[0] = L2CAP_EVENT_LE_CHANNEL_CLOSED;
3830     event[1] = sizeof(event) - 2u;
3831     little_endian_store_16(event, 2, channel->local_cid);
3832     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3833     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3834 }
3835 
3836 static void l2cap_le_send_pdu(l2cap_channel_t *channel){
3837     btstack_assert(channel != NULL);
3838     btstack_assert(channel->send_sdu_buffer != NULL);
3839     btstack_assert(channel->credits_outgoing > 0);
3840 
3841     // send part of SDU
3842     hci_reserve_packet_buffer();
3843     uint8_t * acl_buffer = hci_get_outgoing_packet_buffer();
3844     uint8_t * l2cap_payload = acl_buffer + 8;
3845     uint16_t pos = 0;
3846     if (!channel->send_sdu_pos){
3847         // store SDU len
3848         channel->send_sdu_pos += 2u;
3849         little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
3850         pos += 2u;
3851     }
3852     uint16_t payload_size = btstack_min(channel->send_sdu_len + 2u - channel->send_sdu_pos, channel->remote_mps - pos);
3853     log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
3854     (void)memcpy(&l2cap_payload[pos],
3855                  &channel->send_sdu_buffer[channel->send_sdu_pos - 2u],
3856                  payload_size); // -2 for virtual SDU len
3857     pos += payload_size;
3858     channel->send_sdu_pos += payload_size;
3859     l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
3860 
3861     channel->credits_outgoing--;
3862 
3863     hci_send_acl_packet_buffer(8u + pos);
3864 
3865     if (channel->send_sdu_pos >= (channel->send_sdu_len + 2u)){
3866         channel->send_sdu_buffer = NULL;
3867         // send done event
3868         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
3869         // inform about can send now
3870         l2cap_le_notify_channel_can_send(channel);
3871     }
3872 }
3873 
3874 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
3875 void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
3876     channel->state = L2CAP_STATE_CLOSED;
3877     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
3878     // discard channel
3879     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3880     l2cap_free_channel_entry(channel);
3881 }
3882 
3883 static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
3884     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
3885 }
3886 
3887 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
3888 
3889     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
3890 
3891     // check for alread registered psm
3892     l2cap_service_t *service = l2cap_le_get_service(psm);
3893     if (service) {
3894         return L2CAP_SERVICE_ALREADY_REGISTERED;
3895     }
3896 
3897     // alloc structure
3898     service = btstack_memory_l2cap_service_get();
3899     if (!service) {
3900         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
3901         return BTSTACK_MEMORY_ALLOC_FAILED;
3902     }
3903 
3904     // fill in
3905     service->psm = psm;
3906     service->mtu = 0;
3907     service->packet_handler = packet_handler;
3908     service->required_security_level = security_level;
3909 
3910     // add to services list
3911     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
3912 
3913     // done
3914     return ERROR_CODE_SUCCESS;
3915 }
3916 
3917 uint8_t l2cap_le_unregister_service(uint16_t psm) {
3918     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
3919     l2cap_service_t *service = l2cap_le_get_service(psm);
3920     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3921 
3922     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
3923     btstack_memory_l2cap_service_free(service);
3924     return ERROR_CODE_SUCCESS;
3925 }
3926 
3927 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
3928     // get channel
3929     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3930     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3931 
3932     // validate state
3933     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3934         return ERROR_CODE_COMMAND_DISALLOWED;
3935     }
3936 
3937     // set state accept connection
3938     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
3939     channel->receive_sdu_buffer = receive_sdu_buffer;
3940     channel->local_mtu = mtu;
3941     channel->new_credits_incoming = initial_credits;
3942     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
3943 
3944     // test
3945     // channel->new_credits_incoming = 1;
3946 
3947     // go
3948     l2cap_run();
3949     return ERROR_CODE_SUCCESS;
3950 }
3951 
3952 /**
3953  * @brief Deny incoming LE Data Channel connection due to resource constraints
3954  * @param local_cid             L2CAP LE Data Channel Identifier
3955  */
3956 
3957 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
3958     // get channel
3959     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3960     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3961 
3962     // validate state
3963     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3964         return ERROR_CODE_COMMAND_DISALLOWED;
3965     }
3966 
3967     // set state decline connection
3968     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
3969     channel->reason = 0x04; // no resources available
3970     l2cap_run();
3971     return ERROR_CODE_SUCCESS;
3972 }
3973 
3974 static gap_security_level_t l2cap_le_security_level_for_connection(hci_con_handle_t con_handle){
3975     uint8_t encryption_key_size = gap_encryption_key_size(con_handle);
3976     if (encryption_key_size == 0) return LEVEL_0;
3977 
3978     uint8_t authenticated = gap_authenticated(con_handle);
3979     if (!authenticated) return LEVEL_2;
3980 
3981     return encryption_key_size == 16 ? LEVEL_4 : LEVEL_3;
3982 }
3983 
3984 // used to handle pairing complete after triggering to increase
3985 static void l2cap_sm_packet_handler(uint8_t packet_type, uint16_t channel_nr, uint8_t *packet, uint16_t size) {
3986     UNUSED(channel_nr);
3987     UNUSED(size);
3988     UNUSED(packet_type);
3989     btstack_assert(packet_type = HCI_EVENT_PACKET);
3990     if (hci_event_packet_get_type(packet) != SM_EVENT_PAIRING_COMPLETE) return;
3991     hci_con_handle_t con_handle = sm_event_pairing_complete_get_handle(packet);
3992     btstack_linked_list_iterator_t it;
3993     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3994     while (btstack_linked_list_iterator_has_next(&it)) {
3995         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3996         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3997         if (channel->con_handle != con_handle) continue;
3998         if (channel->state != L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE) continue;
3999 
4000         // found channel, check security level
4001         if (l2cap_le_security_level_for_connection(con_handle) < channel->required_security_level){
4002             // pairing failed or wasn't good enough, inform user
4003             l2cap_emit_le_channel_opened(channel, ERROR_CODE_INSUFFICIENT_SECURITY);
4004             // discard channel
4005             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4006             l2cap_free_channel_entry(channel);
4007         } else {
4008             // send conn request now
4009             channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
4010             l2cap_run();
4011         }
4012     }
4013 }
4014 
4015 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
4016     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
4017     uint16_t * out_local_cid) {
4018 
4019     static btstack_packet_callback_registration_t sm_event_callback_registration;
4020     static bool sm_callback_registered = false;
4021 
4022     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
4023 
4024     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4025     if (!connection) {
4026         log_error("no hci_connection for handle 0x%04x", con_handle);
4027         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4028     }
4029 
4030     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL, connection->address, connection->address_type, psm, mtu, security_level);
4031     if (!channel) {
4032         return BTSTACK_MEMORY_ALLOC_FAILED;
4033     }
4034     log_info("l2cap_le_create_channel %p", channel);
4035 
4036     // store local_cid
4037     if (out_local_cid){
4038        *out_local_cid = channel->local_cid;
4039     }
4040 
4041     // setup channel entry
4042     channel->con_handle = con_handle;
4043     channel->receive_sdu_buffer = receive_sdu_buffer;
4044     channel->new_credits_incoming = initial_credits;
4045     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
4046 
4047     // add to connections list
4048     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
4049 
4050     // check security level
4051     if (l2cap_le_security_level_for_connection(con_handle) < channel->required_security_level){
4052         if (!sm_callback_registered){
4053             sm_callback_registered = true;
4054             // lazy registration for SM events
4055             sm_event_callback_registration.callback = &l2cap_sm_packet_handler;
4056             sm_add_event_handler(&sm_event_callback_registration);
4057         }
4058 
4059         // start pairing
4060         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
4061         sm_request_pairing(con_handle);
4062     } else {
4063         // send conn request right away
4064         channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
4065         l2cap_run();
4066     }
4067 
4068     return ERROR_CODE_SUCCESS;
4069 }
4070 
4071 /**
4072  * @brief Provide credtis for LE Data Channel
4073  * @param local_cid             L2CAP LE Data Channel Identifier
4074  * @param credits               Number additional credits for peer
4075  */
4076 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
4077 
4078     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4079     if (!channel) {
4080         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
4081         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4082     }
4083 
4084     // check state
4085     if (channel->state != L2CAP_STATE_OPEN){
4086         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
4087     }
4088 
4089     // assert incoming credits + credits <= 0xffff
4090     uint32_t total_credits = channel->credits_incoming;
4091     total_credits += channel->new_credits_incoming;
4092     total_credits += credits;
4093     if (total_credits > 0xffffu){
4094         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
4095             channel->new_credits_incoming, credits);
4096     }
4097 
4098     // set credits_granted
4099     channel->new_credits_incoming += credits;
4100 
4101     // go
4102     l2cap_run();
4103     return ERROR_CODE_SUCCESS;
4104 }
4105 
4106 /**
4107  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
4108  * @param local_cid             L2CAP LE Data Channel Identifier
4109  */
4110 int l2cap_le_can_send_now(uint16_t local_cid){
4111     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4112     if (!channel) {
4113         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
4114         return 0;
4115     }
4116 
4117     // check state
4118     if (channel->state != L2CAP_STATE_OPEN) return 0;
4119 
4120     // check queue
4121     if (channel->send_sdu_buffer) return 0;
4122 
4123     // fine, go ahead
4124     return 1;
4125 }
4126 
4127 /**
4128  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
4129  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
4130  *       so packet handler should be ready to handle it
4131  * @param local_cid             L2CAP LE Data Channel Identifier
4132  */
4133 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
4134     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4135     if (!channel) {
4136         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
4137         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4138     }
4139     channel->waiting_for_can_send_now = 1;
4140     l2cap_le_notify_channel_can_send(channel);
4141     return ERROR_CODE_SUCCESS;
4142 }
4143 
4144 /**
4145  * @brief Send data via LE Data Channel
4146  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
4147  * @param local_cid             L2CAP LE Data Channel Identifier
4148  * @param data                  data to send
4149  * @param size                  data size
4150  */
4151 uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
4152 
4153     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4154     if (!channel) {
4155         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4156         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4157     }
4158 
4159     if (len > channel->remote_mtu){
4160         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
4161         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
4162     }
4163 
4164     if (channel->send_sdu_buffer){
4165         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
4166         return BTSTACK_ACL_BUFFERS_FULL;
4167     }
4168 
4169     channel->send_sdu_buffer = data;
4170     channel->send_sdu_len    = len;
4171     channel->send_sdu_pos    = 0;
4172 
4173     l2cap_notify_channel_can_send();
4174     return ERROR_CODE_SUCCESS;
4175 }
4176 
4177 /**
4178  * @brief Disconnect from LE Data Channel
4179  * @param local_cid             L2CAP LE Data Channel Identifier
4180  */
4181 uint8_t l2cap_le_disconnect(uint16_t local_cid)
4182 {
4183     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4184     if (!channel) {
4185         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4186         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4187     }
4188 
4189     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4190     l2cap_run();
4191     return ERROR_CODE_SUCCESS;
4192 }
4193 
4194 #endif
4195