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