xref: /btstack/src/l2cap.c (revision cd5f23a3250874824c01a2b3326a9522fea3f99f)
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,  l2cap_next_sig_id(), 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 #ifdef ENABLE_CLASSIC
2293 static void l2cap_check_classic_timeout(hci_con_handle_t handle){
2294     if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) {
2295         return;
2296     }
2297     if (hci_authentication_active_for_handle(handle)) {
2298         return;
2299     }
2300     bool hci_con_used = false;
2301     btstack_linked_list_iterator_t it;
2302     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2303     while (btstack_linked_list_iterator_has_next(&it)){
2304         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2305         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2306         if (channel->con_handle != handle) continue;
2307         hci_con_used = true;
2308         break;
2309     }
2310     if (hci_con_used) {
2311         return;
2312     }
2313     if (!hci_can_send_command_packet_now()) {
2314         return;
2315     }
2316     hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
2317 }
2318 static void l2cap_handle_features_complete(hci_con_handle_t handle){
2319     hci_connection_t * hci_connection = hci_connection_for_handle(handle);
2320     if (hci_connection == NULL) {
2321         return;
2322     };
2323     if ((hci_connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) == 0) {
2324         return;
2325     }
2326     btstack_linked_list_iterator_t it;
2327     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2328     while (btstack_linked_list_iterator_has_next(&it)){
2329         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2330         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2331         if (channel->con_handle != handle) continue;
2332         log_info("remote supported features, channel %p, cid %04x - state %u", channel, channel->local_cid, channel->state);
2333         l2cap_handle_remote_supported_features_received(channel);
2334     }
2335 }
2336 static void l2cap_handle_security_level(hci_con_handle_t handle, gap_security_level_t actual_level){
2337     log_info("l2cap - security level update for handle 0x%04x", handle);
2338     btstack_linked_list_iterator_t it;
2339     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2340     while (btstack_linked_list_iterator_has_next(&it)){
2341         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2342         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2343         if (channel->con_handle != handle) continue;
2344 
2345          gap_security_level_t required_level = channel->required_security_level;
2346 
2347         log_info("channel %p, cid %04x - state %u: actual %u >= required %u?", channel, channel->local_cid, channel->state, actual_level, required_level);
2348 
2349         switch (channel->state){
2350             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2351                 if (actual_level >= required_level){
2352 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2353                     // we need to know if ERTM is supported before sending a config response
2354                     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
2355                     if (connection->l2cap_state.information_state != L2CAP_INFORMATION_STATE_DONE){
2356                         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2357                         channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
2358                         break;
2359                     }
2360 #endif
2361                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2362                     l2cap_emit_incoming_connection(channel);
2363                 } else {
2364                     channel->reason = 0x0003; // security block
2365                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2366                 }
2367                 break;
2368 
2369             case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2370                 if (actual_level >= required_level){
2371                     l2cap_ready_to_connect(channel);
2372                 } else {
2373                     // disconnnect, authentication not good enough
2374                     hci_disconnect_security_block(handle);
2375                 }
2376                 break;
2377 
2378             default:
2379                 break;
2380         }
2381     }
2382 }
2383 #endif
2384 
2385 #ifdef L2CAP_USES_CHANNELS
2386 static void l2cap_handle_disconnection_complete(hci_con_handle_t handle){
2387     // collect channels to close
2388     btstack_linked_list_t channels_to_close = NULL;
2389     btstack_linked_list_iterator_t it;
2390     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2391     while (btstack_linked_list_iterator_has_next(&it)) {
2392         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2393         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2394         if (channel->con_handle != handle) continue;
2395         btstack_linked_list_iterator_remove(&it);
2396         btstack_linked_list_add(&channels_to_close, (btstack_linked_item_t *) channel);
2397     }
2398     // send l2cap open failed or closed events for all channels on this handle and free them
2399     btstack_linked_list_iterator_init(&it, &channels_to_close);
2400     while (btstack_linked_list_iterator_has_next(&it)) {
2401         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2402         btstack_linked_list_iterator_remove(&it);
2403         switch(channel->channel_type){
2404 #ifdef ENABLE_CLASSIC
2405             case L2CAP_CHANNEL_TYPE_CLASSIC:
2406                 l2cap_handle_hci_disconnect_event(channel);
2407                 break;
2408 #endif
2409 #ifdef ENABLE_LE_DATA_CHANNELS
2410             case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
2411                 l2cap_handle_hci_le_disconnect_event(channel);
2412                 break;
2413 #endif
2414             default:
2415                 break;
2416         }
2417     }
2418 }
2419 #endif
2420 
2421 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
2422 
2423     UNUSED(packet_type); // ok: registered with hci_event_callback_registration
2424     UNUSED(cid);         // ok: there is no channel
2425     UNUSED(size);        // ok: fixed format events read from HCI buffer
2426 
2427 #ifdef ENABLE_CLASSIC
2428     bd_addr_t address;
2429     gap_security_level_t security_level;
2430 #endif
2431 #ifdef L2CAP_USES_CHANNELS
2432     hci_con_handle_t handle;
2433 #endif
2434 
2435     switch(hci_event_packet_get_type(packet)){
2436 
2437         // Notify channel packet handler if they can send now
2438         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2439         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
2440         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
2441             l2cap_run();    // try sending signaling packets first
2442             l2cap_notify_channel_can_send();
2443             break;
2444 
2445         case HCI_EVENT_COMMAND_STATUS:
2446 #ifdef ENABLE_CLASSIC
2447             // check command status for create connection for errors
2448             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
2449                 // cache outgoing address and reset
2450                 (void)memcpy(address, l2cap_outgoing_classic_addr, 6);
2451                 memset(l2cap_outgoing_classic_addr, 0, 6);
2452                 // error => outgoing connection failed
2453                 uint8_t status = hci_event_command_status_get_status(packet);
2454                 if (status){
2455                     l2cap_handle_connection_failed_for_addr(address, status);
2456                 }
2457             }
2458 #endif
2459             l2cap_run();    // try sending signaling packets first
2460             break;
2461 
2462 #ifdef ENABLE_CLASSIC
2463         // handle connection complete events
2464         case HCI_EVENT_CONNECTION_COMPLETE:
2465             reverse_bd_addr(&packet[5], address);
2466             if (packet[2] == 0){
2467                 handle = little_endian_read_16(packet, 3);
2468                 l2cap_handle_connection_success_for_addr(address, handle);
2469             } else {
2470                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
2471             }
2472             break;
2473 
2474         // handle successful create connection cancel command
2475         case HCI_EVENT_COMMAND_COMPLETE:
2476             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
2477                 if (packet[5] == 0){
2478                     reverse_bd_addr(&packet[6], address);
2479                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
2480                     l2cap_handle_connection_failed_for_addr(address, 0x16);
2481                 }
2482             }
2483             l2cap_run();    // try sending signaling packets first
2484             break;
2485 #endif
2486 
2487 #ifdef L2CAP_USES_CHANNELS
2488         // handle disconnection complete events
2489         case HCI_EVENT_DISCONNECTION_COMPLETE:
2490             handle = little_endian_read_16(packet, 3);
2491             l2cap_handle_disconnection_complete(handle);
2492             break;
2493 #endif
2494 
2495         // HCI Connection Timeouts
2496 #ifdef ENABLE_CLASSIC
2497         case L2CAP_EVENT_TIMEOUT_CHECK:
2498             handle = little_endian_read_16(packet, 2);
2499             l2cap_check_classic_timeout(handle);
2500             break;
2501 
2502         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2503         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
2504             handle = little_endian_read_16(packet, 3);
2505             l2cap_handle_features_complete(handle);
2506             break;
2507 
2508         case GAP_EVENT_SECURITY_LEVEL:
2509             handle = little_endian_read_16(packet, 2);
2510             security_level = (gap_security_level_t) packet[4];
2511             l2cap_handle_security_level(handle, security_level);
2512             break;
2513 #endif
2514         default:
2515             break;
2516     }
2517 
2518     l2cap_run();
2519 }
2520 
2521 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t cid, uint16_t data){
2522     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused."
2523     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
2524         signaling_responses[signaling_responses_pending].handle = handle;
2525         signaling_responses[signaling_responses_pending].code = code;
2526         signaling_responses[signaling_responses_pending].sig_id = sig_id;
2527         signaling_responses[signaling_responses_pending].cid = cid;
2528         signaling_responses[signaling_responses_pending].data = data;
2529         signaling_responses_pending++;
2530         l2cap_run();
2531     }
2532 }
2533 
2534 #ifdef ENABLE_CLASSIC
2535 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
2536     switch (channel->state){
2537         case L2CAP_STATE_CONFIG:
2538         case L2CAP_STATE_OPEN:
2539         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2540         case L2CAP_STATE_WAIT_DISCONNECT:
2541             break;
2542         default:
2543             // ignore in other states
2544             return;
2545     }
2546 
2547     channel->remote_sig_id = identifier;
2548     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
2549     l2cap_run();
2550 }
2551 
2552 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
2553 
2554     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
2555     l2cap_service_t *service = l2cap_get_service(psm);
2556     if (!service) {
2557         // 0x0002 PSM not supported
2558         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2559         return;
2560     }
2561 
2562     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
2563     if (!hci_connection) {
2564         //
2565         log_error("no hci_connection for handle %u", handle);
2566         return;
2567     }
2568 
2569     // alloc structure
2570     // log_info("l2cap_handle_connection_request register channel");
2571     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, hci_connection->address, BD_ADDR_TYPE_ACL,
2572     psm, service->mtu, service->required_security_level);
2573     if (!channel){
2574         // 0x0004 No resources available
2575         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2576         return;
2577     }
2578 
2579     channel->con_handle = handle;
2580     channel->remote_cid = source_cid;
2581     channel->remote_sig_id = sig_id;
2582 
2583     // limit local mtu to max acl packet length - l2cap header
2584     if (channel->local_mtu > l2cap_max_mtu()) {
2585         channel->local_mtu = l2cap_max_mtu();
2586     }
2587 
2588     // set initial state
2589     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
2590     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
2591 
2592     // add to connections list
2593     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2594 
2595     // assert security requirements
2596     gap_request_security_level(handle, channel->required_security_level);
2597 }
2598 
2599 void l2cap_accept_connection(uint16_t local_cid){
2600     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
2601     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2602     if (!channel) {
2603         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
2604         return;
2605     }
2606 
2607 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2608     // configure L2CAP Basic mode
2609     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
2610 #endif
2611 
2612     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
2613 
2614     // process
2615     l2cap_run();
2616 }
2617 
2618 void l2cap_decline_connection(uint16_t local_cid){
2619     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
2620     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
2621     if (!channel) {
2622         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
2623         return;
2624     }
2625     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2626     channel->reason = 0x04; // no resources available
2627     l2cap_run();
2628 }
2629 
2630 // @pre command len is valid, see check in l2cap_signaling_handler_channel
2631 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
2632 
2633 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2634     uint8_t use_fcs = 1;
2635 #endif
2636 
2637     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2638 
2639     uint16_t flags = little_endian_read_16(command, 6);
2640     if (flags & 1) {
2641         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
2642     }
2643 
2644     // accept the other's configuration options
2645     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2646     uint16_t pos     = 8;
2647     while (pos < end_pos){
2648         uint8_t option_hint = command[pos] >> 7;
2649         uint8_t option_type = command[pos] & 0x7f;
2650         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
2651         pos++;
2652         uint8_t length = command[pos++];
2653         // MTU { type(8): 1, len(8):2, MTU(16) }
2654         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) && (length == 2)){
2655             channel->remote_mtu = little_endian_read_16(command, pos);
2656             log_info("Remote MTU %u", channel->remote_mtu);
2657             if (channel->remote_mtu > l2cap_max_mtu()){
2658                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
2659                 channel->remote_mtu = l2cap_max_mtu();
2660             }
2661             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
2662         }
2663         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
2664         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT) && (length == 2)){
2665             channel->flush_timeout = little_endian_read_16(command, pos);
2666             log_info("Flush timeout: %u ms", channel->flush_timeout);
2667         }
2668 
2669 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2670         // Retransmission and Flow Control Option
2671         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2672             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
2673             switch(channel->mode){
2674                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2675                     // Store remote config
2676                     channel->remote_tx_window_size = command[pos+1];
2677                     channel->remote_max_transmit   = command[pos+2];
2678                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
2679                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
2680                     channel->remote_mps = little_endian_read_16(command, pos + 7);
2681                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
2682                         channel->remote_tx_window_size,
2683                         channel->remote_max_transmit,
2684                         channel->remote_retransmission_timeout_ms,
2685                         channel->remote_monitor_timeout_ms,
2686                         channel->remote_mps);
2687                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
2688                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
2689                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2690                     } else {
2691                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2692                     }
2693                     break;
2694                 case L2CAP_CHANNEL_MODE_BASIC:
2695                     switch (mode){
2696                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2697                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
2698                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
2699                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2700                             }
2701                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
2702                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
2703                             break;
2704                         default: // case L2CAP_CHANNEL_MODE_BASIC:
2705                             // TODO store and evaluate configuration
2706                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2707                             break;
2708                     }
2709                     break;
2710                 default:
2711                     break;
2712             }
2713         }
2714         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
2715             use_fcs = command[pos];
2716         }
2717 #endif
2718         // check for unknown options
2719         if ((option_hint == 0) && ((option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) || (option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE))){
2720             log_info("l2cap cid %u, unknown options", channel->local_cid);
2721             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
2722         }
2723         pos += length;
2724     }
2725 
2726 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2727         // "FCS" has precedence over "No FCS"
2728         uint8_t update = channel->fcs_option || use_fcs;
2729         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
2730         channel->fcs_option = update;
2731         // If ERTM mandatory, but remote didn't send Retransmission and Flowcontrol options -> disconnect
2732         if (((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM) == 0) & (channel->ertm_mandatory)){
2733             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2734         }
2735 #endif
2736 }
2737 
2738 // @pre command len is valid, see check in l2cap_signaling_handler_channel
2739 static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
2740     log_info("l2cap_signaling_handle_configure_response");
2741 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2742     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2743     uint16_t pos     = 10;
2744     while (pos < end_pos){
2745         uint8_t option_hint = command[pos] >> 7;
2746         uint8_t option_type = command[pos] & 0x7f;
2747         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
2748         pos++;
2749         uint8_t length = command[pos++];
2750 
2751         // Retransmission and Flow Control Option
2752         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2753             switch (channel->mode){
2754                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2755                     if (channel->ertm_mandatory){
2756                         // ??
2757                     } else {
2758                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
2759                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2760                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
2761                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2762                         }
2763                     }
2764                     break;
2765                 case L2CAP_CHANNEL_MODE_BASIC:
2766                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2767                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
2768                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2769                     }
2770                     break;
2771                 default:
2772                     break;
2773             }
2774         }
2775 
2776         // check for unknown options
2777         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
2778             log_info("l2cap cid %u, unknown options", channel->local_cid);
2779             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
2780         }
2781 
2782         pos += length;
2783     }
2784 #else
2785     UNUSED(channel);  // ok: no code
2786     UNUSED(result);   // ok: no code
2787     UNUSED(command);  // ok: no code
2788 #endif
2789 }
2790 
2791 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
2792     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
2793     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
2794     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
2795     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
2796     if (channel->state == L2CAP_STATE_OPEN) return 0;
2797     return 1;
2798 }
2799 
2800 
2801 // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
2802 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
2803 
2804     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2805     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2806     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2807     uint16_t result = 0;
2808 
2809     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
2810 
2811     // handle DISCONNECT REQUESTS seperately
2812     if (code == DISCONNECTION_REQUEST){
2813         l2cap_handle_disconnect_request(channel, identifier);
2814         return;
2815     }
2816 
2817     // @STATEMACHINE(l2cap)
2818     switch (channel->state) {
2819 
2820         case L2CAP_STATE_WAIT_CONNECT_RSP:
2821             switch (code){
2822                 case CONNECTION_RESPONSE:
2823                     if (cmd_len < 8){
2824                         // command imcomplete
2825                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2826                         break;
2827                     }
2828                     l2cap_stop_rtx(channel);
2829                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2830                     switch (result) {
2831                         case 0:
2832                             // successful connection
2833                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2834                             channel->state = L2CAP_STATE_CONFIG;
2835                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2836                             break;
2837                         case 1:
2838                             // connection pending. get some coffee, but start the ERTX
2839                             l2cap_start_ertx(channel);
2840                             break;
2841                         default:
2842                             // channel closed
2843                             channel->state = L2CAP_STATE_CLOSED;
2844                             // map l2cap connection response result to BTstack status enumeration
2845                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
2846 
2847                             // drop link key if security block
2848                             if ((L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result) == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
2849                                 gap_drop_link_key_for_bd_addr(channel->address);
2850                             }
2851 
2852                             // discard channel
2853                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2854                             l2cap_free_channel_entry(channel);
2855                             break;
2856                     }
2857                     break;
2858 
2859                 default:
2860                     //@TODO: implement other signaling packets
2861                     break;
2862             }
2863             break;
2864 
2865         case L2CAP_STATE_CONFIG:
2866             switch (code) {
2867                 case CONFIGURE_REQUEST:
2868                     if (cmd_len < 4){
2869                         // command incomplete
2870                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2871                         break;
2872                     }
2873                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
2874                     l2cap_signaling_handle_configure_request(channel, command);
2875                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
2876                         // only done if continuation not set
2877                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
2878                     }
2879                     break;
2880                 case CONFIGURE_RESPONSE:
2881                     if (cmd_len < 6){
2882                         // command incomplete
2883                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2884                         break;
2885                     }
2886                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2887                     l2cap_stop_rtx(channel);
2888                     l2cap_signaling_handle_configure_response(channel, result, command);
2889                     switch (result){
2890                         case 0: // success
2891                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
2892                             break;
2893                         case 4: // pending
2894                             l2cap_start_ertx(channel);
2895                             break;
2896                         default:
2897 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2898                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
2899                                 // remote does not offer ertm but it's required
2900                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2901                                 break;
2902                             }
2903 #endif
2904                             // retry on negative result
2905                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2906                             break;
2907                     }
2908                     break;
2909                 default:
2910                     break;
2911             }
2912             if (l2cap_channel_ready_for_open(channel)){
2913 
2914 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2915                 // assert that packet can be stored in fragment buffers in ertm
2916                 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
2917                     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
2918                     uint16_t usable_mtu = channel->num_tx_buffers == 1 ? effective_mps : channel->num_tx_buffers * effective_mps - 2;
2919                     if (usable_mtu < channel->remote_mtu){
2920                         log_info("Remote MTU %u > max storable ERTM packet, only using MTU = %u", channel->remote_mtu, usable_mtu);
2921                         channel->remote_mtu = usable_mtu;
2922                     }
2923                 }
2924 #endif
2925                 // for open:
2926                 channel->state = L2CAP_STATE_OPEN;
2927                 l2cap_emit_channel_opened(channel, 0);
2928             }
2929             break;
2930 
2931         case L2CAP_STATE_WAIT_DISCONNECT:
2932             switch (code) {
2933                 case DISCONNECTION_RESPONSE:
2934                     l2cap_finialize_channel_close(channel);
2935                     break;
2936                 default:
2937                     //@TODO: implement other signaling packets
2938                     break;
2939             }
2940             break;
2941 
2942         case L2CAP_STATE_CLOSED:
2943             // @TODO handle incoming requests
2944             break;
2945 
2946         case L2CAP_STATE_OPEN:
2947             //@TODO: implement other signaling packets, e.g. re-configure
2948             break;
2949         default:
2950             break;
2951     }
2952     // log_info("new state %u", channel->state);
2953 }
2954 
2955 
2956 // @pre command len is valid, see check in l2cap_acl_classic_handler
2957 static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
2958 
2959     btstack_linked_list_iterator_t it;
2960 
2961     // get code, signalind identifier and command len
2962     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2963     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2964     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2965 
2966     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
2967     if ((code < 1) || (code == ECHO_RESPONSE) || (code > INFORMATION_RESPONSE)){
2968         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2969         return;
2970     }
2971 
2972     // general commands without an assigned channel
2973     switch(code) {
2974 
2975         case CONNECTION_REQUEST:
2976             if (cmd_len == 4){
2977                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2978                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
2979                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
2980             } else {
2981                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2982             }
2983             return;
2984 
2985         case ECHO_REQUEST:
2986             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
2987             return;
2988 
2989         case INFORMATION_REQUEST:
2990             if (cmd_len == 2) {
2991                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2992                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
2993             } else {
2994                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2995             }
2996             return;
2997 
2998 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2999         case INFORMATION_RESPONSE: {
3000             hci_connection_t * connection = hci_connection_for_handle(handle);
3001             if (!connection) return;
3002             if (connection->l2cap_state.information_state != L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE) return;
3003 
3004             // get extended features from response if valid
3005             connection->l2cap_state.extended_feature_mask = 0;
3006             if (cmd_len >= 6) {
3007                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3008                 uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3009                 if (result == 0 && info_type == L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) {
3010                     connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3011                 }
3012             }
3013             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
3014             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
3015 
3016             // trigger connection request
3017             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3018             while (btstack_linked_list_iterator_has_next(&it)){
3019                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3020                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3021                 if (channel->con_handle != handle) continue;
3022 
3023                 // incoming connection: ask user for channel configuration, esp. if ertm will be mandatory
3024                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
3025                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
3026                     l2cap_emit_incoming_connection(channel);
3027                     continue;
3028                 }
3029 
3030                 // outgoing connection
3031                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
3032 
3033                     // if ERTM was requested, but is not listed in extended feature mask:
3034                     if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
3035 
3036                         if (channel->ertm_mandatory){
3037                             // bail if ERTM is mandatory
3038                             channel->state = L2CAP_STATE_CLOSED;
3039                             // map l2cap connection response result to BTstack status enumeration
3040                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
3041                             // discard channel
3042                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3043                             l2cap_free_channel_entry(channel);
3044                             continue;
3045 
3046                         } else {
3047                             // fallback to Basic mode
3048                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3049                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3050                         }
3051                     }
3052 
3053                     // respond to connection request
3054                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
3055                     continue;
3056                 }
3057             }
3058             return;
3059         }
3060 #endif
3061 
3062         default:
3063             break;
3064     }
3065 
3066     // Get potential destination CID
3067     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3068 
3069     // Find channel for this sig_id and connection handle
3070     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3071     while (btstack_linked_list_iterator_has_next(&it)){
3072         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3073         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3074         if (channel->con_handle != handle) continue;
3075         if (code & 1) {
3076             // match odd commands (responses) by previous signaling identifier
3077             if (channel->local_sig_id == sig_id) {
3078                 l2cap_signaling_handler_channel(channel, command);
3079                 break;
3080             }
3081         } else {
3082             // match even commands (requests) by local channel id
3083             if (channel->local_cid == dest_cid) {
3084                 l2cap_signaling_handler_channel(channel, command);
3085                 break;
3086             }
3087         }
3088     }
3089 }
3090 #endif
3091 
3092 #ifdef ENABLE_BLE
3093 
3094 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
3095     uint8_t event[6];
3096     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
3097     event[1] = 4;
3098     little_endian_store_16(event, 2, con_handle);
3099     little_endian_store_16(event, 4, result);
3100     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3101     if (!l2cap_event_packet_handler) return;
3102     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
3103 }
3104 
3105 // @returns valid
3106 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
3107     hci_connection_t * connection;
3108     uint16_t result;
3109     uint8_t  event[12];
3110 
3111 #ifdef ENABLE_LE_DATA_CHANNELS
3112     btstack_linked_list_iterator_t it;
3113     l2cap_channel_t * channel;
3114     uint16_t local_cid;
3115     uint16_t le_psm;
3116     uint16_t new_credits;
3117     uint16_t credits_before;
3118     l2cap_service_t * service;
3119     uint16_t source_cid;
3120 #endif
3121 
3122     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3123     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3124     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
3125 
3126     switch (code){
3127 
3128         case CONNECTION_PARAMETER_UPDATE_REQUEST:
3129             // check size
3130             if (len < 8u) return 0u;
3131             connection = hci_connection_for_handle(handle);
3132             if (connection != NULL){
3133                 if (connection->role != HCI_ROLE_MASTER){
3134                     // reject command without notifying upper layer when not in master role
3135                     return 0;
3136                 }
3137                 le_connection_parameter_range_t existing_range;
3138                 gap_get_connection_parameter_range(&existing_range);
3139                 uint16_t le_conn_interval_min   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3140                 uint16_t le_conn_interval_max   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3141                 uint16_t le_conn_latency        = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3142                 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
3143 
3144                 int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
3145                 if (update_parameter){
3146                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
3147                     connection->le_conn_interval_min = le_conn_interval_min;
3148                     connection->le_conn_interval_max = le_conn_interval_max;
3149                     connection->le_conn_latency = le_conn_latency;
3150                     connection->le_supervision_timeout = le_supervision_timeout;
3151                 } else {
3152                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
3153                 }
3154                 connection->le_con_param_update_identifier = sig_id;
3155             }
3156 
3157             if (!l2cap_event_packet_handler) break;
3158 
3159             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
3160             event[1] = 8;
3161             little_endian_store_16(event, 2, handle);
3162             (void)memcpy(&event[4], &command[4], 8);
3163             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3164             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
3165             break;
3166 
3167         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
3168             // check size
3169             if (len < 2u) return 0u;
3170             result = little_endian_read_16(command, 4);
3171             l2cap_emit_connection_parameter_update_response(handle, result);
3172             break;
3173 
3174 #ifdef ENABLE_LE_DATA_CHANNELS
3175 
3176         case COMMAND_REJECT:
3177             // Find channel for this sig_id and connection handle
3178             channel = NULL;
3179             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3180             while (btstack_linked_list_iterator_has_next(&it)){
3181                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3182                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
3183                 if (a_channel->con_handle   != handle) continue;
3184                 if (a_channel->local_sig_id != sig_id) continue;
3185                 channel = a_channel;
3186                 break;
3187             }
3188             if (!channel) break;
3189 
3190             // if received while waiting for le connection response, assume legacy device
3191             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
3192                 channel->state = L2CAP_STATE_CLOSED;
3193                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
3194                 l2cap_emit_le_channel_opened(channel, 0x0002);
3195 
3196                 // discard channel
3197                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3198                 l2cap_free_channel_entry(channel);
3199                 break;
3200             }
3201             break;
3202 
3203         case LE_CREDIT_BASED_CONNECTION_REQUEST:
3204             // check size
3205             if (len < 10u) return 0u;
3206 
3207             // get hci connection, bail if not found (must not happen)
3208             connection = hci_connection_for_handle(handle);
3209             if (!connection) return 0;
3210 
3211             // check if service registered
3212             le_psm  = little_endian_read_16(command, 4);
3213             service = l2cap_le_get_service(le_psm);
3214             source_cid = little_endian_read_16(command, 6);
3215 
3216             if (service){
3217                 if (source_cid < 0x40u){
3218                     // 0x0009 Connection refused - Invalid Source CID
3219                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
3220                     return 1;
3221                 }
3222 
3223                 // go through list of channels for this ACL connection and check if we get a match
3224                 btstack_linked_list_iterator_init(&it, &l2cap_channels);
3225                 while (btstack_linked_list_iterator_has_next(&it)){
3226                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3227                     if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
3228                     if (a_channel->con_handle != handle) continue;
3229                     if (a_channel->remote_cid != source_cid) continue;
3230                     // 0x000a Connection refused - Source CID already allocated
3231                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
3232                     return 1;
3233                 }
3234 
3235                 // security: check encryption
3236                 if (service->required_security_level >= LEVEL_2){
3237                     if (gap_encryption_key_size(handle) == 0){
3238                         // 0x0008 Connection refused - insufficient encryption
3239                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
3240                         return 1;
3241                     }
3242                     // anything less than 16 byte key size is insufficient
3243                     if (gap_encryption_key_size(handle) < 16){
3244                         // 0x0007 Connection refused – insufficient encryption key size
3245                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
3246                         return 1;
3247                     }
3248                 }
3249 
3250                 // security: check authencation
3251                 if (service->required_security_level >= LEVEL_3){
3252                     if (!gap_authenticated(handle)){
3253                         // 0x0005 Connection refused – insufficient authentication
3254                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
3255                         return 1;
3256                     }
3257                 }
3258 
3259                 // security: check authorization
3260                 if (service->required_security_level >= LEVEL_4){
3261                     if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
3262                         // 0x0006 Connection refused – insufficient authorization
3263                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
3264                         return 1;
3265                     }
3266                 }
3267 
3268                 // allocate channel
3269                 channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL, connection->address,
3270                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
3271                 if (!channel){
3272                     // 0x0004 Connection refused – no resources available
3273                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
3274                     return 1;
3275                 }
3276 
3277                 channel->con_handle = handle;
3278                 channel->remote_cid = source_cid;
3279                 channel->remote_sig_id = sig_id;
3280                 channel->remote_mtu = little_endian_read_16(command, 8);
3281                 channel->remote_mps = little_endian_read_16(command, 10);
3282                 channel->credits_outgoing = little_endian_read_16(command, 12);
3283 
3284                 // set initial state
3285                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
3286                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
3287 
3288                 // add to connections list
3289                 btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
3290 
3291                 // post connection request event
3292                 l2cap_emit_le_incoming_connection(channel);
3293 
3294             } else {
3295                 // Connection refused – LE_PSM not supported
3296                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
3297             }
3298             break;
3299 
3300         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
3301             // check size
3302             if (len < 10u) return 0u;
3303 
3304             // Find channel for this sig_id and connection handle
3305             channel = NULL;
3306             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3307             while (btstack_linked_list_iterator_has_next(&it)){
3308                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3309                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
3310                 if (a_channel->con_handle   != handle) continue;
3311                 if (a_channel->local_sig_id != sig_id) continue;
3312                 channel = a_channel;
3313                 break;
3314             }
3315             if (!channel) break;
3316 
3317             // cid + 0
3318             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
3319             if (result){
3320                 channel->state = L2CAP_STATE_CLOSED;
3321                 // map l2cap connection response result to BTstack status enumeration
3322                 l2cap_emit_le_channel_opened(channel, result);
3323 
3324                 // discard channel
3325                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3326                 l2cap_free_channel_entry(channel);
3327                 break;
3328             }
3329 
3330             // success
3331             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3332             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3333             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3334             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
3335             channel->state = L2CAP_STATE_OPEN;
3336             l2cap_emit_le_channel_opened(channel, result);
3337             break;
3338 
3339         case LE_FLOW_CONTROL_CREDIT:
3340             // check size
3341             if (len < 4u) return 0u;
3342 
3343             // find channel
3344             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3345             channel = l2cap_get_channel_for_local_cid_and_handle(local_cid, handle);
3346             if (!channel) {
3347                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
3348                 break;
3349             }
3350             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3351             credits_before = channel->credits_outgoing;
3352             channel->credits_outgoing += new_credits;
3353             // check for credit overrun
3354             if (credits_before > channel->credits_outgoing){
3355                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
3356                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3357                 break;
3358             }
3359             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
3360             break;
3361 
3362         case DISCONNECTION_REQUEST:
3363 
3364             // check size
3365             if (len < 4u) return 0u;
3366 
3367             // find channel
3368             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3369             channel = l2cap_get_channel_for_local_cid_and_handle(local_cid, handle);
3370             if (!channel) {
3371                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
3372                 break;
3373             }
3374             channel->remote_sig_id = sig_id;
3375             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
3376             break;
3377 
3378 #endif
3379 
3380         case DISCONNECTION_RESPONSE:
3381             break;
3382 
3383         default:
3384             // command unknown -> reject command
3385             return 0;
3386     }
3387     return 1;
3388 }
3389 #endif
3390 
3391 #ifdef ENABLE_CLASSIC
3392 static void l2cap_acl_classic_handler_for_channel(l2cap_channel_t * l2cap_channel, uint8_t * packet, uint16_t size){
3393 
3394     // forward data only in OPEN state
3395     if (l2cap_channel->state != L2CAP_STATE_OPEN) return;
3396 
3397 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3398     if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3399 
3400         int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
3401 
3402         // assert control + FCS fields are inside
3403         if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) return;
3404 
3405         if (l2cap_channel->fcs_option){
3406             // verify FCS (required if one side requested it)
3407             uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
3408             uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
3409 
3410 #ifdef L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL
3411             // simulate fcs error
3412                         static int counter = 0;
3413                         if (++counter == L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL) {
3414                             log_info("Simulate fcs error");
3415                             fcs_calculated++;
3416                             counter = 0;
3417                         }
3418 #endif
3419 
3420             if (fcs_calculated == fcs_packet){
3421                 log_info("Packet FCS 0x%04x verified", fcs_packet);
3422             } else {
3423                 log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
3424                 // ERTM State Machine in Bluetooth Spec does not handle 'I-Frame with invalid FCS'
3425                 return;
3426             }
3427         }
3428 
3429         // switch on packet type
3430         uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3431         uint8_t  req_seq = (control >> 8) & 0x3f;
3432         int final = (control >> 7) & 0x01;
3433         if (control & 1){
3434             // S-Frame
3435             int poll  = (control >> 4) & 0x01;
3436             l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
3437             log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
3438             l2cap_ertm_tx_packet_state_t * tx_state;
3439             switch (s){
3440                 case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
3441                     log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
3442                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3443                     if (poll && final){
3444                         // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
3445                         log_error("P=F=1 in S-Frame");
3446                         break;
3447                     }
3448                     if (poll){
3449                         // check if we did request selective retransmission before <==> we have stored SDU segments
3450                         int i;
3451                         int num_stored_out_of_order_packets = 0;
3452                         for (i=0;i<l2cap_channel->num_rx_buffers;i++){
3453                             int index = l2cap_channel->rx_store_index + i;
3454                             if (index >= l2cap_channel->num_rx_buffers){
3455                                 index -= l2cap_channel->num_rx_buffers;
3456                             }
3457                             l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3458                             if (!rx_state->valid) continue;
3459                             num_stored_out_of_order_packets++;
3460                         }
3461                         if (num_stored_out_of_order_packets){
3462                             l2cap_channel->send_supervisor_frame_selective_reject = 1;
3463                         } else {
3464                             l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
3465                         }
3466                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
3467                     }
3468                     if (final){
3469                         // Stop-MonitorTimer
3470                         l2cap_ertm_stop_monitor_timer(l2cap_channel);
3471                         // If UnackedFrames > 0 then Start-RetransTimer
3472                         if (l2cap_channel->unacked_frames){
3473                             l2cap_ertm_start_retransmission_timer(l2cap_channel);
3474                         }
3475                         // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3476                         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
3477                     }
3478                     break;
3479                 case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
3480                     log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
3481                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3482                     // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
3483                     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
3484                     break;
3485                 case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
3486                     log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
3487                     break;
3488                 case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
3489                     log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
3490                     if (poll){
3491                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3492                     }
3493                     // find requested i-frame
3494                     tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
3495                     if (tx_state){
3496                         log_info("Retransmission for tx_seq %u requested", req_seq);
3497                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
3498                         tx_state->retransmission_requested = 1;
3499                         l2cap_channel->srej_active = 1;
3500                     }
3501                     break;
3502                 default:
3503                     break;
3504             }
3505         } else {
3506             // I-Frame
3507             // get control
3508             l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
3509             uint8_t tx_seq = (control >> 1) & 0x3f;
3510             log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
3511             log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
3512             log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
3513             l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3514             if (final){
3515                 // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3516                 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
3517             }
3518 
3519             // get SDU
3520             const uint8_t * payload_data = &packet[COMPLETE_L2CAP_HEADER+2];
3521             uint16_t        payload_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
3522 
3523             // assert SDU size is smaller or equal to our buffers
3524             uint16_t max_payload_size = 0;
3525             switch (sar){
3526                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
3527                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
3528                     // SDU Length + MPS
3529                     max_payload_size = l2cap_channel->local_mps + 2;
3530                     break;
3531                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
3532                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
3533                     max_payload_size = l2cap_channel->local_mps;
3534                     break;
3535                 default:
3536                     btstack_assert(false);
3537                     break;
3538             }
3539             if (payload_len > max_payload_size){
3540                 log_info("payload len %u > max payload %u -> drop packet", payload_len, max_payload_size);
3541                 return;
3542             }
3543 
3544             // check ordering
3545             if (l2cap_channel->expected_tx_seq == tx_seq){
3546                 log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
3547                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3548                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3549 
3550                 // process SDU
3551                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, payload_data, payload_len);
3552 
3553                 // process stored segments
3554                 while (true){
3555                     int index = l2cap_channel->rx_store_index;
3556                     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3557                     if (!rx_state->valid) break;
3558 
3559                     log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
3560                     l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3561                     l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3562 
3563                     rx_state->valid = 0;
3564                     l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
3565 
3566                     // update rx store index
3567                     index++;
3568                     if (index >= l2cap_channel->num_rx_buffers){
3569                         index = 0;
3570                     }
3571                     l2cap_channel->rx_store_index = index;
3572                 }
3573 
3574                 //
3575                 l2cap_channel->send_supervisor_frame_receiver_ready = 1;
3576 
3577             } else {
3578                 int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
3579                 if (delta < 2){
3580                     // store segment
3581                     l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, payload_data, payload_len);
3582 
3583                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
3584                     l2cap_channel->send_supervisor_frame_selective_reject = 1;
3585                 } else {
3586                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
3587                     l2cap_channel->send_supervisor_frame_reject = 1;
3588                 }
3589             }
3590         }
3591         return;
3592     }
3593 #endif
3594 
3595     // check size
3596     uint16_t payload_size = size - COMPLETE_L2CAP_HEADER;
3597     if (l2cap_channel->local_mtu < payload_size) return;
3598 
3599     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], payload_size);
3600 }
3601 #endif
3602 
3603 static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3604 #ifdef ENABLE_CLASSIC
3605     l2cap_channel_t * l2cap_channel;
3606     l2cap_fixed_channel_t * l2cap_fixed_channel;
3607 
3608     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3609     uint8_t  broadcast_flag = READ_ACL_FLAGS(packet) >> 2;
3610     switch (channel_id) {
3611 
3612         case L2CAP_CID_SIGNALING: {
3613             if (broadcast_flag != 0) break;
3614             uint32_t command_offset = 8;
3615             while ((command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET) < size) {
3616                 // assert signaling command is fully inside packet
3617                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3618                 uint32_t next_command_offset = command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
3619                 if (next_command_offset > size){
3620                     log_error("l2cap signaling command len invalid -> drop");
3621                     break;
3622                 }
3623                 // handle signaling command
3624                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
3625                 // go to next command
3626                 command_offset = next_command_offset;
3627             }
3628             break;
3629         }
3630         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
3631             if (broadcast_flag == 0) break;
3632             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL);
3633             if (!l2cap_fixed_channel) break;
3634             if (!l2cap_fixed_channel->packet_handler) break;
3635             (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3636             break;
3637 
3638         default:
3639             if (broadcast_flag != 0) break;
3640             // Find channel for this channel_id and connection handle
3641             l2cap_channel = l2cap_get_channel_for_local_cid_and_handle(channel_id, handle);
3642             if (l2cap_channel != NULL){
3643                 l2cap_acl_classic_handler_for_channel(l2cap_channel, packet, size);
3644             }
3645             break;
3646     }
3647 #else
3648     UNUSED(handle); // ok: no code
3649     UNUSED(packet); // ok: no code
3650     UNUSED(size);   // ok: no code
3651 #endif
3652 }
3653 
3654 static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3655 #ifdef ENABLE_BLE
3656 
3657     l2cap_fixed_channel_t * l2cap_fixed_channel;
3658 
3659 #ifdef ENABLE_LE_DATA_CHANNELS
3660     l2cap_channel_t * l2cap_channel;
3661 #endif
3662     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3663     switch (channel_id) {
3664 
3665         case L2CAP_CID_SIGNALING_LE: {
3666             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
3667             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
3668             if ((COMPLETE_L2CAP_HEADER + 4u + len) > size) break;
3669             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
3670             if (!valid){
3671                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3672             }
3673             break;
3674         }
3675 
3676         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
3677             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL);
3678             if (!l2cap_fixed_channel) break;
3679             if (!l2cap_fixed_channel->packet_handler) break;
3680             (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3681             break;
3682 
3683         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
3684             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
3685             if (!l2cap_fixed_channel) break;
3686             if (!l2cap_fixed_channel->packet_handler) break;
3687             (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3688             break;
3689 
3690         default:
3691 
3692 #ifdef ENABLE_LE_DATA_CHANNELS
3693             l2cap_channel = l2cap_get_channel_for_local_cid_and_handle(channel_id, handle);
3694             if (l2cap_channel != NULL) {
3695                 // credit counting
3696                 if (l2cap_channel->credits_incoming == 0u){
3697                     log_info("LE Data Channel packet received but no incoming credits");
3698                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3699                     break;
3700                 }
3701                 l2cap_channel->credits_incoming--;
3702 
3703                 // automatic credits
3704                 if ((l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK) && l2cap_channel->automatic_credits){
3705                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
3706                 }
3707 
3708                 // first fragment
3709                 uint16_t pos = 0;
3710                 if (!l2cap_channel->receive_sdu_len){
3711                     uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3712                     if(sdu_len > l2cap_channel->local_mtu) break;   // SDU would be larger than our buffer
3713                     l2cap_channel->receive_sdu_len = sdu_len;
3714                     l2cap_channel->receive_sdu_pos = 0;
3715                     pos  += 2u;
3716                     size -= 2u;
3717                 }
3718                 uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
3719                 uint16_t remaining_space = l2cap_channel->local_mtu - l2cap_channel->receive_sdu_pos;
3720                 if (fragment_size > remaining_space) break;         // SDU would cause buffer overrun
3721                 (void)memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos],
3722                              &packet[COMPLETE_L2CAP_HEADER + pos],
3723                              fragment_size);
3724                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
3725                 // done?
3726                 log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
3727                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
3728                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
3729                     l2cap_channel->receive_sdu_len = 0;
3730                 }
3731             }
3732 #endif
3733             break;
3734     }
3735 #else
3736     UNUSED(handle); // ok: no code
3737     UNUSED(packet); // ok: no code
3738     UNUSED(size);   // ok: no code
3739 #endif
3740 }
3741 
3742 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
3743     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
3744     UNUSED(channel);        // ok: there is no channel
3745 
3746     // Assert full L2CAP header present
3747     if (size < COMPLETE_L2CAP_HEADER) return;
3748 
3749     // Dispatch to Classic or LE handler (SCO packets are not dispatched to L2CAP)
3750     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
3751     hci_connection_t *conn = hci_connection_for_handle(handle);
3752     if (!conn) return;
3753     if (conn->address_type == BD_ADDR_TYPE_ACL){
3754         l2cap_acl_classic_handler(handle, packet, size);
3755     } else {
3756         l2cap_acl_le_handler(handle, packet, size);
3757     }
3758 
3759     l2cap_run();
3760 }
3761 
3762 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
3763 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
3764     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
3765     if (!channel) return;
3766     channel->packet_handler = the_packet_handler;
3767 }
3768 
3769 #ifdef ENABLE_CLASSIC
3770 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
3771 void l2cap_finialize_channel_close(l2cap_channel_t * channel){
3772     channel->state = L2CAP_STATE_CLOSED;
3773     l2cap_handle_channel_closed(channel);
3774     // discard channel
3775     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3776     l2cap_free_channel_entry(channel);
3777 }
3778 #endif
3779 
3780 #ifdef L2CAP_USES_CHANNELS
3781 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3782     btstack_linked_list_iterator_t it;
3783     btstack_linked_list_iterator_init(&it, services);
3784     while (btstack_linked_list_iterator_has_next(&it)){
3785         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
3786         if ( service->psm == psm){
3787             return service;
3788         };
3789     }
3790     return NULL;
3791 }
3792 #endif
3793 
3794 #ifdef ENABLE_CLASSIC
3795 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
3796     return l2cap_get_service_internal(&l2cap_services, psm);
3797 }
3798 
3799 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
3800 
3801     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
3802 
3803     // check for alread registered psm
3804     l2cap_service_t *service = l2cap_get_service(psm);
3805     if (service) {
3806         log_error("l2cap_register_service: PSM %u already registered", psm);
3807         return L2CAP_SERVICE_ALREADY_REGISTERED;
3808     }
3809 
3810     // alloc structure
3811     service = btstack_memory_l2cap_service_get();
3812     if (!service) {
3813         log_error("l2cap_register_service: no memory for l2cap_service_t");
3814         return BTSTACK_MEMORY_ALLOC_FAILED;
3815     }
3816 
3817     // fill in
3818     service->psm = psm;
3819     service->mtu = mtu;
3820     service->packet_handler = service_packet_handler;
3821     service->required_security_level = security_level;
3822 
3823     // add to services list
3824     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
3825 
3826 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
3827     // enable page scan
3828     gap_connectable_control(1);
3829 #endif
3830 
3831     return ERROR_CODE_SUCCESS;
3832 }
3833 
3834 uint8_t l2cap_unregister_service(uint16_t psm){
3835 
3836     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
3837 
3838     l2cap_service_t *service = l2cap_get_service(psm);
3839     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3840     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
3841     btstack_memory_l2cap_service_free(service);
3842 
3843 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
3844     // disable page scan when no services registered
3845     if (btstack_linked_list_empty(&l2cap_services)) {
3846         gap_connectable_control(0);
3847     }
3848 #endif
3849 
3850     return ERROR_CODE_SUCCESS;
3851 }
3852 #endif
3853 
3854 
3855 #ifdef ENABLE_LE_DATA_CHANNELS
3856 
3857 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
3858     if (!channel->waiting_for_can_send_now) return;
3859     if (channel->send_sdu_buffer) return;
3860     channel->waiting_for_can_send_now = 0;
3861     log_debug("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
3862     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
3863 }
3864 
3865 // 1BH2222
3866 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
3867     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",
3868              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
3869     uint8_t event[19];
3870     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
3871     event[1] = sizeof(event) - 2u;
3872     event[2] = channel->address_type;
3873     reverse_bd_addr(channel->address, &event[3]);
3874     little_endian_store_16(event,  9, channel->con_handle);
3875     little_endian_store_16(event, 11, channel->psm);
3876     little_endian_store_16(event, 13, channel->local_cid);
3877     little_endian_store_16(event, 15, channel->remote_cid);
3878     little_endian_store_16(event, 17, channel->remote_mtu);
3879     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3880     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3881 }
3882 // 11BH22222
3883 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
3884     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",
3885              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
3886              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
3887     uint8_t event[23];
3888     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
3889     event[1] = sizeof(event) - 2u;
3890     event[2] = status;
3891     event[3] = channel->address_type;
3892     reverse_bd_addr(channel->address, &event[4]);
3893     little_endian_store_16(event, 10, channel->con_handle);
3894     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
3895     little_endian_store_16(event, 13, channel->psm);
3896     little_endian_store_16(event, 15, channel->local_cid);
3897     little_endian_store_16(event, 17, channel->remote_cid);
3898     little_endian_store_16(event, 19, channel->local_mtu);
3899     little_endian_store_16(event, 21, channel->remote_mtu);
3900     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3901     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3902 }
3903 // 2
3904 static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel){
3905     log_info("L2CAP_EVENT_LE_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
3906     uint8_t event[4];
3907     event[0] = L2CAP_EVENT_LE_CHANNEL_CLOSED;
3908     event[1] = sizeof(event) - 2u;
3909     little_endian_store_16(event, 2, channel->local_cid);
3910     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3911     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3912 }
3913 
3914 static void l2cap_le_send_pdu(l2cap_channel_t *channel){
3915     btstack_assert(channel != NULL);
3916     btstack_assert(channel->send_sdu_buffer != NULL);
3917     btstack_assert(channel->credits_outgoing > 0);
3918 
3919     // send part of SDU
3920     hci_reserve_packet_buffer();
3921     uint8_t * acl_buffer = hci_get_outgoing_packet_buffer();
3922     uint8_t * l2cap_payload = acl_buffer + 8;
3923     uint16_t pos = 0;
3924     if (!channel->send_sdu_pos){
3925         // store SDU len
3926         channel->send_sdu_pos += 2u;
3927         little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
3928         pos += 2u;
3929     }
3930     uint16_t payload_size = btstack_min(channel->send_sdu_len + 2u - channel->send_sdu_pos, channel->remote_mps - pos);
3931     log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
3932     (void)memcpy(&l2cap_payload[pos],
3933                  &channel->send_sdu_buffer[channel->send_sdu_pos - 2u],
3934                  payload_size); // -2 for virtual SDU len
3935     pos += payload_size;
3936     channel->send_sdu_pos += payload_size;
3937     l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
3938 
3939     channel->credits_outgoing--;
3940 
3941     hci_send_acl_packet_buffer(8u + pos);
3942 
3943     if (channel->send_sdu_pos >= (channel->send_sdu_len + 2u)){
3944         channel->send_sdu_buffer = NULL;
3945         // send done event
3946         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
3947         // inform about can send now
3948         l2cap_le_notify_channel_can_send(channel);
3949     }
3950 }
3951 
3952 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
3953 void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
3954     channel->state = L2CAP_STATE_CLOSED;
3955     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
3956     // discard channel
3957     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3958     l2cap_free_channel_entry(channel);
3959 }
3960 
3961 static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
3962     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
3963 }
3964 
3965 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
3966 
3967     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
3968 
3969     // check for alread registered psm
3970     l2cap_service_t *service = l2cap_le_get_service(psm);
3971     if (service) {
3972         return L2CAP_SERVICE_ALREADY_REGISTERED;
3973     }
3974 
3975     // alloc structure
3976     service = btstack_memory_l2cap_service_get();
3977     if (!service) {
3978         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
3979         return BTSTACK_MEMORY_ALLOC_FAILED;
3980     }
3981 
3982     // fill in
3983     service->psm = psm;
3984     service->mtu = 0;
3985     service->packet_handler = packet_handler;
3986     service->required_security_level = security_level;
3987 
3988     // add to services list
3989     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
3990 
3991     // done
3992     return ERROR_CODE_SUCCESS;
3993 }
3994 
3995 uint8_t l2cap_le_unregister_service(uint16_t psm) {
3996     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
3997     l2cap_service_t *service = l2cap_le_get_service(psm);
3998     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3999 
4000     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
4001     btstack_memory_l2cap_service_free(service);
4002     return ERROR_CODE_SUCCESS;
4003 }
4004 
4005 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
4006     // get channel
4007     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4008     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4009 
4010     // validate state
4011     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
4012         return ERROR_CODE_COMMAND_DISALLOWED;
4013     }
4014 
4015     // set state accept connection
4016     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
4017     channel->receive_sdu_buffer = receive_sdu_buffer;
4018     channel->local_mtu = mtu;
4019     channel->new_credits_incoming = initial_credits;
4020     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
4021 
4022     // test
4023     // channel->new_credits_incoming = 1;
4024 
4025     // go
4026     l2cap_run();
4027     return ERROR_CODE_SUCCESS;
4028 }
4029 
4030 /**
4031  * @brief Deny incoming LE Data Channel connection due to resource constraints
4032  * @param local_cid             L2CAP LE Data Channel Identifier
4033  */
4034 
4035 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
4036     // get channel
4037     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4038     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4039 
4040     // validate state
4041     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
4042         return ERROR_CODE_COMMAND_DISALLOWED;
4043     }
4044 
4045     // set state decline connection
4046     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
4047     channel->reason = 0x04; // no resources available
4048     l2cap_run();
4049     return ERROR_CODE_SUCCESS;
4050 }
4051 
4052 static gap_security_level_t l2cap_le_security_level_for_connection(hci_con_handle_t con_handle){
4053     uint8_t encryption_key_size = gap_encryption_key_size(con_handle);
4054     if (encryption_key_size == 0) return LEVEL_0;
4055 
4056     uint8_t authenticated = gap_authenticated(con_handle);
4057     if (!authenticated) return LEVEL_2;
4058 
4059     return encryption_key_size == 16 ? LEVEL_4 : LEVEL_3;
4060 }
4061 
4062 // used to handle pairing complete after triggering to increase
4063 static void l2cap_sm_packet_handler(uint8_t packet_type, uint16_t channel_nr, uint8_t *packet, uint16_t size) {
4064     UNUSED(channel_nr);
4065     UNUSED(size);
4066     UNUSED(packet_type);
4067     btstack_assert(packet_type == HCI_EVENT_PACKET);
4068     if (hci_event_packet_get_type(packet) != SM_EVENT_PAIRING_COMPLETE) return;
4069     hci_con_handle_t con_handle = sm_event_pairing_complete_get_handle(packet);
4070     btstack_linked_list_iterator_t it;
4071     btstack_linked_list_iterator_init(&it, &l2cap_channels);
4072     while (btstack_linked_list_iterator_has_next(&it)) {
4073         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4074         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4075         if (channel->con_handle != con_handle) continue;
4076         if (channel->state != L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE) continue;
4077 
4078         // found channel, check security level
4079         if (l2cap_le_security_level_for_connection(con_handle) < channel->required_security_level){
4080             // pairing failed or wasn't good enough, inform user
4081             l2cap_emit_le_channel_opened(channel, ERROR_CODE_INSUFFICIENT_SECURITY);
4082             // discard channel
4083             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4084             l2cap_free_channel_entry(channel);
4085         } else {
4086             // send conn request now
4087             channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
4088             l2cap_run();
4089         }
4090     }
4091 }
4092 
4093 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
4094     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
4095     uint16_t * out_local_cid) {
4096 
4097     static btstack_packet_callback_registration_t sm_event_callback_registration;
4098     static bool sm_callback_registered = false;
4099 
4100     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
4101 
4102     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4103     if (!connection) {
4104         log_error("no hci_connection for handle 0x%04x", con_handle);
4105         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4106     }
4107 
4108     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);
4109     if (!channel) {
4110         return BTSTACK_MEMORY_ALLOC_FAILED;
4111     }
4112     log_info("l2cap_le_create_channel %p", channel);
4113 
4114     // store local_cid
4115     if (out_local_cid){
4116        *out_local_cid = channel->local_cid;
4117     }
4118 
4119     // setup channel entry
4120     channel->con_handle = con_handle;
4121     channel->receive_sdu_buffer = receive_sdu_buffer;
4122     channel->new_credits_incoming = initial_credits;
4123     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
4124 
4125     // add to connections list
4126     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
4127 
4128     // check security level
4129     if (l2cap_le_security_level_for_connection(con_handle) < channel->required_security_level){
4130         if (!sm_callback_registered){
4131             sm_callback_registered = true;
4132             // lazy registration for SM events
4133             sm_event_callback_registration.callback = &l2cap_sm_packet_handler;
4134             sm_add_event_handler(&sm_event_callback_registration);
4135         }
4136 
4137         // start pairing
4138         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
4139         sm_request_pairing(con_handle);
4140     } else {
4141         // send conn request right away
4142         channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
4143         l2cap_run();
4144     }
4145 
4146     return ERROR_CODE_SUCCESS;
4147 }
4148 
4149 /**
4150  * @brief Provide credtis for LE Data Channel
4151  * @param local_cid             L2CAP LE Data Channel Identifier
4152  * @param credits               Number additional credits for peer
4153  */
4154 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
4155 
4156     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4157     if (!channel) {
4158         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
4159         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4160     }
4161 
4162     // check state
4163     if (channel->state != L2CAP_STATE_OPEN){
4164         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
4165     }
4166 
4167     // assert incoming credits + credits <= 0xffff
4168     uint32_t total_credits = channel->credits_incoming;
4169     total_credits += channel->new_credits_incoming;
4170     total_credits += credits;
4171     if (total_credits > 0xffffu){
4172         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
4173             channel->new_credits_incoming, credits);
4174     }
4175 
4176     // set credits_granted
4177     channel->new_credits_incoming += credits;
4178 
4179     // go
4180     l2cap_run();
4181     return ERROR_CODE_SUCCESS;
4182 }
4183 
4184 /**
4185  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
4186  * @param local_cid             L2CAP LE Data Channel Identifier
4187  */
4188 int l2cap_le_can_send_now(uint16_t local_cid){
4189     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4190     if (!channel) {
4191         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
4192         return 0;
4193     }
4194 
4195     // check state
4196     if (channel->state != L2CAP_STATE_OPEN) return 0;
4197 
4198     // check queue
4199     if (channel->send_sdu_buffer) return 0;
4200 
4201     // fine, go ahead
4202     return 1;
4203 }
4204 
4205 /**
4206  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
4207  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
4208  *       so packet handler should be ready to handle it
4209  * @param local_cid             L2CAP LE Data Channel Identifier
4210  */
4211 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
4212     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4213     if (!channel) {
4214         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
4215         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4216     }
4217     channel->waiting_for_can_send_now = 1;
4218     l2cap_le_notify_channel_can_send(channel);
4219     return ERROR_CODE_SUCCESS;
4220 }
4221 
4222 /**
4223  * @brief Send data via LE Data Channel
4224  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
4225  * @param local_cid             L2CAP LE Data Channel Identifier
4226  * @param data                  data to send
4227  * @param size                  data size
4228  */
4229 uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
4230 
4231     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4232     if (!channel) {
4233         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4234         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4235     }
4236 
4237     if (len > channel->remote_mtu){
4238         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
4239         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
4240     }
4241 
4242     if (channel->send_sdu_buffer){
4243         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
4244         return BTSTACK_ACL_BUFFERS_FULL;
4245     }
4246 
4247     channel->send_sdu_buffer = data;
4248     channel->send_sdu_len    = len;
4249     channel->send_sdu_pos    = 0;
4250 
4251     l2cap_notify_channel_can_send();
4252     return ERROR_CODE_SUCCESS;
4253 }
4254 
4255 /**
4256  * @brief Disconnect from LE Data Channel
4257  * @param local_cid             L2CAP LE Data Channel Identifier
4258  */
4259 uint8_t l2cap_le_disconnect(uint16_t local_cid)
4260 {
4261     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4262     if (!channel) {
4263         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4264         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4265     }
4266 
4267     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4268     l2cap_run();
4269     return ERROR_CODE_SUCCESS;
4270 }
4271 
4272 #endif
4273