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