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