xref: /btstack/src/l2cap.c (revision a0549bf12c828ca3e78481902bce3330c32aa70d)
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;
204 #endif
205 // next signaling sequence number
206 static uint8_t   sig_seq_nr;
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     local_source_cid  = 0x40;
877     sig_seq_nr  = 0xff;
878     l2cap_channels = NULL;
879 
880 #ifdef ENABLE_CLASSIC
881     l2cap_services = NULL;
882     require_security_level2_for_outgoing_sdp = 0;
883 
884     // Setup Connectionless Channel
885     l2cap_fixed_channel_connectionless.local_cid     = L2CAP_CID_CONNECTIONLESS_CHANNEL;
886     l2cap_fixed_channel_connectionless.channel_type  = L2CAP_CHANNEL_TYPE_CONNECTIONLESS;
887     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_connectionless);
888 #endif
889 
890 #ifdef ENABLE_LE_DATA_CHANNELS
891     l2cap_le_services = NULL;
892 #endif
893 
894 #ifdef ENABLE_BLE
895     l2cap_event_packet_handler = NULL;
896     l2cap_le_custom_max_mtu = 0;
897 
898     // Setup fixed ATT Channel
899     l2cap_fixed_channel_att.local_cid    = L2CAP_CID_ATTRIBUTE_PROTOCOL;
900     l2cap_fixed_channel_att.channel_type = L2CAP_CHANNEL_TYPE_LE_FIXED;
901     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_att);
902 
903     // Setup fixed SM Channel
904     l2cap_fixed_channel_sm.local_cid     = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
905     l2cap_fixed_channel_sm.channel_type  = L2CAP_CHANNEL_TYPE_LE_FIXED;
906     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_sm);
907 #endif
908 
909     //
910     // register callback with HCI
911     //
912     hci_event_callback_registration.callback = &l2cap_hci_event_handler;
913     hci_add_event_handler(&hci_event_callback_registration);
914 
915     hci_register_acl_packet_handler(&l2cap_acl_handler);
916 
917 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
918 #ifdef ENABLE_CLASSIC
919     gap_connectable_control(0); // no services yet
920 #endif
921 #endif
922 }
923 
924 /**
925  * @brief De-Init L2CAP
926  */
927 void l2cap_deinit(void){
928     memset(l2cap_outgoing_classic_addr, 0, 6);
929     signaling_responses_pending = 0;
930 }
931 
932 void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
933 #ifdef ENABLE_BLE
934     l2cap_event_packet_handler = handler;
935 #else
936     UNUSED(handler);    // ok: no code
937 #endif
938 }
939 
940 void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
941     UNUSED(con_handle);  // ok: there is no con handle
942 
943     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
944     if (!channel) return;
945     channel->waiting_for_can_send_now = 1;
946     l2cap_notify_channel_can_send();
947 }
948 
949 int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
950     UNUSED(channel_id); // ok: only depends on Controller LE buffers
951 
952     return hci_can_send_acl_packet_now(con_handle);
953 }
954 
955 uint8_t *l2cap_get_outgoing_buffer(void){
956     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
957 }
958 
959 // only for L2CAP Basic Channels
960 int l2cap_reserve_packet_buffer(void){
961     return hci_reserve_packet_buffer();
962 }
963 
964 // only for L2CAP Basic Channels
965 void l2cap_release_packet_buffer(void){
966     hci_release_packet_buffer();
967 }
968 
969 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){
970     // 0 - Connection handle : PB=pb : BC=00
971     little_endian_store_16(acl_buffer, 0u, con_handle | (packet_boundary << 12u) | (0u << 14u));
972     // 2 - ACL length
973     little_endian_store_16(acl_buffer, 2u,  len + 4u);
974     // 4 - L2CAP packet length
975     little_endian_store_16(acl_buffer, 4u,  len + 0u);
976     // 6 - L2CAP channel DEST
977     little_endian_store_16(acl_buffer, 6,  remote_cid);
978 }
979 
980 // assumption - only on LE connections
981 int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
982 
983     if (!hci_is_packet_buffer_reserved()){
984         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
985         return BTSTACK_ACL_BUFFERS_FULL;
986     }
987 
988     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
989         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
990         return BTSTACK_ACL_BUFFERS_FULL;
991     }
992 
993     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
994 
995     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
996     l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
997     // send
998     return hci_send_acl_packet_buffer(len+8u);
999 }
1000 
1001 // assumption - only on LE connections
1002 int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
1003 
1004     if (!hci_can_send_acl_packet_now(con_handle)){
1005         log_info("l2cap_send cid 0x%02x, cannot send", cid);
1006         return BTSTACK_ACL_BUFFERS_FULL;
1007     }
1008 
1009     hci_reserve_packet_buffer();
1010     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1011 
1012     (void)memcpy(&acl_buffer[8], data, len);
1013 
1014     return l2cap_send_prepared_connectionless(con_handle, cid, len);
1015 }
1016 
1017 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
1018     log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
1019     uint8_t event[4];
1020     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
1021     event[1] = sizeof(event) - 2u;
1022     little_endian_store_16(event, 2, channel);
1023     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1024     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
1025 }
1026 
1027 #ifdef L2CAP_USES_CHANNELS
1028 static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
1029     (* (channel->packet_handler))(type, channel->local_cid, data, size);
1030 }
1031 
1032 static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
1033     uint8_t event[4];
1034     event[0] = event_code;
1035     event[1] = sizeof(event) - 2u;
1036     little_endian_store_16(event, 2, channel->local_cid);
1037     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1038     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1039 }
1040 #endif
1041 
1042 #ifdef ENABLE_CLASSIC
1043 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
1044     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",
1045              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
1046              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
1047     uint8_t event[26];
1048     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
1049     event[1] = sizeof(event) - 2;
1050     event[2] = status;
1051     reverse_bd_addr(channel->address, &event[3]);
1052     little_endian_store_16(event,  9, channel->con_handle);
1053     little_endian_store_16(event, 11, channel->psm);
1054     little_endian_store_16(event, 13, channel->local_cid);
1055     little_endian_store_16(event, 15, channel->remote_cid);
1056     little_endian_store_16(event, 17, channel->local_mtu);
1057     little_endian_store_16(event, 19, channel->remote_mtu);
1058     little_endian_store_16(event, 21, channel->flush_timeout);
1059     event[23] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
1060 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1061     log_info("ERTM mode %u, fcs enabled %u", channel->mode, channel->fcs_option);
1062     event[24] = channel->mode;
1063     event[25] = channel->fcs_option;
1064 
1065 #else
1066     event[24] = L2CAP_CHANNEL_MODE_BASIC;
1067     event[25] = 0;
1068 #endif
1069     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1070     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1071 }
1072 
1073 static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
1074     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
1075     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
1076 }
1077 
1078 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
1079     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
1080              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
1081     uint8_t event[16];
1082     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
1083     event[1] = sizeof(event) - 2;
1084     reverse_bd_addr(channel->address, &event[2]);
1085     little_endian_store_16(event,  8, channel->con_handle);
1086     little_endian_store_16(event, 10, channel->psm);
1087     little_endian_store_16(event, 12, channel->local_cid);
1088     little_endian_store_16(event, 14, channel->remote_cid);
1089     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1090     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1091 }
1092 
1093 static void l2cap_handle_channel_open_failed(l2cap_channel_t * channel, uint8_t status){
1094 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1095     // emit ertm buffer released, as it's not needed. if in basic mode, it was either not allocated or already released
1096     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1097         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1098     }
1099 #endif
1100     l2cap_emit_channel_opened(channel, status);
1101 }
1102 
1103 static void l2cap_handle_channel_closed(l2cap_channel_t * channel){
1104 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1105     // emit ertm buffer released, as it's not needed anymore. if in basic mode, it was either not allocated or already released
1106     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1107         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1108     }
1109 #endif
1110     l2cap_emit_channel_closed(channel);
1111 }
1112 #endif
1113 
1114 static l2cap_fixed_channel_t * l2cap_channel_item_by_cid(uint16_t cid){
1115     btstack_linked_list_iterator_t it;
1116     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1117     while (btstack_linked_list_iterator_has_next(&it)){
1118         l2cap_fixed_channel_t * channel = (l2cap_fixed_channel_t*) btstack_linked_list_iterator_next(&it);
1119         if (channel->local_cid == cid) {
1120             return channel;
1121         }
1122     }
1123     return NULL;
1124 }
1125 
1126 // used for fixed channels in LE (ATT/SM) and Classic (Connectionless Channel). CID < 0x04
1127 static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid){
1128     if (local_cid >= 0x40u) return NULL;
1129     return (l2cap_fixed_channel_t*) l2cap_channel_item_by_cid(local_cid);
1130 }
1131 
1132 // used for Classic Channels + LE Data Channels. local_cid >= 0x40
1133 #ifdef L2CAP_USES_CHANNELS
1134 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
1135     if (local_cid < 0x40u) return NULL;
1136     return (l2cap_channel_t*) l2cap_channel_item_by_cid(local_cid);
1137 }
1138 
1139 static l2cap_channel_t * l2cap_get_channel_for_local_cid_and_handle(uint16_t local_cid, hci_con_handle_t con_handle){
1140     if (local_cid < 0x40u) return NULL;
1141     l2cap_channel_t * l2cap_channel = (l2cap_channel_t*) l2cap_channel_item_by_cid(local_cid);
1142     if (l2cap_channel == NULL)  return NULL;
1143     if (l2cap_channel->con_handle != con_handle) return NULL;
1144     return l2cap_channel;
1145 }
1146 
1147 void l2cap_request_can_send_now_event(uint16_t local_cid){
1148     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1149     if (!channel) return;
1150     channel->waiting_for_can_send_now = 1;
1151 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1152     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1153         l2cap_ertm_notify_channel_can_send(channel);
1154         return;
1155     }
1156 #endif
1157     l2cap_notify_channel_can_send();
1158 }
1159 
1160 int  l2cap_can_send_packet_now(uint16_t local_cid){
1161     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1162     if (!channel) return 0;
1163 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1164     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1165         return l2cap_ertm_can_store_packet_now(channel);
1166     }
1167 #endif
1168     return hci_can_send_acl_packet_now(channel->con_handle);
1169 }
1170 
1171 int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
1172     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1173     if (!channel) return 0;
1174 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1175     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1176         return 0;
1177     }
1178 #endif
1179     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
1180 }
1181 
1182 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
1183     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1184     if (channel) {
1185         return channel->remote_mtu;
1186     }
1187     return 0;
1188 }
1189 #endif
1190 
1191 #ifdef L2CAP_USES_CHANNELS
1192 static int l2cap_is_dynamic_channel_type(l2cap_channel_type_t channel_type){
1193     switch (channel_type){
1194         case L2CAP_CHANNEL_TYPE_CLASSIC:
1195         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
1196             return 1;
1197         default:
1198             return 0;
1199     }
1200 }
1201 #endif
1202 
1203 #ifdef ENABLE_CLASSIC
1204 // RTX Timer only exist for dynamic channels
1205 static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
1206     btstack_linked_list_iterator_t it;
1207     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1208     while (btstack_linked_list_iterator_has_next(&it)){
1209         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1210         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
1211         if (&channel->rtx == ts) {
1212             return channel;
1213         }
1214     }
1215     return NULL;
1216 }
1217 
1218 static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
1219     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
1220     if (!channel) return;
1221 
1222     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
1223 
1224     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
1225     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
1226     // notify client
1227     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
1228 
1229     // discard channel
1230     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1231     l2cap_free_channel_entry(channel);
1232 }
1233 
1234 #endif
1235 
1236 #ifdef L2CAP_USES_CHANNELS
1237 static void l2cap_stop_rtx(l2cap_channel_t * channel){
1238     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
1239     btstack_run_loop_remove_timer(&channel->rtx);
1240 }
1241 #endif
1242 
1243 #ifdef ENABLE_CLASSIC
1244 
1245 static void l2cap_start_rtx(l2cap_channel_t * channel){
1246     l2cap_stop_rtx(channel);
1247     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
1248     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1249     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
1250     btstack_run_loop_add_timer(&channel->rtx);
1251 }
1252 
1253 static void l2cap_start_ertx(l2cap_channel_t * channel){
1254     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
1255     l2cap_stop_rtx(channel);
1256     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1257     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
1258     btstack_run_loop_add_timer(&channel->rtx);
1259 }
1260 
1261 void l2cap_require_security_level_2_for_outgoing_sdp(void){
1262     require_security_level2_for_outgoing_sdp = 1;
1263 }
1264 
1265 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
1266     return (psm == BLUETOOTH_PSM_SDP) && (!require_security_level2_for_outgoing_sdp);
1267 }
1268 
1269 static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1270     if (!hci_can_send_acl_packet_now(handle)){
1271         log_info("l2cap_send_signaling_packet, cannot send");
1272         return BTSTACK_ACL_BUFFERS_FULL;
1273     }
1274 
1275     // log_info("l2cap_send_signaling_packet type %u", cmd);
1276     hci_reserve_packet_buffer();
1277     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1278     va_list argptr;
1279     va_start(argptr, identifier);
1280     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
1281     va_end(argptr);
1282     // log_info("l2cap_send_signaling_packet con %u!", handle);
1283     return hci_send_acl_packet_buffer(len);
1284 }
1285 
1286 // assumption - only on Classic connections
1287 // cannot be used for L2CAP ERTM
1288 int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
1289 
1290     if (!hci_is_packet_buffer_reserved()){
1291         log_error("l2cap_send_prepared called without reserving packet first");
1292         return BTSTACK_ACL_BUFFERS_FULL;
1293     }
1294 
1295     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1296     if (!channel) {
1297         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
1298         return -1;   // TODO: define error
1299     }
1300 
1301     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
1302         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
1303         return BTSTACK_ACL_BUFFERS_FULL;
1304     }
1305 
1306     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
1307 
1308     int fcs_size = 0;
1309 
1310 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1311     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->fcs_option){
1312         fcs_size = 2;
1313     }
1314 #endif
1315 
1316     // set non-flushable packet boundary flag if supported on Controller
1317     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1318     uint8_t packet_boundary_flag = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
1319     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
1320 
1321 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1322     if (fcs_size){
1323         // calculate FCS over l2cap data
1324         uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
1325         log_info("I-Frame: fcs 0x%04x", fcs);
1326         little_endian_store_16(acl_buffer, 8 + len, fcs);
1327     }
1328 #endif
1329 
1330     // send
1331     return hci_send_acl_packet_buffer(len+8+fcs_size);
1332 }
1333 
1334 // assumption - only on Classic connections
1335 int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
1336     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1337     if (!channel) {
1338         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
1339         return -1;   // TODO: define error
1340     }
1341 
1342 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1343     // send in ERTM
1344     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1345         return l2cap_ertm_send(channel, data, len);
1346     }
1347 #endif
1348 
1349     if (len > channel->remote_mtu){
1350         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
1351         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
1352     }
1353 
1354     if (!hci_can_send_acl_packet_now(channel->con_handle)){
1355         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
1356         return BTSTACK_ACL_BUFFERS_FULL;
1357     }
1358 
1359     hci_reserve_packet_buffer();
1360     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1361     (void)memcpy(&acl_buffer[8], data, len);
1362     return l2cap_send_prepared(local_cid, len);
1363 }
1364 
1365 int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
1366     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
1367 }
1368 
1369 static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
1370     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
1371 }
1372 
1373 static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
1374     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
1375 }
1376 #endif
1377 
1378 
1379 #ifdef ENABLE_BLE
1380 static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1381 
1382     if (!hci_can_send_acl_packet_now(handle)){
1383         log_info("l2cap_send_le_signaling_packet, cannot send");
1384         return BTSTACK_ACL_BUFFERS_FULL;
1385     }
1386 
1387     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
1388     hci_reserve_packet_buffer();
1389     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1390     va_list argptr;
1391     va_start(argptr, identifier);
1392     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
1393     va_end(argptr);
1394     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
1395     return hci_send_acl_packet_buffer(len);
1396 }
1397 #endif
1398 
1399 uint16_t l2cap_max_mtu(void){
1400     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
1401 }
1402 
1403 #ifdef ENABLE_BLE
1404 uint16_t l2cap_max_le_mtu(void){
1405     if (l2cap_le_custom_max_mtu != 0u) return l2cap_le_custom_max_mtu;
1406     return l2cap_max_mtu();
1407 }
1408 
1409 void l2cap_set_max_le_mtu(uint16_t max_mtu){
1410     if (max_mtu < l2cap_max_mtu()){
1411         l2cap_le_custom_max_mtu = max_mtu;
1412     }
1413 }
1414 #endif
1415 
1416 #ifdef ENABLE_CLASSIC
1417 
1418 static uint16_t l2cap_setup_options_mtu(uint8_t * config_options, uint16_t mtu){
1419     config_options[0] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
1420     config_options[1] = 2; // len param
1421     little_endian_store_16(config_options, 2, mtu);
1422     return 4;
1423 }
1424 
1425 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1426 static int l2cap_ertm_mode(l2cap_channel_t * channel){
1427     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
1428     return ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE)
1429         &&  (connection->l2cap_state.extended_feature_mask & 0x08));
1430 }
1431 #endif
1432 
1433 static uint16_t l2cap_setup_options_request(l2cap_channel_t * channel, uint8_t * config_options){
1434 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1435     // use ERTM options if supported by remote and channel ready to use it
1436     if (l2cap_ertm_mode(channel) && channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1437         return l2cap_setup_options_ertm_request(channel, config_options);
1438     }
1439 #endif
1440     uint16_t mtu = channel->local_mtu;
1441     return l2cap_setup_options_mtu(config_options, mtu);
1442 }
1443 
1444 static uint16_t l2cap_setup_options_mtu_response(l2cap_channel_t * channel, uint8_t * config_options){
1445     uint16_t mtu = btstack_min(channel->local_mtu, channel->remote_mtu);
1446     return l2cap_setup_options_mtu(config_options, mtu);
1447 }
1448 
1449 static uint32_t l2cap_extended_features_mask(void){
1450     // extended features request supported, features: fixed channels, unicast connectionless data reception
1451     uint32_t features = 0x280;
1452 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1453     features |= 0x0028;
1454 #endif
1455     return features;
1456 }
1457 #endif
1458 
1459 //
1460 #ifdef ENABLE_CLASSIC
1461 
1462 // returns true if channel was finalized
1463 static bool l2cap_run_for_classic_channel(l2cap_channel_t * channel){
1464 
1465 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1466     uint8_t  config_options[18];
1467 #else
1468     uint8_t  config_options[10];
1469 #endif
1470 
1471     switch (channel->state){
1472 
1473         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1474         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
1475             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1476             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
1477                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
1478                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
1479             }
1480             break;
1481 
1482         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1483             if (!hci_can_send_command_packet_now()) break;
1484             // send connection request - set state first
1485             channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
1486             // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
1487             (void)memcpy(l2cap_outgoing_classic_addr, channel->address, 6);
1488             hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_get_allow_role_switch());
1489             break;
1490 
1491         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
1492             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1493             channel->state = L2CAP_STATE_INVALID;
1494             l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
1495             // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1496             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1497             l2cap_free_channel_entry(channel);
1498             channel = NULL;
1499             break;
1500 
1501         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
1502             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1503             channel->state = L2CAP_STATE_CONFIG;
1504             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1505             l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
1506             break;
1507 
1508         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
1509             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1510             // success, start l2cap handshake
1511             channel->local_sig_id = l2cap_next_sig_id();
1512             channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
1513             l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
1514             l2cap_start_rtx(channel);
1515             break;
1516 
1517         case L2CAP_STATE_CONFIG:
1518             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1519 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1520             // fallback to basic mode if ERTM requested but not not supported by remote
1521             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1522                 if (!l2cap_ertm_mode(channel)){
1523                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1524                     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
1525                 }
1526             }
1527 #endif
1528             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
1529                 uint16_t flags = 0;
1530                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1531                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
1532                     flags = 1;
1533                 } else {
1534                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1535                 }
1536                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
1537                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1538                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS, 0, NULL);
1539 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1540                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
1541                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1542                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1543                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1544                     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);
1545                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM){
1546                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
1547                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1548                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1549                     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);
1550 #endif
1551                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
1552                     channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1553                     uint16_t options_size = l2cap_setup_options_mtu_response(channel, config_options);
1554                     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);
1555                 } else {
1556                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
1557                 }
1558                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1559             }
1560             else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
1561                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1562                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
1563                 channel->local_sig_id = l2cap_next_sig_id();
1564                 uint16_t options_size = l2cap_setup_options_request(channel, config_options);
1565                 l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options);
1566                 l2cap_start_rtx(channel);
1567             }
1568             if (l2cap_channel_ready_for_open(channel)){
1569                 channel->state = L2CAP_STATE_OPEN;
1570                 l2cap_emit_channel_opened(channel, 0);  // success
1571             }
1572             break;
1573 
1574         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1575             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1576             channel->state = L2CAP_STATE_INVALID;
1577             l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1578             // 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 :)
1579             l2cap_finialize_channel_close(channel);  // -- remove from list
1580             channel = NULL;
1581             break;
1582 
1583         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1584             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1585             channel->local_sig_id = l2cap_next_sig_id();
1586             channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1587             l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1588             break;
1589         default:
1590             break;
1591     }
1592 
1593     // handle channel finalize on L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE and L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE
1594     return channel == NULL;
1595 }
1596 
1597 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1598 static void l2cap_run_for_classic_channel_ertm(l2cap_channel_t * channel){
1599 
1600     // ERTM mode
1601     if (channel->mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) return;
1602 
1603     // check if we can still send
1604     if (channel->con_handle == HCI_CON_HANDLE_INVALID) return;
1605     if (!hci_can_send_acl_packet_now(channel->con_handle)) return;
1606 
1607     if (channel->send_supervisor_frame_receiver_ready){
1608         channel->send_supervisor_frame_receiver_ready = 0;
1609         log_info("Send S-Frame: RR %u, final %u", channel->req_seq, channel->set_final_bit_after_packet_with_poll_bit_set);
1610         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);
1611         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1612         l2cap_ertm_send_supervisor_frame(channel, control);
1613         return;
1614     }
1615     if (channel->send_supervisor_frame_receiver_ready_poll){
1616         channel->send_supervisor_frame_receiver_ready_poll = 0;
1617         log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
1618         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
1619         l2cap_ertm_send_supervisor_frame(channel, control);
1620         return;
1621     }
1622     if (channel->send_supervisor_frame_receiver_not_ready){
1623         channel->send_supervisor_frame_receiver_not_ready = 0;
1624         log_info("Send S-Frame: RNR %u", channel->req_seq);
1625         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
1626         l2cap_ertm_send_supervisor_frame(channel, control);
1627         return;
1628     }
1629     if (channel->send_supervisor_frame_reject){
1630         channel->send_supervisor_frame_reject = 0;
1631         log_info("Send S-Frame: REJ %u", channel->req_seq);
1632         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 0, 0, channel->req_seq);
1633         l2cap_ertm_send_supervisor_frame(channel, control);
1634         return;
1635     }
1636     if (channel->send_supervisor_frame_selective_reject){
1637         channel->send_supervisor_frame_selective_reject = 0;
1638         log_info("Send S-Frame: SREJ %u", channel->expected_tx_seq);
1639         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);
1640         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1641         l2cap_ertm_send_supervisor_frame(channel, control);
1642         return;
1643     }
1644 
1645     if (channel->srej_active){
1646         int i;
1647         for (i=0;i<channel->num_tx_buffers;i++){
1648             l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
1649             if (tx_state->retransmission_requested) {
1650                 tx_state->retransmission_requested = 0;
1651                 uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set;
1652                 channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1653                 l2cap_ertm_send_information_frame(channel, i, final);
1654                 break;
1655             }
1656         }
1657         if (i == channel->num_tx_buffers){
1658             // no retransmission request found
1659             channel->srej_active = 0;
1660         } else {
1661             // packet was sent
1662             return;
1663         }
1664     }
1665 }
1666 #endif /* ERTM */
1667 #endif /* Classic */
1668 
1669 static void l2cap_run_signaling_response(void) {
1670 
1671     // check pending signaling responses
1672     while (signaling_responses_pending){
1673 
1674         hci_con_handle_t handle = signaling_responses[0].handle;
1675 
1676         if (!hci_can_send_acl_packet_now(handle)) break;
1677 
1678         uint8_t  sig_id        = signaling_responses[0].sig_id;
1679         uint8_t  response_code = signaling_responses[0].code;
1680         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
1681 #ifdef ENABLE_CLASSIC
1682         uint16_t info_type     = signaling_responses[0].data;  // INFORMATION_REQUEST
1683         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
1684 #endif
1685 
1686         // remove first item before sending (to avoid sending response mutliple times)
1687         signaling_responses_pending--;
1688         int i;
1689         for (i=0; i < signaling_responses_pending; i++){
1690             (void)memcpy(&signaling_responses[i],
1691                          &signaling_responses[i + 1],
1692                          sizeof(l2cap_signaling_response_t));
1693         }
1694 
1695         switch (response_code){
1696 #ifdef ENABLE_CLASSIC
1697             case CONNECTION_REQUEST:
1698                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
1699                 // also disconnect if result is 0x0003 - security blocked
1700                 if (result == 0x0003){
1701                     hci_disconnect_security_block(handle);
1702                 }
1703                 break;
1704             case ECHO_REQUEST:
1705                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
1706                 break;
1707             case INFORMATION_REQUEST:
1708                 switch (info_type){
1709                     case L2CAP_INFO_TYPE_CONNECTIONLESS_MTU: {
1710                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
1711                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(connectionless_mtu), &connectionless_mtu);
1712                         }
1713                         break;
1714                     case L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED: {
1715                             uint32_t features = l2cap_extended_features_mask();
1716                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(features), &features);
1717                         }
1718                         break;
1719                     case L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED: {
1720                             uint8_t map[8];
1721                             memset(map, 0, 8);
1722                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
1723                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(map), &map);
1724                         }
1725                         break;
1726                     default:
1727                         // all other types are not supported
1728                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 1, 0, NULL);
1729                         break;
1730                 }
1731                 break;
1732             case COMMAND_REJECT:
1733                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
1734                 break;
1735 #endif
1736 #ifdef ENABLE_BLE
1737             case LE_CREDIT_BASED_CONNECTION_REQUEST:
1738                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
1739                 break;
1740             case COMMAND_REJECT_LE:
1741                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
1742                 break;
1743 #endif
1744             default:
1745                 // should not happen
1746                 break;
1747         }
1748     }
1749 }
1750 
1751 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1752 static bool l2ap_run_ertm(void){
1753     // send l2cap information request if neccessary
1754     btstack_linked_list_iterator_t it;
1755     hci_connections_get_iterator(&it);
1756     while(btstack_linked_list_iterator_has_next(&it)){
1757         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1758         if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST){
1759             if (!hci_can_send_acl_packet_now(connection->con_handle)) break;
1760             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
1761             uint8_t sig_id = l2cap_next_sig_id();
1762             uint8_t info_type = L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED;
1763             l2cap_send_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
1764             return true;
1765         }
1766     }
1767     return false;
1768 }
1769 #endif
1770 
1771 #ifdef ENABLE_LE_DATA_CHANNELS
1772 static void l2cap_run_le_data_channels(void){
1773     btstack_linked_list_iterator_t it;
1774     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1775     while (btstack_linked_list_iterator_has_next(&it)){
1776         uint16_t mps;
1777         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1778 
1779         if (channel->channel_type != L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL) continue;
1780 
1781         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1782         switch (channel->state){
1783             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
1784                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1785                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
1786                 // le psm, source cid, mtu, mps, initial credits
1787                 channel->local_sig_id = l2cap_next_sig_id();
1788                 channel->credits_incoming =  channel->new_credits_incoming;
1789                 channel->new_credits_incoming = 0;
1790                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
1791                 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);
1792                 break;
1793             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
1794                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1795                 // TODO: support larger MPS
1796                 channel->state = L2CAP_STATE_OPEN;
1797                 channel->credits_incoming =  channel->new_credits_incoming;
1798                 channel->new_credits_incoming = 0;
1799                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
1800                 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);
1801                 // notify client
1802                 l2cap_emit_le_channel_opened(channel, 0);
1803                 break;
1804             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
1805                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1806                 channel->state = L2CAP_STATE_INVALID;
1807                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
1808                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1809                 btstack_linked_list_iterator_remove(&it);
1810                 l2cap_free_channel_entry(channel);
1811                 break;
1812             case L2CAP_STATE_OPEN:
1813                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1814 
1815                 // send credits
1816                 if (channel->new_credits_incoming){
1817                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
1818                     channel->local_sig_id = l2cap_next_sig_id();
1819                     uint16_t new_credits = channel->new_credits_incoming;
1820                     channel->new_credits_incoming = 0;
1821                     channel->credits_incoming += new_credits;
1822                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
1823                 }
1824                 break;
1825 
1826             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1827                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1828                 channel->local_sig_id = l2cap_next_sig_id();
1829                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1830                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1831                 break;
1832             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1833                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1834                 channel->state = L2CAP_STATE_INVALID;
1835                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1836                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
1837                 break;
1838             default:
1839                 break;
1840         }
1841     }
1842 }
1843 #endif
1844 
1845 // MARK: L2CAP_RUN
1846 // process outstanding signaling tasks
1847 static void l2cap_run(void){
1848 
1849     // log_info("l2cap_run: entered");
1850     l2cap_run_signaling_response();
1851 
1852 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1853     bool done = l2ap_run_ertm();
1854     if (done) return;
1855 #endif
1856 
1857 #if defined(ENABLE_CLASSIC) || defined(ENABLE_BLE)
1858     btstack_linked_list_iterator_t it;
1859 #endif
1860 
1861 #ifdef ENABLE_CLASSIC
1862     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1863     while (btstack_linked_list_iterator_has_next(&it)){
1864 
1865         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1866 
1867         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CLASSIC) continue;
1868 
1869         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1870         bool finalized = l2cap_run_for_classic_channel(channel);
1871 
1872         if (!finalized) {
1873 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1874             l2cap_run_for_classic_channel_ertm(channel);
1875 #endif
1876         }
1877     }
1878 #endif
1879 
1880 #ifdef ENABLE_LE_DATA_CHANNELS
1881     l2cap_run_le_data_channels();
1882 #endif
1883 
1884 #ifdef ENABLE_BLE
1885     // send l2cap con paramter update if necessary
1886     hci_connections_get_iterator(&it);
1887     while(btstack_linked_list_iterator_has_next(&it)){
1888         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1889         if ((connection->address_type != BD_ADDR_TYPE_LE_PUBLIC) && (connection->address_type != BD_ADDR_TYPE_LE_RANDOM)) continue;
1890         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
1891         switch (connection->le_con_parameter_update_state){
1892             case CON_PARAMETER_UPDATE_SEND_REQUEST:
1893                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1894                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, l2cap_next_sig_id(),
1895                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
1896                 break;
1897             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
1898                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
1899                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
1900                 break;
1901             case CON_PARAMETER_UPDATE_DENY:
1902                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1903                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
1904                 break;
1905             default:
1906                 break;
1907         }
1908     }
1909 #endif
1910 
1911     // log_info("l2cap_run: exit");
1912 }
1913 
1914 #ifdef ENABLE_CLASSIC
1915 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
1916     if ((channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE) || (channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION)) {
1917         log_info("connection complete con_handle %04x - for channel %p cid 0x%04x", (int) con_handle, channel, channel->local_cid);
1918         // success, start l2cap handshake
1919         channel->con_handle = con_handle;
1920         // check remote SSP feature first
1921         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
1922     }
1923 }
1924 
1925 static void l2cap_ready_to_connect(l2cap_channel_t * channel){
1926 
1927 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1928     // assumption: outgoing connection
1929     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
1930     if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
1931         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
1932         channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
1933         return;
1934     }
1935 #endif
1936 
1937     // fine, go ahead
1938     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
1939 }
1940 
1941 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
1942     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
1943 
1944     // we have been waiting for remote supported features
1945     if (channel->required_security_level > LEVEL_0){
1946         // request security level
1947         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
1948         gap_request_security_level(channel->con_handle, channel->required_security_level);
1949         return;
1950     }
1951 
1952     l2cap_ready_to_connect(channel);
1953 }
1954 #endif
1955 
1956 #ifdef L2CAP_USES_CHANNELS
1957 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,
1958     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
1959 
1960     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1961     if (!channel) {
1962         return NULL;
1963     }
1964 
1965     // fill in
1966     channel->packet_handler = packet_handler;
1967     channel->channel_type   = channel_type;
1968     bd_addr_copy(channel->address, address);
1969     channel->address_type = address_type;
1970     channel->psm = psm;
1971     channel->local_mtu  = local_mtu;
1972     channel->remote_mtu = L2CAP_DEFAULT_MTU;
1973     channel->required_security_level = security_level;
1974 
1975     //
1976     channel->local_cid = l2cap_next_local_cid();
1977     channel->con_handle = HCI_CON_HANDLE_INVALID;
1978 
1979     // set initial state
1980     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
1981     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
1982     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
1983     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
1984 
1985     log_info("create channel %p, local_cid 0x%04x", channel, channel->local_cid);
1986 
1987     return channel;
1988 }
1989 
1990 static void l2cap_free_channel_entry(l2cap_channel_t * channel){
1991     log_info("free channel %p, local_cid 0x%04x", channel, channel->local_cid);
1992     // assert all timers are stopped
1993     l2cap_stop_rtx(channel);
1994 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1995     l2cap_ertm_stop_retransmission_timer(channel);
1996     l2cap_ertm_stop_monitor_timer(channel);
1997 #endif
1998     // free  memory
1999     btstack_memory_l2cap_channel_free(channel);
2000 }
2001 #endif
2002 
2003 #ifdef ENABLE_CLASSIC
2004 
2005 /**
2006  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
2007  * @param packet_handler
2008  * @param address
2009  * @param psm
2010  * @param mtu
2011  * @param local_cid
2012  */
2013 
2014 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){
2015     // limit MTU to the size of our outgoing HCI buffer
2016     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
2017 
2018 	// determine security level based on psm
2019 	const gap_security_level_t security_level = l2cap_security_level_0_allowed_for_PSM(psm) ? LEVEL_0 : gap_get_security_level();
2020 	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);
2021 
2022     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);
2023     if (!channel) {
2024         return BTSTACK_MEMORY_ALLOC_FAILED;
2025     }
2026 
2027 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2028     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2029 #endif
2030 
2031     // add to connections list
2032     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2033 
2034     // store local_cid
2035     if (out_local_cid){
2036        *out_local_cid = channel->local_cid;
2037     }
2038 
2039 	// state: L2CAP_STATE_WILL_SEND_CREATE_CONNECTION
2040 
2041     // check if hci connection is already usable,
2042     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
2043     if (conn && conn->con_handle != HCI_CON_HANDLE_INVALID){
2044     	// simulate connection complete
2045 	    l2cap_handle_connection_complete(conn->con_handle, channel);
2046 
2047 		// state: L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES
2048 
2049         // check if remote supported features are already received
2050         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
2051         	// simulate remote features received
2052             l2cap_handle_remote_supported_features_received(channel);
2053         }
2054     }
2055 
2056     l2cap_run();
2057 
2058     return ERROR_CODE_SUCCESS;
2059 }
2060 
2061 void l2cap_disconnect(uint16_t local_cid, uint8_t reason){
2062     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
2063     // find channel for local_cid
2064     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2065     if (channel) {
2066         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2067     }
2068     // process
2069     l2cap_run();
2070 }
2071 
2072 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
2073     // mark all channels before emitting open events as these could trigger new connetion requests to the same device
2074     btstack_linked_list_iterator_t it;
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 (bd_addr_cmp( channel->address, address) != 0) continue;
2080         // channel for this address found
2081         switch (channel->state){
2082             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2083             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2084                 channel->state = L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD;
2085                 break;
2086             default:
2087                 break;
2088         }
2089     }
2090     // emit and free marked entries. restart loop to deal with list changes
2091     int done = 0;
2092     while (!done) {
2093         done = 1;
2094         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2095         while (btstack_linked_list_iterator_has_next(&it)){
2096             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2097             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2098             if (channel->state == L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD){
2099                 done = 0;
2100                 // failure, forward error code
2101                 l2cap_handle_channel_open_failed(channel, status);
2102                 // discard channel
2103                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2104                 l2cap_free_channel_entry(channel);
2105                 break;
2106             }
2107         }
2108     }
2109 
2110 }
2111 
2112 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
2113     btstack_linked_list_iterator_t it;
2114     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2115     while (btstack_linked_list_iterator_has_next(&it)){
2116         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2117         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2118         if ( ! bd_addr_cmp( channel->address, address) ){
2119             l2cap_handle_connection_complete(handle, channel);
2120         }
2121     }
2122     // process
2123     l2cap_run();
2124 }
2125 #endif
2126 
2127 static bool l2cap_channel_ready_to_send(l2cap_channel_t * channel){
2128     switch (channel->channel_type){
2129 #ifdef ENABLE_CLASSIC
2130         case L2CAP_CHANNEL_TYPE_CLASSIC:
2131             if (channel->state != L2CAP_STATE_OPEN) return false;
2132 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2133             // send if we have more data and remote windows isn't full yet
2134             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2135                 if (channel->unacked_frames >= btstack_min(channel->num_stored_tx_frames, channel->remote_tx_window_size)) return false;
2136                 return hci_can_send_acl_classic_packet_now() != 0;
2137             }
2138 #endif
2139             if (!channel->waiting_for_can_send_now) return false;
2140             return (hci_can_send_acl_classic_packet_now() != 0);
2141         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2142             if (!channel->waiting_for_can_send_now) return false;
2143             return hci_can_send_acl_classic_packet_now() != 0;
2144 #endif
2145 #ifdef ENABLE_BLE
2146         case L2CAP_CHANNEL_TYPE_LE_FIXED:
2147             if (!channel->waiting_for_can_send_now) return false;
2148             return hci_can_send_acl_le_packet_now() != 0;
2149 #ifdef ENABLE_LE_DATA_CHANNELS
2150         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
2151             if (channel->state != L2CAP_STATE_OPEN) return false;
2152             if (channel->send_sdu_buffer == NULL) return false;
2153             if (channel->credits_outgoing == 0u) return false;
2154             return hci_can_send_acl_le_packet_now() != 0;
2155 #endif
2156 #endif
2157         default:
2158             return false;
2159     }
2160 }
2161 
2162 static void l2cap_channel_trigger_send(l2cap_channel_t * channel){
2163     switch (channel->channel_type){
2164 #ifdef ENABLE_CLASSIC
2165         case L2CAP_CHANNEL_TYPE_CLASSIC:
2166 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2167             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2168                 l2cap_ertm_channel_send_information_frame(channel);
2169                 return;
2170             }
2171 #endif
2172             channel->waiting_for_can_send_now = 0;
2173             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2174             break;
2175         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2176             channel->waiting_for_can_send_now = 0;
2177             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2178             break;
2179 #endif
2180 #ifdef ENABLE_BLE
2181         case L2CAP_CHANNEL_TYPE_LE_FIXED:
2182             channel->waiting_for_can_send_now = 0;
2183             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2184             break;
2185 #ifdef ENABLE_LE_DATA_CHANNELS
2186         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
2187             l2cap_le_send_pdu(channel);
2188             break;
2189 #endif
2190 #endif
2191         default:
2192             break;
2193     }
2194 }
2195 
2196 static void l2cap_notify_channel_can_send(void){
2197     bool done = false;
2198     while (!done){
2199         done = true;
2200         btstack_linked_list_iterator_t it;
2201         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2202         while (btstack_linked_list_iterator_has_next(&it)){
2203             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2204             bool ready = l2cap_channel_ready_to_send(channel);
2205             if (!ready) continue;
2206 
2207             // requeue channel for fairness
2208             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2209             btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2210 
2211             // trigger sending
2212             l2cap_channel_trigger_send(channel);
2213 
2214             // exit inner loop as we just broke the iterator, but try again
2215             done = false;
2216             break;
2217         }
2218     }
2219 }
2220 
2221 #ifdef L2CAP_USES_CHANNELS
2222 
2223 static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){
2224     // open cannot fail for for incoming connections
2225     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0;
2226 
2227     // check state
2228     switch (channel->state){
2229         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2230         case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2231         case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES:
2232         case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2233         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
2234         case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES:
2235         case L2CAP_STATE_WAIT_CONNECT_RSP:
2236         case L2CAP_STATE_CONFIG:
2237         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
2238         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
2239         case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE:
2240         case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD:
2241             return 1;
2242 
2243         case L2CAP_STATE_OPEN:
2244         case L2CAP_STATE_CLOSED:
2245         case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES:
2246         case L2CAP_STATE_WAIT_DISCONNECT:
2247         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY:
2248         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
2249         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
2250         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2251         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
2252         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
2253         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
2254         case L2CAP_STATE_INVALID:
2255         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2256             return 0;
2257 
2258         default:
2259             // get a "warning" about new states
2260             btstack_assert(false);
2261             return 0;
2262     }
2263 }
2264 #endif
2265 
2266 #ifdef ENABLE_CLASSIC
2267 static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){
2268     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2269         l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2270     } else {
2271         l2cap_handle_channel_closed(channel);
2272     }
2273     l2cap_free_channel_entry(channel);
2274 }
2275 #endif
2276 
2277 #ifdef ENABLE_LE_DATA_CHANNELS
2278 static void l2cap_handle_hci_le_disconnect_event(l2cap_channel_t * channel){
2279     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2280         l2cap_emit_le_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2281     } else {
2282         l2cap_emit_le_channel_closed(channel);
2283     }
2284     l2cap_free_channel_entry(channel);
2285 }
2286 #endif
2287 
2288 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
2289 
2290     UNUSED(packet_type); // ok: registered with hci_event_callback_registration
2291     UNUSED(cid);         // ok: there is no channel
2292     UNUSED(size);        // ok: fixed format events read from HCI buffer
2293 
2294 #ifdef ENABLE_CLASSIC
2295     bd_addr_t address;
2296     hci_connection_t * hci_connection;
2297     int hci_con_used;
2298 #endif
2299 #ifdef L2CAP_USES_CHANNELS
2300     hci_con_handle_t handle;
2301     btstack_linked_list_iterator_t it;
2302 #endif
2303 
2304     switch(hci_event_packet_get_type(packet)){
2305 
2306         // Notify channel packet handler if they can send now
2307         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2308         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
2309         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
2310             l2cap_run();    // try sending signaling packets first
2311             l2cap_notify_channel_can_send();
2312             break;
2313 
2314         case HCI_EVENT_COMMAND_STATUS:
2315 #ifdef ENABLE_CLASSIC
2316             // check command status for create connection for errors
2317             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
2318                 // cache outgoing address and reset
2319                 (void)memcpy(address, l2cap_outgoing_classic_addr, 6);
2320                 memset(l2cap_outgoing_classic_addr, 0, 6);
2321                 // error => outgoing connection failed
2322                 uint8_t status = hci_event_command_status_get_status(packet);
2323                 if (status){
2324                     l2cap_handle_connection_failed_for_addr(address, status);
2325                 }
2326             }
2327 #endif
2328             l2cap_run();    // try sending signaling packets first
2329             break;
2330 
2331 #ifdef ENABLE_CLASSIC
2332         // handle connection complete events
2333         case HCI_EVENT_CONNECTION_COMPLETE:
2334             reverse_bd_addr(&packet[5], address);
2335             if (packet[2] == 0){
2336                 handle = little_endian_read_16(packet, 3);
2337                 l2cap_handle_connection_success_for_addr(address, handle);
2338             } else {
2339                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
2340             }
2341             break;
2342 
2343         // handle successful create connection cancel command
2344         case HCI_EVENT_COMMAND_COMPLETE:
2345             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
2346                 if (packet[5] == 0){
2347                     reverse_bd_addr(&packet[6], address);
2348                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
2349                     l2cap_handle_connection_failed_for_addr(address, 0x16);
2350                 }
2351             }
2352             l2cap_run();    // try sending signaling packets first
2353             break;
2354 #endif
2355 
2356 #ifdef L2CAP_USES_CHANNELS
2357         // handle disconnection complete events
2358         case HCI_EVENT_DISCONNECTION_COMPLETE:
2359             handle = little_endian_read_16(packet, 3);
2360             // send l2cap open failed or closed events for all channels on this handle and free them
2361             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2362             while (btstack_linked_list_iterator_has_next(&it)){
2363                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2364                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2365                 if (channel->con_handle != handle) continue;
2366                 btstack_linked_list_iterator_remove(&it);
2367                 switch(channel->channel_type){
2368 #ifdef ENABLE_CLASSIC
2369                     case L2CAP_CHANNEL_TYPE_CLASSIC:
2370                         l2cap_handle_hci_disconnect_event(channel);
2371                         break;
2372 #endif
2373 #ifdef ENABLE_LE_DATA_CHANNELS
2374                     case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
2375                         l2cap_handle_hci_le_disconnect_event(channel);
2376                         break;
2377 #endif
2378                     default:
2379                         break;
2380                 }
2381             }
2382             break;
2383 #endif
2384 
2385 
2386         // HCI Connection Timeouts
2387 #ifdef ENABLE_CLASSIC
2388         case L2CAP_EVENT_TIMEOUT_CHECK:
2389             handle = little_endian_read_16(packet, 2);
2390             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
2391             if (hci_authentication_active_for_handle(handle)) break;
2392             hci_con_used = 0;
2393             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2394             while (btstack_linked_list_iterator_has_next(&it)){
2395                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2396                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2397                 if (channel->con_handle != handle) continue;
2398                 hci_con_used = 1;
2399                 break;
2400             }
2401             if (hci_con_used) break;
2402             if (!hci_can_send_command_packet_now()) break;
2403             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
2404             break;
2405 
2406         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2407         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
2408             handle = little_endian_read_16(packet, 3);
2409             hci_connection = hci_connection_for_handle(handle);
2410             if (hci_connection == NULL) break;
2411             if ((hci_connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) == 0) break;
2412             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2413             while (btstack_linked_list_iterator_has_next(&it)){
2414                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2415                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2416                 if (channel->con_handle != handle) continue;
2417                 log_info("remote supported features, channel %p, cid %04x - state %u", channel, channel->local_cid, channel->state);
2418                 l2cap_handle_remote_supported_features_received(channel);
2419             }
2420             break;
2421 
2422         case GAP_EVENT_SECURITY_LEVEL:
2423             handle = little_endian_read_16(packet, 2);
2424             log_info("l2cap - security level update for handle 0x%04x", handle);
2425             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2426             while (btstack_linked_list_iterator_has_next(&it)){
2427                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2428                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2429                 if (channel->con_handle != handle) continue;
2430 
2431                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
2432                 gap_security_level_t required_level = channel->required_security_level;
2433 
2434                 log_info("channel %p, cid %04x - state %u: actual %u >= required %u?", channel, channel->local_cid, channel->state, actual_level, required_level);
2435 
2436                 switch (channel->state){
2437                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2438                         if (actual_level >= required_level){
2439 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2440                             // we need to know if ERTM is supported before sending a config response
2441                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
2442                             if (connection->l2cap_state.information_state != L2CAP_INFORMATION_STATE_DONE){
2443                                 connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2444                                 channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
2445                                 break;
2446                             }
2447 #endif
2448                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2449                             l2cap_emit_incoming_connection(channel);
2450                         } else {
2451                             channel->reason = 0x0003; // security block
2452                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2453                         }
2454                         break;
2455 
2456                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2457                         if (actual_level >= required_level){
2458                             l2cap_ready_to_connect(channel);
2459                         } else {
2460                             // disconnnect, authentication not good enough
2461                             hci_disconnect_security_block(handle);
2462                         }
2463                         break;
2464 
2465                     default:
2466                         break;
2467                 }
2468             }
2469             break;
2470 #endif
2471 
2472         default:
2473             break;
2474     }
2475 
2476     l2cap_run();
2477 }
2478 
2479 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t cid, uint16_t data){
2480     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused."
2481     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
2482         signaling_responses[signaling_responses_pending].handle = handle;
2483         signaling_responses[signaling_responses_pending].code = code;
2484         signaling_responses[signaling_responses_pending].sig_id = sig_id;
2485         signaling_responses[signaling_responses_pending].cid = cid;
2486         signaling_responses[signaling_responses_pending].data = data;
2487         signaling_responses_pending++;
2488         l2cap_run();
2489     }
2490 }
2491 
2492 #ifdef ENABLE_CLASSIC
2493 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
2494     channel->remote_sig_id = identifier;
2495     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
2496     l2cap_run();
2497 }
2498 
2499 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
2500 
2501     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
2502     l2cap_service_t *service = l2cap_get_service(psm);
2503     if (!service) {
2504         // 0x0002 PSM not supported
2505         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2506         return;
2507     }
2508 
2509     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
2510     if (!hci_connection) {
2511         //
2512         log_error("no hci_connection for handle %u", handle);
2513         return;
2514     }
2515 
2516     // alloc structure
2517     // log_info("l2cap_handle_connection_request register channel");
2518     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, hci_connection->address, BD_ADDR_TYPE_ACL,
2519     psm, service->mtu, service->required_security_level);
2520     if (!channel){
2521         // 0x0004 No resources available
2522         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2523         return;
2524     }
2525 
2526     channel->con_handle = handle;
2527     channel->remote_cid = source_cid;
2528     channel->remote_sig_id = sig_id;
2529 
2530     // limit local mtu to max acl packet length - l2cap header
2531     if (channel->local_mtu > l2cap_max_mtu()) {
2532         channel->local_mtu = l2cap_max_mtu();
2533     }
2534 
2535     // set initial state
2536     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
2537     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
2538 
2539     // add to connections list
2540     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2541 
2542     // assert security requirements
2543     gap_request_security_level(handle, channel->required_security_level);
2544 }
2545 
2546 void l2cap_accept_connection(uint16_t local_cid){
2547     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
2548     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2549     if (!channel) {
2550         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
2551         return;
2552     }
2553 
2554 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2555     // configure L2CAP Basic mode
2556     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
2557 #endif
2558 
2559     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
2560 
2561     // process
2562     l2cap_run();
2563 }
2564 
2565 void l2cap_decline_connection(uint16_t local_cid){
2566     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
2567     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
2568     if (!channel) {
2569         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
2570         return;
2571     }
2572     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2573     channel->reason = 0x04; // no resources available
2574     l2cap_run();
2575 }
2576 
2577 // @pre command len is valid, see check in l2cap_signaling_handler_channel
2578 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
2579 
2580 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2581     uint8_t use_fcs = 1;
2582 #endif
2583 
2584     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2585 
2586     uint16_t flags = little_endian_read_16(command, 6);
2587     if (flags & 1) {
2588         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
2589     }
2590 
2591     // accept the other's configuration options
2592     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2593     uint16_t pos     = 8;
2594     while (pos < end_pos){
2595         uint8_t option_hint = command[pos] >> 7;
2596         uint8_t option_type = command[pos] & 0x7f;
2597         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
2598         pos++;
2599         uint8_t length = command[pos++];
2600         // MTU { type(8): 1, len(8):2, MTU(16) }
2601         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) && (length == 2)){
2602             channel->remote_mtu = little_endian_read_16(command, pos);
2603             log_info("Remote MTU %u", channel->remote_mtu);
2604             if (channel->remote_mtu > l2cap_max_mtu()){
2605                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
2606                 channel->remote_mtu = l2cap_max_mtu();
2607             }
2608             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
2609         }
2610         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
2611         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT) && (length == 2)){
2612             channel->flush_timeout = little_endian_read_16(command, pos);
2613             log_info("Flush timeout: %u ms", channel->flush_timeout);
2614         }
2615 
2616 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2617         // Retransmission and Flow Control Option
2618         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2619             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
2620             switch(channel->mode){
2621                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2622                     // Store remote config
2623                     channel->remote_tx_window_size = command[pos+1];
2624                     channel->remote_max_transmit   = command[pos+2];
2625                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
2626                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
2627                     channel->remote_mps = little_endian_read_16(command, pos + 7);
2628                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
2629                         channel->remote_tx_window_size,
2630                         channel->remote_max_transmit,
2631                         channel->remote_retransmission_timeout_ms,
2632                         channel->remote_monitor_timeout_ms,
2633                         channel->remote_mps);
2634                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
2635                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
2636                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2637                     } else {
2638                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2639                     }
2640                     break;
2641                 case L2CAP_CHANNEL_MODE_BASIC:
2642                     switch (mode){
2643                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2644                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
2645                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
2646                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2647                             }
2648                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
2649                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
2650                             break;
2651                         default: // case L2CAP_CHANNEL_MODE_BASIC:
2652                             // TODO store and evaluate configuration
2653                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2654                             break;
2655                     }
2656                     break;
2657                 default:
2658                     break;
2659             }
2660         }
2661         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
2662             use_fcs = command[pos];
2663         }
2664 #endif
2665         // check for unknown options
2666         if ((option_hint == 0) && ((option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) || (option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE))){
2667             log_info("l2cap cid %u, unknown options", channel->local_cid);
2668             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
2669         }
2670         pos += length;
2671     }
2672 
2673 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2674         // "FCS" has precedence over "No FCS"
2675         uint8_t update = channel->fcs_option || use_fcs;
2676         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
2677         channel->fcs_option = update;
2678         // If ERTM mandatory, but remote didn't send Retransmission and Flowcontrol options -> disconnect
2679         if (((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM) == 0) & (channel->ertm_mandatory)){
2680             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2681         }
2682 #endif
2683 }
2684 
2685 // @pre command len is valid, see check in l2cap_signaling_handler_channel
2686 static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
2687     log_info("l2cap_signaling_handle_configure_response");
2688 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2689     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2690     uint16_t pos     = 10;
2691     while (pos < end_pos){
2692         uint8_t option_hint = command[pos] >> 7;
2693         uint8_t option_type = command[pos] & 0x7f;
2694         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
2695         pos++;
2696         uint8_t length = command[pos++];
2697 
2698         // Retransmission and Flow Control Option
2699         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2700             switch (channel->mode){
2701                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2702                     if (channel->ertm_mandatory){
2703                         // ??
2704                     } else {
2705                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
2706                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2707                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
2708                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2709                         }
2710                     }
2711                     break;
2712                 case L2CAP_CHANNEL_MODE_BASIC:
2713                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2714                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
2715                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2716                     }
2717                     break;
2718                 default:
2719                     break;
2720             }
2721         }
2722 
2723         // check for unknown options
2724         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
2725             log_info("l2cap cid %u, unknown options", channel->local_cid);
2726             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
2727         }
2728 
2729         pos += length;
2730     }
2731 #else
2732     UNUSED(channel);  // ok: no code
2733     UNUSED(result);   // ok: no code
2734     UNUSED(command);  // ok: no code
2735 #endif
2736 }
2737 
2738 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
2739     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
2740     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
2741     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
2742     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
2743     if (channel->state == L2CAP_STATE_OPEN) return 0;
2744     return 1;
2745 }
2746 
2747 
2748 // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
2749 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
2750 
2751     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2752     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2753     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2754     uint16_t result = 0;
2755 
2756     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
2757 
2758     // handle DISCONNECT REQUESTS seperately
2759     if (code == DISCONNECTION_REQUEST){
2760         switch (channel->state){
2761             case L2CAP_STATE_CONFIG:
2762             case L2CAP_STATE_OPEN:
2763             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2764             case L2CAP_STATE_WAIT_DISCONNECT:
2765                 l2cap_handle_disconnect_request(channel, identifier);
2766                 break;
2767 
2768             default:
2769                 // ignore in other states
2770                 break;
2771         }
2772         return;
2773     }
2774 
2775     // @STATEMACHINE(l2cap)
2776     switch (channel->state) {
2777 
2778         case L2CAP_STATE_WAIT_CONNECT_RSP:
2779             switch (code){
2780                 case CONNECTION_RESPONSE:
2781                     if (cmd_len < 8){
2782                         // command imcomplete
2783                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2784                         break;
2785                     }
2786                     l2cap_stop_rtx(channel);
2787                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2788                     switch (result) {
2789                         case 0:
2790                             // successful connection
2791                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2792                             channel->state = L2CAP_STATE_CONFIG;
2793                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2794                             break;
2795                         case 1:
2796                             // connection pending. get some coffee, but start the ERTX
2797                             l2cap_start_ertx(channel);
2798                             break;
2799                         default:
2800                             // channel closed
2801                             channel->state = L2CAP_STATE_CLOSED;
2802                             // map l2cap connection response result to BTstack status enumeration
2803                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
2804 
2805                             // drop link key if security block
2806                             if ((L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result) == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
2807                                 gap_drop_link_key_for_bd_addr(channel->address);
2808                             }
2809 
2810                             // discard channel
2811                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2812                             l2cap_free_channel_entry(channel);
2813                             break;
2814                     }
2815                     break;
2816 
2817                 default:
2818                     //@TODO: implement other signaling packets
2819                     break;
2820             }
2821             break;
2822 
2823         case L2CAP_STATE_CONFIG:
2824             switch (code) {
2825                 case CONFIGURE_REQUEST:
2826                     if (cmd_len < 4){
2827                         // command incomplete
2828                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2829                         break;
2830                     }
2831                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
2832                     l2cap_signaling_handle_configure_request(channel, command);
2833                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
2834                         // only done if continuation not set
2835                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
2836                     }
2837                     break;
2838                 case CONFIGURE_RESPONSE:
2839                     if (cmd_len < 6){
2840                         // command incomplete
2841                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2842                         break;
2843                     }
2844                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2845                     l2cap_stop_rtx(channel);
2846                     l2cap_signaling_handle_configure_response(channel, result, command);
2847                     switch (result){
2848                         case 0: // success
2849                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
2850                             break;
2851                         case 4: // pending
2852                             l2cap_start_ertx(channel);
2853                             break;
2854                         default:
2855 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2856                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
2857                                 // remote does not offer ertm but it's required
2858                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2859                                 break;
2860                             }
2861 #endif
2862                             // retry on negative result
2863                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2864                             break;
2865                     }
2866                     break;
2867                 default:
2868                     break;
2869             }
2870             if (l2cap_channel_ready_for_open(channel)){
2871 
2872 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2873                 // assert that packet can be stored in fragment buffers in ertm
2874                 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
2875                     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
2876                     uint16_t usable_mtu = channel->num_tx_buffers == 1 ? effective_mps : channel->num_tx_buffers * effective_mps - 2;
2877                     if (usable_mtu < channel->remote_mtu){
2878                         log_info("Remote MTU %u > max storable ERTM packet, only using MTU = %u", channel->remote_mtu, usable_mtu);
2879                         channel->remote_mtu = usable_mtu;
2880                     }
2881                 }
2882 #endif
2883                 // for open:
2884                 channel->state = L2CAP_STATE_OPEN;
2885                 l2cap_emit_channel_opened(channel, 0);
2886             }
2887             break;
2888 
2889         case L2CAP_STATE_WAIT_DISCONNECT:
2890             switch (code) {
2891                 case DISCONNECTION_RESPONSE:
2892                     l2cap_finialize_channel_close(channel);
2893                     break;
2894                 default:
2895                     //@TODO: implement other signaling packets
2896                     break;
2897             }
2898             break;
2899 
2900         case L2CAP_STATE_CLOSED:
2901             // @TODO handle incoming requests
2902             break;
2903 
2904         case L2CAP_STATE_OPEN:
2905             //@TODO: implement other signaling packets, e.g. re-configure
2906             break;
2907         default:
2908             break;
2909     }
2910     // log_info("new state %u", channel->state);
2911 }
2912 
2913 
2914 // @pre command len is valid, see check in l2cap_acl_classic_handler
2915 static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
2916 
2917     btstack_linked_list_iterator_t it;
2918 
2919     // get code, signalind identifier and command len
2920     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2921     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2922     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2923 
2924     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
2925     if ((code < 1) || (code == ECHO_RESPONSE) || (code > INFORMATION_RESPONSE)){
2926         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2927         return;
2928     }
2929 
2930     // general commands without an assigned channel
2931     switch(code) {
2932 
2933         case CONNECTION_REQUEST:
2934             if (cmd_len == 4){
2935                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2936                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
2937                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
2938             } else {
2939                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2940             }
2941             return;
2942 
2943         case ECHO_REQUEST:
2944             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
2945             return;
2946 
2947         case INFORMATION_REQUEST:
2948             if (cmd_len == 2) {
2949                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2950                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
2951             } else {
2952                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2953             }
2954             return;
2955 
2956 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2957         case INFORMATION_RESPONSE: {
2958             hci_connection_t * connection = hci_connection_for_handle(handle);
2959             if (!connection) return;
2960             if (connection->l2cap_state.information_state != L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE) return;
2961 
2962             // get extended features from response if valid
2963             connection->l2cap_state.extended_feature_mask = 0;
2964             if (cmd_len >= 6) {
2965                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2966                 uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
2967                 if (result == 0 && info_type == L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) {
2968                     connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2969                 }
2970             }
2971             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
2972             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
2973 
2974             // trigger connection request
2975             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2976             while (btstack_linked_list_iterator_has_next(&it)){
2977                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2978                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2979                 if (channel->con_handle != handle) continue;
2980 
2981                 // incoming connection: ask user for channel configuration, esp. if ertm will be mandatory
2982                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
2983                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2984                     l2cap_emit_incoming_connection(channel);
2985                     continue;
2986                 }
2987 
2988                 // outgoing connection
2989                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
2990 
2991                     // if ERTM was requested, but is not listed in extended feature mask:
2992                     if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2993 
2994                         if (channel->ertm_mandatory){
2995                             // bail if ERTM is mandatory
2996                             channel->state = L2CAP_STATE_CLOSED;
2997                             // map l2cap connection response result to BTstack status enumeration
2998                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
2999                             // discard channel
3000                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3001                             l2cap_free_channel_entry(channel);
3002                             continue;
3003 
3004                         } else {
3005                             // fallback to Basic mode
3006                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3007                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3008                         }
3009                     }
3010 
3011                     // respond to connection request
3012                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
3013                     continue;
3014                 }
3015             }
3016             return;
3017         }
3018 #endif
3019 
3020         default:
3021             break;
3022     }
3023 
3024     // Get potential destination CID
3025     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3026 
3027     // Find channel for this sig_id and connection handle
3028     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3029     while (btstack_linked_list_iterator_has_next(&it)){
3030         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3031         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3032         if (channel->con_handle != handle) continue;
3033         if (code & 1) {
3034             // match odd commands (responses) by previous signaling identifier
3035             if (channel->local_sig_id == sig_id) {
3036                 l2cap_signaling_handler_channel(channel, command);
3037                 break;
3038             }
3039         } else {
3040             // match even commands (requests) by local channel id
3041             if (channel->local_cid == dest_cid) {
3042                 l2cap_signaling_handler_channel(channel, command);
3043                 break;
3044             }
3045         }
3046     }
3047 }
3048 #endif
3049 
3050 #ifdef ENABLE_BLE
3051 
3052 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
3053     uint8_t event[6];
3054     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
3055     event[1] = 4;
3056     little_endian_store_16(event, 2, con_handle);
3057     little_endian_store_16(event, 4, result);
3058     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3059     if (!l2cap_event_packet_handler) return;
3060     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
3061 }
3062 
3063 // @returns valid
3064 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
3065     hci_connection_t * connection;
3066     uint16_t result;
3067     uint8_t  event[12];
3068 
3069 #ifdef ENABLE_LE_DATA_CHANNELS
3070     btstack_linked_list_iterator_t it;
3071     l2cap_channel_t * channel;
3072     uint16_t local_cid;
3073     uint16_t le_psm;
3074     uint16_t new_credits;
3075     uint16_t credits_before;
3076     l2cap_service_t * service;
3077     uint16_t source_cid;
3078 #endif
3079 
3080     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3081     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3082     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
3083 
3084     switch (code){
3085 
3086         case CONNECTION_PARAMETER_UPDATE_REQUEST:
3087             // check size
3088             if (len < 8u) return 0u;
3089             connection = hci_connection_for_handle(handle);
3090             if (connection){
3091                 if (connection->role != HCI_ROLE_MASTER){
3092                     // reject command without notifying upper layer when not in master role
3093                     return 0;
3094                 }
3095                 le_connection_parameter_range_t existing_range;
3096                 gap_get_connection_parameter_range(&existing_range);
3097                 uint16_t le_conn_interval_min   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3098                 uint16_t le_conn_interval_max   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3099                 uint16_t le_conn_latency        = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3100                 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
3101 
3102                 int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
3103                 if (update_parameter){
3104                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
3105                     connection->le_conn_interval_min = le_conn_interval_min;
3106                     connection->le_conn_interval_max = le_conn_interval_max;
3107                     connection->le_conn_latency = le_conn_latency;
3108                     connection->le_supervision_timeout = le_supervision_timeout;
3109                 } else {
3110                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
3111                 }
3112                 connection->le_con_param_update_identifier = sig_id;
3113             }
3114 
3115             if (!l2cap_event_packet_handler) break;
3116 
3117             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
3118             event[1] = 8;
3119             little_endian_store_16(event, 2, handle);
3120             (void)memcpy(&event[4], &command[4], 8);
3121             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3122             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
3123             break;
3124 
3125         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
3126             // check size
3127             if (len < 2u) return 0u;
3128             result = little_endian_read_16(command, 4);
3129             l2cap_emit_connection_parameter_update_response(handle, result);
3130             break;
3131 
3132 #ifdef ENABLE_LE_DATA_CHANNELS
3133 
3134         case COMMAND_REJECT:
3135             // Find channel for this sig_id and connection handle
3136             channel = NULL;
3137             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3138             while (btstack_linked_list_iterator_has_next(&it)){
3139                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3140                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
3141                 if (a_channel->con_handle   != handle) continue;
3142                 if (a_channel->local_sig_id != sig_id) continue;
3143                 channel = a_channel;
3144                 break;
3145             }
3146             if (!channel) break;
3147 
3148             // if received while waiting for le connection response, assume legacy device
3149             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
3150                 channel->state = L2CAP_STATE_CLOSED;
3151                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
3152                 l2cap_emit_le_channel_opened(channel, 0x0002);
3153 
3154                 // discard channel
3155                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3156                 l2cap_free_channel_entry(channel);
3157                 break;
3158             }
3159             break;
3160 
3161         case LE_CREDIT_BASED_CONNECTION_REQUEST:
3162             // check size
3163             if (len < 10u) return 0u;
3164 
3165             // get hci connection, bail if not found (must not happen)
3166             connection = hci_connection_for_handle(handle);
3167             if (!connection) return 0;
3168 
3169             // check if service registered
3170             le_psm  = little_endian_read_16(command, 4);
3171             service = l2cap_le_get_service(le_psm);
3172             source_cid = little_endian_read_16(command, 6);
3173 
3174             if (service){
3175                 if (source_cid < 0x40u){
3176                     // 0x0009 Connection refused - Invalid Source CID
3177                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
3178                     return 1;
3179                 }
3180 
3181                 // go through list of channels for this ACL connection and check if we get a match
3182                 btstack_linked_list_iterator_init(&it, &l2cap_channels);
3183                 while (btstack_linked_list_iterator_has_next(&it)){
3184                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3185                     if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
3186                     if (a_channel->con_handle != handle) continue;
3187                     if (a_channel->remote_cid != source_cid) continue;
3188                     // 0x000a Connection refused - Source CID already allocated
3189                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
3190                     return 1;
3191                 }
3192 
3193                 // security: check encryption
3194                 if (service->required_security_level >= LEVEL_2){
3195                     if (gap_encryption_key_size(handle) == 0){
3196                         // 0x0008 Connection refused - insufficient encryption
3197                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
3198                         return 1;
3199                     }
3200                     // anything less than 16 byte key size is insufficient
3201                     if (gap_encryption_key_size(handle) < 16){
3202                         // 0x0007 Connection refused – insufficient encryption key size
3203                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
3204                         return 1;
3205                     }
3206                 }
3207 
3208                 // security: check authencation
3209                 if (service->required_security_level >= LEVEL_3){
3210                     if (!gap_authenticated(handle)){
3211                         // 0x0005 Connection refused – insufficient authentication
3212                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
3213                         return 1;
3214                     }
3215                 }
3216 
3217                 // security: check authorization
3218                 if (service->required_security_level >= LEVEL_4){
3219                     if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
3220                         // 0x0006 Connection refused – insufficient authorization
3221                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
3222                         return 1;
3223                     }
3224                 }
3225 
3226                 // allocate channel
3227                 channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL, connection->address,
3228                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
3229                 if (!channel){
3230                     // 0x0004 Connection refused – no resources available
3231                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
3232                     return 1;
3233                 }
3234 
3235                 channel->con_handle = handle;
3236                 channel->remote_cid = source_cid;
3237                 channel->remote_sig_id = sig_id;
3238                 channel->remote_mtu = little_endian_read_16(command, 8);
3239                 channel->remote_mps = little_endian_read_16(command, 10);
3240                 channel->credits_outgoing = little_endian_read_16(command, 12);
3241 
3242                 // set initial state
3243                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
3244                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
3245 
3246                 // add to connections list
3247                 btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
3248 
3249                 // post connection request event
3250                 l2cap_emit_le_incoming_connection(channel);
3251 
3252             } else {
3253                 // Connection refused – LE_PSM not supported
3254                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
3255             }
3256             break;
3257 
3258         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
3259             // check size
3260             if (len < 10u) return 0u;
3261 
3262             // Find channel for this sig_id and connection handle
3263             channel = NULL;
3264             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3265             while (btstack_linked_list_iterator_has_next(&it)){
3266                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3267                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
3268                 if (a_channel->con_handle   != handle) continue;
3269                 if (a_channel->local_sig_id != sig_id) continue;
3270                 channel = a_channel;
3271                 break;
3272             }
3273             if (!channel) break;
3274 
3275             // cid + 0
3276             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
3277             if (result){
3278                 channel->state = L2CAP_STATE_CLOSED;
3279                 // map l2cap connection response result to BTstack status enumeration
3280                 l2cap_emit_le_channel_opened(channel, result);
3281 
3282                 // discard channel
3283                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3284                 l2cap_free_channel_entry(channel);
3285                 break;
3286             }
3287 
3288             // success
3289             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3290             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3291             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3292             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
3293             channel->state = L2CAP_STATE_OPEN;
3294             l2cap_emit_le_channel_opened(channel, result);
3295             break;
3296 
3297         case LE_FLOW_CONTROL_CREDIT:
3298             // check size
3299             if (len < 4u) return 0u;
3300 
3301             // find channel
3302             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3303             channel = l2cap_get_channel_for_local_cid_and_handle(local_cid, handle);
3304             if (!channel) {
3305                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
3306                 break;
3307             }
3308             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3309             credits_before = channel->credits_outgoing;
3310             channel->credits_outgoing += new_credits;
3311             // check for credit overrun
3312             if (credits_before > channel->credits_outgoing){
3313                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
3314                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3315                 break;
3316             }
3317             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
3318             break;
3319 
3320         case DISCONNECTION_REQUEST:
3321 
3322             // check size
3323             if (len < 4u) return 0u;
3324 
3325             // find channel
3326             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3327             channel = l2cap_get_channel_for_local_cid_and_handle(local_cid, handle);
3328             if (!channel) {
3329                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
3330                 break;
3331             }
3332             channel->remote_sig_id = sig_id;
3333             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
3334             break;
3335 
3336 #endif
3337 
3338         case DISCONNECTION_RESPONSE:
3339             break;
3340 
3341         default:
3342             // command unknown -> reject command
3343             return 0;
3344     }
3345     return 1;
3346 }
3347 #endif
3348 
3349 #ifdef ENABLE_CLASSIC
3350 static void l2cap_acl_classic_handler_for_channel(l2cap_channel_t * l2cap_channel, uint8_t * packet, uint16_t size){
3351 
3352     // forward data only in OPEN state
3353     if (l2cap_channel->state != L2CAP_STATE_OPEN) return;
3354 
3355 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3356     if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3357 
3358         int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
3359 
3360         // assert control + FCS fields are inside
3361         if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) return;
3362 
3363         if (l2cap_channel->fcs_option){
3364             // verify FCS (required if one side requested it)
3365             uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
3366             uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
3367 
3368 #ifdef L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL
3369             // simulate fcs error
3370                         static int counter = 0;
3371                         if (++counter == L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL) {
3372                             log_info("Simulate fcs error");
3373                             fcs_calculated++;
3374                             counter = 0;
3375                         }
3376 #endif
3377 
3378             if (fcs_calculated == fcs_packet){
3379                 log_info("Packet FCS 0x%04x verified", fcs_packet);
3380             } else {
3381                 log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
3382                 // ERTM State Machine in Bluetooth Spec does not handle 'I-Frame with invalid FCS'
3383                 return;
3384             }
3385         }
3386 
3387         // switch on packet type
3388         uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3389         uint8_t  req_seq = (control >> 8) & 0x3f;
3390         int final = (control >> 7) & 0x01;
3391         if (control & 1){
3392             // S-Frame
3393             int poll  = (control >> 4) & 0x01;
3394             l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
3395             log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
3396             l2cap_ertm_tx_packet_state_t * tx_state;
3397             switch (s){
3398                 case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
3399                     log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
3400                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3401                     if (poll && final){
3402                         // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
3403                         log_error("P=F=1 in S-Frame");
3404                         break;
3405                     }
3406                     if (poll){
3407                         // check if we did request selective retransmission before <==> we have stored SDU segments
3408                         int i;
3409                         int num_stored_out_of_order_packets = 0;
3410                         for (i=0;i<l2cap_channel->num_rx_buffers;i++){
3411                             int index = l2cap_channel->rx_store_index + i;
3412                             if (index >= l2cap_channel->num_rx_buffers){
3413                                 index -= l2cap_channel->num_rx_buffers;
3414                             }
3415                             l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3416                             if (!rx_state->valid) continue;
3417                             num_stored_out_of_order_packets++;
3418                         }
3419                         if (num_stored_out_of_order_packets){
3420                             l2cap_channel->send_supervisor_frame_selective_reject = 1;
3421                         } else {
3422                             l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
3423                         }
3424                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
3425                     }
3426                     if (final){
3427                         // Stop-MonitorTimer
3428                         l2cap_ertm_stop_monitor_timer(l2cap_channel);
3429                         // If UnackedFrames > 0 then Start-RetransTimer
3430                         if (l2cap_channel->unacked_frames){
3431                             l2cap_ertm_start_retransmission_timer(l2cap_channel);
3432                         }
3433                         // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3434                         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
3435                     }
3436                     break;
3437                 case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
3438                     log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
3439                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3440                     // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
3441                     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
3442                     break;
3443                 case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
3444                     log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
3445                     break;
3446                 case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
3447                     log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
3448                     if (poll){
3449                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3450                     }
3451                     // find requested i-frame
3452                     tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
3453                     if (tx_state){
3454                         log_info("Retransmission for tx_seq %u requested", req_seq);
3455                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
3456                         tx_state->retransmission_requested = 1;
3457                         l2cap_channel->srej_active = 1;
3458                     }
3459                     break;
3460                 default:
3461                     break;
3462             }
3463         } else {
3464             // I-Frame
3465             // get control
3466             l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
3467             uint8_t tx_seq = (control >> 1) & 0x3f;
3468             log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
3469             log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
3470             log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
3471             l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3472             if (final){
3473                 // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3474                 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
3475             }
3476 
3477             // get SDU
3478             const uint8_t * payload_data = &packet[COMPLETE_L2CAP_HEADER+2];
3479             uint16_t        payload_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
3480 
3481             // assert SDU size is smaller or equal to our buffers
3482             uint16_t max_payload_size = 0;
3483             switch (sar){
3484                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
3485                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
3486                     // SDU Length + MPS
3487                     max_payload_size = l2cap_channel->local_mps + 2;
3488                     break;
3489                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
3490                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
3491                     max_payload_size = l2cap_channel->local_mps;
3492                     break;
3493                 default:
3494                     btstack_assert(false);
3495                     break;
3496             }
3497             if (payload_len > max_payload_size){
3498                 log_info("payload len %u > max payload %u -> drop packet", payload_len, max_payload_size);
3499                 return;
3500             }
3501 
3502             // check ordering
3503             if (l2cap_channel->expected_tx_seq == tx_seq){
3504                 log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
3505                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3506                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3507 
3508                 // process SDU
3509                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, payload_data, payload_len);
3510 
3511                 // process stored segments
3512                 while (true){
3513                     int index = l2cap_channel->rx_store_index;
3514                     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3515                     if (!rx_state->valid) break;
3516 
3517                     log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
3518                     l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3519                     l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3520 
3521                     rx_state->valid = 0;
3522                     l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
3523 
3524                     // update rx store index
3525                     index++;
3526                     if (index >= l2cap_channel->num_rx_buffers){
3527                         index = 0;
3528                     }
3529                     l2cap_channel->rx_store_index = index;
3530                 }
3531 
3532                 //
3533                 l2cap_channel->send_supervisor_frame_receiver_ready = 1;
3534 
3535             } else {
3536                 int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
3537                 if (delta < 2){
3538                     // store segment
3539                     l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, payload_data, payload_len);
3540 
3541                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
3542                     l2cap_channel->send_supervisor_frame_selective_reject = 1;
3543                 } else {
3544                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
3545                     l2cap_channel->send_supervisor_frame_reject = 1;
3546                 }
3547             }
3548         }
3549         return;
3550     }
3551 #endif
3552 
3553     // check size
3554     uint16_t payload_size = size - COMPLETE_L2CAP_HEADER;
3555     if (l2cap_channel->local_mtu < payload_size) return;
3556 
3557     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], payload_size);
3558 }
3559 #endif
3560 
3561 static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3562 #ifdef ENABLE_CLASSIC
3563     l2cap_channel_t * l2cap_channel;
3564     l2cap_fixed_channel_t * l2cap_fixed_channel;
3565 
3566     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3567     uint8_t  broadcast_flag = READ_ACL_FLAGS(packet) >> 2;
3568     switch (channel_id) {
3569 
3570         case L2CAP_CID_SIGNALING: {
3571             if (broadcast_flag != 0) break;
3572             uint32_t command_offset = 8;
3573             while ((command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET) < size) {
3574                 // assert signaling command is fully inside packet
3575                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3576                 uint32_t next_command_offset = command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
3577                 if (next_command_offset > size){
3578                     log_error("l2cap signaling command len invalid -> drop");
3579                     break;
3580                 }
3581                 // handle signaling command
3582                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
3583                 // go to next command
3584                 command_offset = next_command_offset;
3585             }
3586             break;
3587         }
3588         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
3589             if (broadcast_flag == 0) break;
3590             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL);
3591             if (!l2cap_fixed_channel) break;
3592             if (!l2cap_fixed_channel->packet_handler) break;
3593             (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3594             break;
3595 
3596         default:
3597             if (broadcast_flag != 0) break;
3598             // Find channel for this channel_id and connection handle
3599             l2cap_channel = l2cap_get_channel_for_local_cid_and_handle(channel_id, handle);
3600             if (l2cap_channel != NULL){
3601                 l2cap_acl_classic_handler_for_channel(l2cap_channel, packet, size);
3602             }
3603             break;
3604     }
3605 #else
3606     UNUSED(handle); // ok: no code
3607     UNUSED(packet); // ok: no code
3608     UNUSED(size);   // ok: no code
3609 #endif
3610 }
3611 
3612 static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3613 #ifdef ENABLE_BLE
3614 
3615     l2cap_fixed_channel_t * l2cap_fixed_channel;
3616 
3617 #ifdef ENABLE_LE_DATA_CHANNELS
3618     l2cap_channel_t * l2cap_channel;
3619 #endif
3620     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3621     switch (channel_id) {
3622 
3623         case L2CAP_CID_SIGNALING_LE: {
3624             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
3625             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
3626             if ((COMPLETE_L2CAP_HEADER + 4u + len) > size) break;
3627             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
3628             if (!valid){
3629                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3630             }
3631             break;
3632         }
3633 
3634         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
3635             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL);
3636             if (!l2cap_fixed_channel) break;
3637             if (!l2cap_fixed_channel->packet_handler) break;
3638             (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3639             break;
3640 
3641         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
3642             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
3643             if (!l2cap_fixed_channel) break;
3644             if (!l2cap_fixed_channel->packet_handler) break;
3645             (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3646             break;
3647 
3648         default:
3649 
3650 #ifdef ENABLE_LE_DATA_CHANNELS
3651             l2cap_channel = l2cap_get_channel_for_local_cid_and_handle(channel_id, handle);
3652             if (l2cap_channel != NULL) {
3653                 // credit counting
3654                 if (l2cap_channel->credits_incoming == 0u){
3655                     log_info("LE Data Channel packet received but no incoming credits");
3656                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3657                     break;
3658                 }
3659                 l2cap_channel->credits_incoming--;
3660 
3661                 // automatic credits
3662                 if ((l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK) && l2cap_channel->automatic_credits){
3663                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
3664                 }
3665 
3666                 // first fragment
3667                 uint16_t pos = 0;
3668                 if (!l2cap_channel->receive_sdu_len){
3669                     uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3670                     if(sdu_len > l2cap_channel->local_mtu) break;   // SDU would be larger than our buffer
3671                     l2cap_channel->receive_sdu_len = sdu_len;
3672                     l2cap_channel->receive_sdu_pos = 0;
3673                     pos  += 2u;
3674                     size -= 2u;
3675                 }
3676                 uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
3677                 uint16_t remaining_space = l2cap_channel->local_mtu - l2cap_channel->receive_sdu_pos;
3678                 if (fragment_size > remaining_space) break;         // SDU would cause buffer overrun
3679                 (void)memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos],
3680                              &packet[COMPLETE_L2CAP_HEADER + pos],
3681                              fragment_size);
3682                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
3683                 // done?
3684                 log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
3685                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
3686                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
3687                     l2cap_channel->receive_sdu_len = 0;
3688                 }
3689             }
3690 #endif
3691             break;
3692     }
3693 #else
3694     UNUSED(handle); // ok: no code
3695     UNUSED(packet); // ok: no code
3696     UNUSED(size);   // ok: no code
3697 #endif
3698 }
3699 
3700 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
3701     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
3702     UNUSED(channel);        // ok: there is no channel
3703 
3704     // Assert full L2CAP header present
3705     if (size < COMPLETE_L2CAP_HEADER) return;
3706 
3707     // Dispatch to Classic or LE handler (SCO packets are not dispatched to L2CAP)
3708     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
3709     hci_connection_t *conn = hci_connection_for_handle(handle);
3710     if (!conn) return;
3711     if (conn->address_type == BD_ADDR_TYPE_ACL){
3712         l2cap_acl_classic_handler(handle, packet, size);
3713     } else {
3714         l2cap_acl_le_handler(handle, packet, size);
3715     }
3716 
3717     l2cap_run();
3718 }
3719 
3720 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
3721 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
3722     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
3723     if (!channel) return;
3724     channel->packet_handler = the_packet_handler;
3725 }
3726 
3727 #ifdef ENABLE_CLASSIC
3728 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
3729 void l2cap_finialize_channel_close(l2cap_channel_t * channel){
3730     channel->state = L2CAP_STATE_CLOSED;
3731     l2cap_handle_channel_closed(channel);
3732     // discard channel
3733     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3734     l2cap_free_channel_entry(channel);
3735 }
3736 #endif
3737 
3738 #ifdef L2CAP_USES_CHANNELS
3739 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3740     btstack_linked_list_iterator_t it;
3741     btstack_linked_list_iterator_init(&it, services);
3742     while (btstack_linked_list_iterator_has_next(&it)){
3743         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
3744         if ( service->psm == psm){
3745             return service;
3746         };
3747     }
3748     return NULL;
3749 }
3750 #endif
3751 
3752 #ifdef ENABLE_CLASSIC
3753 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
3754     return l2cap_get_service_internal(&l2cap_services, psm);
3755 }
3756 
3757 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
3758 
3759     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
3760 
3761     // check for alread registered psm
3762     l2cap_service_t *service = l2cap_get_service(psm);
3763     if (service) {
3764         log_error("l2cap_register_service: PSM %u already registered", psm);
3765         return L2CAP_SERVICE_ALREADY_REGISTERED;
3766     }
3767 
3768     // alloc structure
3769     service = btstack_memory_l2cap_service_get();
3770     if (!service) {
3771         log_error("l2cap_register_service: no memory for l2cap_service_t");
3772         return BTSTACK_MEMORY_ALLOC_FAILED;
3773     }
3774 
3775     // fill in
3776     service->psm = psm;
3777     service->mtu = mtu;
3778     service->packet_handler = service_packet_handler;
3779     service->required_security_level = security_level;
3780 
3781     // add to services list
3782     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
3783 
3784 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
3785     // enable page scan
3786     gap_connectable_control(1);
3787 #endif
3788 
3789     return ERROR_CODE_SUCCESS;
3790 }
3791 
3792 uint8_t l2cap_unregister_service(uint16_t psm){
3793 
3794     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
3795 
3796     l2cap_service_t *service = l2cap_get_service(psm);
3797     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3798     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
3799     btstack_memory_l2cap_service_free(service);
3800 
3801 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
3802     // disable page scan when no services registered
3803     if (btstack_linked_list_empty(&l2cap_services)) {
3804         gap_connectable_control(0);
3805     }
3806 #endif
3807 
3808     return ERROR_CODE_SUCCESS;
3809 }
3810 #endif
3811 
3812 
3813 #ifdef ENABLE_LE_DATA_CHANNELS
3814 
3815 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
3816     if (!channel->waiting_for_can_send_now) return;
3817     if (channel->send_sdu_buffer) return;
3818     channel->waiting_for_can_send_now = 0;
3819     log_debug("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
3820     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
3821 }
3822 
3823 // 1BH2222
3824 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
3825     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",
3826              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
3827     uint8_t event[19];
3828     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
3829     event[1] = sizeof(event) - 2u;
3830     event[2] = channel->address_type;
3831     reverse_bd_addr(channel->address, &event[3]);
3832     little_endian_store_16(event,  9, channel->con_handle);
3833     little_endian_store_16(event, 11, channel->psm);
3834     little_endian_store_16(event, 13, channel->local_cid);
3835     little_endian_store_16(event, 15, channel->remote_cid);
3836     little_endian_store_16(event, 17, channel->remote_mtu);
3837     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3838     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3839 }
3840 // 11BH22222
3841 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
3842     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",
3843              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
3844              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
3845     uint8_t event[23];
3846     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
3847     event[1] = sizeof(event) - 2u;
3848     event[2] = status;
3849     event[3] = channel->address_type;
3850     reverse_bd_addr(channel->address, &event[4]);
3851     little_endian_store_16(event, 10, channel->con_handle);
3852     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
3853     little_endian_store_16(event, 13, channel->psm);
3854     little_endian_store_16(event, 15, channel->local_cid);
3855     little_endian_store_16(event, 17, channel->remote_cid);
3856     little_endian_store_16(event, 19, channel->local_mtu);
3857     little_endian_store_16(event, 21, channel->remote_mtu);
3858     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3859     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3860 }
3861 // 2
3862 static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel){
3863     log_info("L2CAP_EVENT_LE_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
3864     uint8_t event[4];
3865     event[0] = L2CAP_EVENT_LE_CHANNEL_CLOSED;
3866     event[1] = sizeof(event) - 2u;
3867     little_endian_store_16(event, 2, channel->local_cid);
3868     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3869     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3870 }
3871 
3872 static void l2cap_le_send_pdu(l2cap_channel_t *channel){
3873     btstack_assert(channel != NULL);
3874     btstack_assert(channel->send_sdu_buffer != NULL);
3875     btstack_assert(channel->credits_outgoing > 0);
3876 
3877     // send part of SDU
3878     hci_reserve_packet_buffer();
3879     uint8_t * acl_buffer = hci_get_outgoing_packet_buffer();
3880     uint8_t * l2cap_payload = acl_buffer + 8;
3881     uint16_t pos = 0;
3882     if (!channel->send_sdu_pos){
3883         // store SDU len
3884         channel->send_sdu_pos += 2u;
3885         little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
3886         pos += 2u;
3887     }
3888     uint16_t payload_size = btstack_min(channel->send_sdu_len + 2u - channel->send_sdu_pos, channel->remote_mps - pos);
3889     log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
3890     (void)memcpy(&l2cap_payload[pos],
3891                  &channel->send_sdu_buffer[channel->send_sdu_pos - 2u],
3892                  payload_size); // -2 for virtual SDU len
3893     pos += payload_size;
3894     channel->send_sdu_pos += payload_size;
3895     l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
3896 
3897     channel->credits_outgoing--;
3898 
3899     hci_send_acl_packet_buffer(8u + pos);
3900 
3901     if (channel->send_sdu_pos >= (channel->send_sdu_len + 2u)){
3902         channel->send_sdu_buffer = NULL;
3903         // send done event
3904         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
3905         // inform about can send now
3906         l2cap_le_notify_channel_can_send(channel);
3907     }
3908 }
3909 
3910 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
3911 void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
3912     channel->state = L2CAP_STATE_CLOSED;
3913     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
3914     // discard channel
3915     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3916     l2cap_free_channel_entry(channel);
3917 }
3918 
3919 static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
3920     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
3921 }
3922 
3923 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
3924 
3925     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
3926 
3927     // check for alread registered psm
3928     l2cap_service_t *service = l2cap_le_get_service(psm);
3929     if (service) {
3930         return L2CAP_SERVICE_ALREADY_REGISTERED;
3931     }
3932 
3933     // alloc structure
3934     service = btstack_memory_l2cap_service_get();
3935     if (!service) {
3936         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
3937         return BTSTACK_MEMORY_ALLOC_FAILED;
3938     }
3939 
3940     // fill in
3941     service->psm = psm;
3942     service->mtu = 0;
3943     service->packet_handler = packet_handler;
3944     service->required_security_level = security_level;
3945 
3946     // add to services list
3947     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
3948 
3949     // done
3950     return ERROR_CODE_SUCCESS;
3951 }
3952 
3953 uint8_t l2cap_le_unregister_service(uint16_t psm) {
3954     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
3955     l2cap_service_t *service = l2cap_le_get_service(psm);
3956     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3957 
3958     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
3959     btstack_memory_l2cap_service_free(service);
3960     return ERROR_CODE_SUCCESS;
3961 }
3962 
3963 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
3964     // get channel
3965     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3966     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3967 
3968     // validate state
3969     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3970         return ERROR_CODE_COMMAND_DISALLOWED;
3971     }
3972 
3973     // set state accept connection
3974     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
3975     channel->receive_sdu_buffer = receive_sdu_buffer;
3976     channel->local_mtu = mtu;
3977     channel->new_credits_incoming = initial_credits;
3978     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
3979 
3980     // test
3981     // channel->new_credits_incoming = 1;
3982 
3983     // go
3984     l2cap_run();
3985     return ERROR_CODE_SUCCESS;
3986 }
3987 
3988 /**
3989  * @brief Deny incoming LE Data Channel connection due to resource constraints
3990  * @param local_cid             L2CAP LE Data Channel Identifier
3991  */
3992 
3993 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
3994     // get channel
3995     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3996     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3997 
3998     // validate state
3999     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
4000         return ERROR_CODE_COMMAND_DISALLOWED;
4001     }
4002 
4003     // set state decline connection
4004     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
4005     channel->reason = 0x04; // no resources available
4006     l2cap_run();
4007     return ERROR_CODE_SUCCESS;
4008 }
4009 
4010 static gap_security_level_t l2cap_le_security_level_for_connection(hci_con_handle_t con_handle){
4011     uint8_t encryption_key_size = gap_encryption_key_size(con_handle);
4012     if (encryption_key_size == 0) return LEVEL_0;
4013 
4014     uint8_t authenticated = gap_authenticated(con_handle);
4015     if (!authenticated) return LEVEL_2;
4016 
4017     return encryption_key_size == 16 ? LEVEL_4 : LEVEL_3;
4018 }
4019 
4020 // used to handle pairing complete after triggering to increase
4021 static void l2cap_sm_packet_handler(uint8_t packet_type, uint16_t channel_nr, uint8_t *packet, uint16_t size) {
4022     UNUSED(channel_nr);
4023     UNUSED(size);
4024     UNUSED(packet_type);
4025     btstack_assert(packet_type == HCI_EVENT_PACKET);
4026     if (hci_event_packet_get_type(packet) != SM_EVENT_PAIRING_COMPLETE) return;
4027     hci_con_handle_t con_handle = sm_event_pairing_complete_get_handle(packet);
4028     btstack_linked_list_iterator_t it;
4029     btstack_linked_list_iterator_init(&it, &l2cap_channels);
4030     while (btstack_linked_list_iterator_has_next(&it)) {
4031         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4032         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4033         if (channel->con_handle != con_handle) continue;
4034         if (channel->state != L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE) continue;
4035 
4036         // found channel, check security level
4037         if (l2cap_le_security_level_for_connection(con_handle) < channel->required_security_level){
4038             // pairing failed or wasn't good enough, inform user
4039             l2cap_emit_le_channel_opened(channel, ERROR_CODE_INSUFFICIENT_SECURITY);
4040             // discard channel
4041             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4042             l2cap_free_channel_entry(channel);
4043         } else {
4044             // send conn request now
4045             channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
4046             l2cap_run();
4047         }
4048     }
4049 }
4050 
4051 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
4052     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
4053     uint16_t * out_local_cid) {
4054 
4055     static btstack_packet_callback_registration_t sm_event_callback_registration;
4056     static bool sm_callback_registered = false;
4057 
4058     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
4059 
4060     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4061     if (!connection) {
4062         log_error("no hci_connection for handle 0x%04x", con_handle);
4063         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4064     }
4065 
4066     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);
4067     if (!channel) {
4068         return BTSTACK_MEMORY_ALLOC_FAILED;
4069     }
4070     log_info("l2cap_le_create_channel %p", channel);
4071 
4072     // store local_cid
4073     if (out_local_cid){
4074        *out_local_cid = channel->local_cid;
4075     }
4076 
4077     // setup channel entry
4078     channel->con_handle = con_handle;
4079     channel->receive_sdu_buffer = receive_sdu_buffer;
4080     channel->new_credits_incoming = initial_credits;
4081     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
4082 
4083     // add to connections list
4084     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
4085 
4086     // check security level
4087     if (l2cap_le_security_level_for_connection(con_handle) < channel->required_security_level){
4088         if (!sm_callback_registered){
4089             sm_callback_registered = true;
4090             // lazy registration for SM events
4091             sm_event_callback_registration.callback = &l2cap_sm_packet_handler;
4092             sm_add_event_handler(&sm_event_callback_registration);
4093         }
4094 
4095         // start pairing
4096         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
4097         sm_request_pairing(con_handle);
4098     } else {
4099         // send conn request right away
4100         channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
4101         l2cap_run();
4102     }
4103 
4104     return ERROR_CODE_SUCCESS;
4105 }
4106 
4107 /**
4108  * @brief Provide credtis for LE Data Channel
4109  * @param local_cid             L2CAP LE Data Channel Identifier
4110  * @param credits               Number additional credits for peer
4111  */
4112 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
4113 
4114     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4115     if (!channel) {
4116         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
4117         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4118     }
4119 
4120     // check state
4121     if (channel->state != L2CAP_STATE_OPEN){
4122         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
4123     }
4124 
4125     // assert incoming credits + credits <= 0xffff
4126     uint32_t total_credits = channel->credits_incoming;
4127     total_credits += channel->new_credits_incoming;
4128     total_credits += credits;
4129     if (total_credits > 0xffffu){
4130         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
4131             channel->new_credits_incoming, credits);
4132     }
4133 
4134     // set credits_granted
4135     channel->new_credits_incoming += credits;
4136 
4137     // go
4138     l2cap_run();
4139     return ERROR_CODE_SUCCESS;
4140 }
4141 
4142 /**
4143  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
4144  * @param local_cid             L2CAP LE Data Channel Identifier
4145  */
4146 int l2cap_le_can_send_now(uint16_t local_cid){
4147     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4148     if (!channel) {
4149         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
4150         return 0;
4151     }
4152 
4153     // check state
4154     if (channel->state != L2CAP_STATE_OPEN) return 0;
4155 
4156     // check queue
4157     if (channel->send_sdu_buffer) return 0;
4158 
4159     // fine, go ahead
4160     return 1;
4161 }
4162 
4163 /**
4164  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
4165  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
4166  *       so packet handler should be ready to handle it
4167  * @param local_cid             L2CAP LE Data Channel Identifier
4168  */
4169 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
4170     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4171     if (!channel) {
4172         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
4173         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4174     }
4175     channel->waiting_for_can_send_now = 1;
4176     l2cap_le_notify_channel_can_send(channel);
4177     return ERROR_CODE_SUCCESS;
4178 }
4179 
4180 /**
4181  * @brief Send data via LE Data Channel
4182  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
4183  * @param local_cid             L2CAP LE Data Channel Identifier
4184  * @param data                  data to send
4185  * @param size                  data size
4186  */
4187 uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
4188 
4189     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4190     if (!channel) {
4191         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4192         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4193     }
4194 
4195     if (len > channel->remote_mtu){
4196         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
4197         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
4198     }
4199 
4200     if (channel->send_sdu_buffer){
4201         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
4202         return BTSTACK_ACL_BUFFERS_FULL;
4203     }
4204 
4205     channel->send_sdu_buffer = data;
4206     channel->send_sdu_len    = len;
4207     channel->send_sdu_pos    = 0;
4208 
4209     l2cap_notify_channel_can_send();
4210     return ERROR_CODE_SUCCESS;
4211 }
4212 
4213 /**
4214  * @brief Disconnect from LE Data Channel
4215  * @param local_cid             L2CAP LE Data Channel Identifier
4216  */
4217 uint8_t l2cap_le_disconnect(uint16_t local_cid)
4218 {
4219     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4220     if (!channel) {
4221         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4222         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4223     }
4224 
4225     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4226     l2cap_run();
4227     return ERROR_CODE_SUCCESS;
4228 }
4229 
4230 #endif
4231