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