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