xref: /btstack/src/l2cap.c (revision a8d51f092f1b660d0f6921369ad2bc3f9368296c)
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         default:
834             btstack_assert(false);
835             break;
836     }
837 }
838 
839 static void l2cap_ertm_channel_send_information_frame(l2cap_channel_t * channel){
840     channel->unacked_frames++;
841     int index = channel->tx_send_index;
842     channel->tx_send_index++;
843     if (channel->tx_send_index >= channel->num_tx_buffers){
844         channel->tx_send_index = 0;
845     }
846     l2cap_ertm_send_information_frame(channel, index, 0);   // final = 0
847 }
848 
849 #endif
850 
851 #ifdef L2CAP_USES_CHANNELS
852 static uint16_t l2cap_next_local_cid(void){
853     do {
854         if (local_source_cid == 0xffffu) {
855             local_source_cid = 0x40;
856         } else {
857             local_source_cid++;
858         }
859     } while (l2cap_get_channel_for_local_cid(local_source_cid) != NULL);
860     return local_source_cid;
861 }
862 #endif
863 
864 static uint8_t l2cap_next_sig_id(void){
865     if (sig_seq_nr == 0xffu) {
866         sig_seq_nr = 1;
867     } else {
868         sig_seq_nr++;
869     }
870     return sig_seq_nr;
871 }
872 
873 void l2cap_init(void){
874     signaling_responses_pending = 0;
875 
876     l2cap_channels = NULL;
877 
878 #ifdef ENABLE_CLASSIC
879     l2cap_services = NULL;
880     require_security_level2_for_outgoing_sdp = 0;
881 
882     // Setup Connectionless Channel
883     l2cap_fixed_channel_connectionless.local_cid     = L2CAP_CID_CONNECTIONLESS_CHANNEL;
884     l2cap_fixed_channel_connectionless.channel_type  = L2CAP_CHANNEL_TYPE_CONNECTIONLESS;
885     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_connectionless);
886 #endif
887 
888 #ifdef ENABLE_LE_DATA_CHANNELS
889     l2cap_le_services = NULL;
890 #endif
891 
892 #ifdef ENABLE_BLE
893     l2cap_event_packet_handler = NULL;
894     l2cap_le_custom_max_mtu = 0;
895 
896     // Setup fixed ATT Channel
897     l2cap_fixed_channel_att.local_cid    = L2CAP_CID_ATTRIBUTE_PROTOCOL;
898     l2cap_fixed_channel_att.channel_type = L2CAP_CHANNEL_TYPE_LE_FIXED;
899     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_att);
900 
901     // Setup fixed SM Channel
902     l2cap_fixed_channel_sm.local_cid     = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
903     l2cap_fixed_channel_sm.channel_type  = L2CAP_CHANNEL_TYPE_LE_FIXED;
904     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_sm);
905 #endif
906 
907     //
908     // register callback with HCI
909     //
910     hci_event_callback_registration.callback = &l2cap_hci_event_handler;
911     hci_add_event_handler(&hci_event_callback_registration);
912 
913     hci_register_acl_packet_handler(&l2cap_acl_handler);
914 
915 #ifdef ENABLE_CLASSIC
916     gap_connectable_control(0); // no services yet
917 #endif
918 }
919 
920 void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
921 #ifdef ENABLE_BLE
922     l2cap_event_packet_handler = handler;
923 #else
924     UNUSED(handler);    // ok: no code
925 #endif
926 }
927 
928 void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
929     UNUSED(con_handle);  // ok: there is no con handle
930 
931     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
932     if (!channel) return;
933     channel->waiting_for_can_send_now = 1;
934     l2cap_notify_channel_can_send();
935 }
936 
937 int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
938     UNUSED(channel_id); // ok: only depends on Controller LE buffers
939 
940     return hci_can_send_acl_packet_now(con_handle);
941 }
942 
943 uint8_t *l2cap_get_outgoing_buffer(void){
944     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
945 }
946 
947 // only for L2CAP Basic Channels
948 int l2cap_reserve_packet_buffer(void){
949     return hci_reserve_packet_buffer();
950 }
951 
952 // only for L2CAP Basic Channels
953 void l2cap_release_packet_buffer(void){
954     hci_release_packet_buffer();
955 }
956 
957 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){
958     // 0 - Connection handle : PB=pb : BC=00
959     little_endian_store_16(acl_buffer, 0u, con_handle | (packet_boundary << 12u) | (0u << 14u));
960     // 2 - ACL length
961     little_endian_store_16(acl_buffer, 2u,  len + 4u);
962     // 4 - L2CAP packet length
963     little_endian_store_16(acl_buffer, 4u,  len + 0u);
964     // 6 - L2CAP channel DEST
965     little_endian_store_16(acl_buffer, 6,  remote_cid);
966 }
967 
968 // assumption - only on LE connections
969 int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
970 
971     if (!hci_is_packet_buffer_reserved()){
972         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
973         return BTSTACK_ACL_BUFFERS_FULL;
974     }
975 
976     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
977         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
978         return BTSTACK_ACL_BUFFERS_FULL;
979     }
980 
981     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
982 
983     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
984     l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
985     // send
986     return hci_send_acl_packet_buffer(len+8u);
987 }
988 
989 // assumption - only on LE connections
990 int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
991 
992     if (!hci_can_send_acl_packet_now(con_handle)){
993         log_info("l2cap_send cid 0x%02x, cannot send", cid);
994         return BTSTACK_ACL_BUFFERS_FULL;
995     }
996 
997     hci_reserve_packet_buffer();
998     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
999 
1000     (void)memcpy(&acl_buffer[8], data, len);
1001 
1002     return l2cap_send_prepared_connectionless(con_handle, cid, len);
1003 }
1004 
1005 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
1006     log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
1007     uint8_t event[4];
1008     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
1009     event[1] = sizeof(event) - 2u;
1010     little_endian_store_16(event, 2, channel);
1011     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1012     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
1013 }
1014 
1015 #ifdef L2CAP_USES_CHANNELS
1016 static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
1017     (* (channel->packet_handler))(type, channel->local_cid, data, size);
1018 }
1019 
1020 static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
1021     uint8_t event[4];
1022     event[0] = event_code;
1023     event[1] = sizeof(event) - 2u;
1024     little_endian_store_16(event, 2, channel->local_cid);
1025     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1026     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1027 }
1028 #endif
1029 
1030 #ifdef ENABLE_CLASSIC
1031 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
1032     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",
1033              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
1034              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
1035     uint8_t event[26];
1036     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
1037     event[1] = sizeof(event) - 2;
1038     event[2] = status;
1039     reverse_bd_addr(channel->address, &event[3]);
1040     little_endian_store_16(event,  9, channel->con_handle);
1041     little_endian_store_16(event, 11, channel->psm);
1042     little_endian_store_16(event, 13, channel->local_cid);
1043     little_endian_store_16(event, 15, channel->remote_cid);
1044     little_endian_store_16(event, 17, channel->local_mtu);
1045     little_endian_store_16(event, 19, channel->remote_mtu);
1046     little_endian_store_16(event, 21, channel->flush_timeout);
1047     event[23] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
1048 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1049     log_info("ERTM mode %u, fcs enabled %u", channel->mode, channel->fcs_option);
1050     event[24] = channel->mode;
1051     event[25] = channel->fcs_option;
1052 
1053 #else
1054     event[24] = L2CAP_CHANNEL_MODE_BASIC;
1055     event[25] = 0;
1056 #endif
1057     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1058     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1059 }
1060 
1061 static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
1062     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
1063     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
1064 }
1065 
1066 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
1067     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
1068              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
1069     uint8_t event[16];
1070     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
1071     event[1] = sizeof(event) - 2;
1072     reverse_bd_addr(channel->address, &event[2]);
1073     little_endian_store_16(event,  8, channel->con_handle);
1074     little_endian_store_16(event, 10, channel->psm);
1075     little_endian_store_16(event, 12, channel->local_cid);
1076     little_endian_store_16(event, 14, channel->remote_cid);
1077     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1078     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1079 }
1080 
1081 static void l2cap_handle_channel_open_failed(l2cap_channel_t * channel, uint8_t status){
1082 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1083     // emit ertm buffer released, as it's not needed. if in basic mode, it was either not allocated or already released
1084     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1085         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1086     }
1087 #endif
1088     l2cap_emit_channel_opened(channel, status);
1089 }
1090 
1091 static void l2cap_handle_channel_closed(l2cap_channel_t * channel){
1092 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1093     // emit ertm buffer released, as it's not needed anymore. if in basic mode, it was either not allocated or already released
1094     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1095         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1096     }
1097 #endif
1098     l2cap_emit_channel_closed(channel);
1099 }
1100 #endif
1101 
1102 static l2cap_fixed_channel_t * l2cap_channel_item_by_cid(uint16_t cid){
1103     btstack_linked_list_iterator_t it;
1104     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1105     while (btstack_linked_list_iterator_has_next(&it)){
1106         l2cap_fixed_channel_t * channel = (l2cap_fixed_channel_t*) btstack_linked_list_iterator_next(&it);
1107         if (channel->local_cid == cid) {
1108             return channel;
1109         }
1110     }
1111     return NULL;
1112 }
1113 
1114 // used for fixed channels in LE (ATT/SM) and Classic (Connectionless Channel). CID < 0x04
1115 static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid){
1116     if (local_cid >= 0x40u) return NULL;
1117     return (l2cap_fixed_channel_t*) l2cap_channel_item_by_cid(local_cid);
1118 }
1119 
1120 // used for Classic Channels + LE Data Channels. local_cid >= 0x40
1121 #ifdef L2CAP_USES_CHANNELS
1122 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
1123     if (local_cid < 0x40u) return NULL;
1124     return (l2cap_channel_t*) l2cap_channel_item_by_cid(local_cid);
1125 }
1126 
1127 void l2cap_request_can_send_now_event(uint16_t local_cid){
1128     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1129     if (!channel) return;
1130     channel->waiting_for_can_send_now = 1;
1131 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1132     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1133         l2cap_ertm_notify_channel_can_send(channel);
1134         return;
1135     }
1136 #endif
1137     l2cap_notify_channel_can_send();
1138 }
1139 
1140 int  l2cap_can_send_packet_now(uint16_t local_cid){
1141     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1142     if (!channel) return 0;
1143 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1144     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1145         return l2cap_ertm_can_store_packet_now(channel);
1146     }
1147 #endif
1148     return hci_can_send_acl_packet_now(channel->con_handle);
1149 }
1150 
1151 int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
1152     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1153     if (!channel) return 0;
1154 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1155     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1156         return 0;
1157     }
1158 #endif
1159     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
1160 }
1161 
1162 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
1163     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1164     if (channel) {
1165         return channel->remote_mtu;
1166     }
1167     return 0;
1168 }
1169 #endif
1170 
1171 #ifdef L2CAP_USES_CHANNELS
1172 static int l2cap_is_dynamic_channel_type(l2cap_channel_type_t channel_type){
1173     switch (channel_type){
1174         case L2CAP_CHANNEL_TYPE_CLASSIC:
1175         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
1176             return 1;
1177         default:
1178             return 0;
1179     }
1180 }
1181 #endif
1182 
1183 #ifdef ENABLE_CLASSIC
1184 // RTX Timer only exist for dynamic channels
1185 static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
1186     btstack_linked_list_iterator_t it;
1187     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1188     while (btstack_linked_list_iterator_has_next(&it)){
1189         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1190         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
1191         if (&channel->rtx == ts) {
1192             return channel;
1193         }
1194     }
1195     return NULL;
1196 }
1197 
1198 static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
1199     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
1200     if (!channel) return;
1201 
1202     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
1203 
1204     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
1205     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
1206     // notify client
1207     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
1208 
1209     // discard channel
1210     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1211     l2cap_free_channel_entry(channel);
1212 }
1213 
1214 #endif
1215 
1216 #ifdef L2CAP_USES_CHANNELS
1217 static void l2cap_stop_rtx(l2cap_channel_t * channel){
1218     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
1219     btstack_run_loop_remove_timer(&channel->rtx);
1220 }
1221 #endif
1222 
1223 #ifdef ENABLE_CLASSIC
1224 
1225 static void l2cap_start_rtx(l2cap_channel_t * channel){
1226     l2cap_stop_rtx(channel);
1227     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
1228     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1229     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
1230     btstack_run_loop_add_timer(&channel->rtx);
1231 }
1232 
1233 static void l2cap_start_ertx(l2cap_channel_t * channel){
1234     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
1235     l2cap_stop_rtx(channel);
1236     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1237     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
1238     btstack_run_loop_add_timer(&channel->rtx);
1239 }
1240 
1241 void l2cap_require_security_level_2_for_outgoing_sdp(void){
1242     require_security_level2_for_outgoing_sdp = 1;
1243 }
1244 
1245 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
1246     return (psm == BLUETOOTH_PSM_SDP) && (!require_security_level2_for_outgoing_sdp);
1247 }
1248 
1249 static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1250     if (!hci_can_send_acl_packet_now(handle)){
1251         log_info("l2cap_send_signaling_packet, cannot send");
1252         return BTSTACK_ACL_BUFFERS_FULL;
1253     }
1254 
1255     // log_info("l2cap_send_signaling_packet type %u", cmd);
1256     hci_reserve_packet_buffer();
1257     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1258     va_list argptr;
1259     va_start(argptr, identifier);
1260     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
1261     va_end(argptr);
1262     // log_info("l2cap_send_signaling_packet con %u!", handle);
1263     return hci_send_acl_packet_buffer(len);
1264 }
1265 
1266 // assumption - only on Classic connections
1267 // cannot be used for L2CAP ERTM
1268 int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
1269 
1270     if (!hci_is_packet_buffer_reserved()){
1271         log_error("l2cap_send_prepared called without reserving packet first");
1272         return BTSTACK_ACL_BUFFERS_FULL;
1273     }
1274 
1275     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1276     if (!channel) {
1277         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
1278         return -1;   // TODO: define error
1279     }
1280 
1281     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
1282         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
1283         return BTSTACK_ACL_BUFFERS_FULL;
1284     }
1285 
1286     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
1287 
1288     int fcs_size = 0;
1289 
1290 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1291     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->fcs_option){
1292         fcs_size = 2;
1293     }
1294 #endif
1295 
1296     // set non-flushable packet boundary flag if supported on Controller
1297     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1298     uint8_t packet_boundary_flag = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
1299     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
1300 
1301 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1302     if (fcs_size){
1303         // calculate FCS over l2cap data
1304         uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
1305         log_info("I-Frame: fcs 0x%04x", fcs);
1306         little_endian_store_16(acl_buffer, 8 + len, fcs);
1307     }
1308 #endif
1309 
1310     // send
1311     return hci_send_acl_packet_buffer(len+8+fcs_size);
1312 }
1313 
1314 // assumption - only on Classic connections
1315 int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
1316     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1317     if (!channel) {
1318         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
1319         return -1;   // TODO: define error
1320     }
1321 
1322 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1323     // send in ERTM
1324     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1325         return l2cap_ertm_send(channel, data, len);
1326     }
1327 #endif
1328 
1329     if (len > channel->remote_mtu){
1330         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
1331         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
1332     }
1333 
1334     if (!hci_can_send_acl_packet_now(channel->con_handle)){
1335         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
1336         return BTSTACK_ACL_BUFFERS_FULL;
1337     }
1338 
1339     hci_reserve_packet_buffer();
1340     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1341     (void)memcpy(&acl_buffer[8], data, len);
1342     return l2cap_send_prepared(local_cid, len);
1343 }
1344 
1345 int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
1346     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
1347 }
1348 
1349 static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
1350     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
1351 }
1352 
1353 static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
1354     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
1355 }
1356 #endif
1357 
1358 
1359 #ifdef ENABLE_BLE
1360 static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1361 
1362     if (!hci_can_send_acl_packet_now(handle)){
1363         log_info("l2cap_send_le_signaling_packet, cannot send");
1364         return BTSTACK_ACL_BUFFERS_FULL;
1365     }
1366 
1367     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
1368     hci_reserve_packet_buffer();
1369     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1370     va_list argptr;
1371     va_start(argptr, identifier);
1372     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
1373     va_end(argptr);
1374     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
1375     return hci_send_acl_packet_buffer(len);
1376 }
1377 #endif
1378 
1379 uint16_t l2cap_max_mtu(void){
1380     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
1381 }
1382 
1383 #ifdef ENABLE_BLE
1384 uint16_t l2cap_max_le_mtu(void){
1385     if (l2cap_le_custom_max_mtu != 0u) return l2cap_le_custom_max_mtu;
1386     return l2cap_max_mtu();
1387 }
1388 
1389 void l2cap_set_max_le_mtu(uint16_t max_mtu){
1390     if (max_mtu < l2cap_max_mtu()){
1391         l2cap_le_custom_max_mtu = max_mtu;
1392     }
1393 }
1394 #endif
1395 
1396 #ifdef ENABLE_CLASSIC
1397 
1398 static uint16_t l2cap_setup_options_mtu(uint8_t * config_options, uint16_t mtu){
1399     config_options[0] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
1400     config_options[1] = 2; // len param
1401     little_endian_store_16(config_options, 2, mtu);
1402     return 4;
1403 }
1404 
1405 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1406 static int l2cap_ertm_mode(l2cap_channel_t * channel){
1407     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
1408     return ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE)
1409         &&  (connection->l2cap_state.extended_feature_mask & 0x08));
1410 }
1411 #endif
1412 
1413 static uint16_t l2cap_setup_options_request(l2cap_channel_t * channel, uint8_t * config_options){
1414 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1415     // use ERTM options if supported by remote and channel ready to use it
1416     if (l2cap_ertm_mode(channel) && channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1417         return l2cap_setup_options_ertm_request(channel, config_options);
1418     }
1419 #endif
1420     uint16_t mtu = channel->local_mtu;
1421     return l2cap_setup_options_mtu(config_options, mtu);
1422 }
1423 
1424 static uint16_t l2cap_setup_options_mtu_response(l2cap_channel_t * channel, uint8_t * config_options){
1425     uint16_t mtu = btstack_min(channel->local_mtu, channel->remote_mtu);
1426     return l2cap_setup_options_mtu(config_options, mtu);
1427 }
1428 
1429 static uint32_t l2cap_extended_features_mask(void){
1430     // extended features request supported, features: fixed channels, unicast connectionless data reception
1431     uint32_t features = 0x280;
1432 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1433     features |= 0x0028;
1434 #endif
1435     return features;
1436 }
1437 #endif
1438 
1439 //
1440 #ifdef ENABLE_CLASSIC
1441 
1442 // returns true if channel was finalized
1443 static bool l2cap_run_for_classic_channel(l2cap_channel_t * channel){
1444 
1445 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1446     uint8_t  config_options[18];
1447 #else
1448     uint8_t  config_options[10];
1449 #endif
1450 
1451     switch (channel->state){
1452 
1453         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1454         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
1455             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1456             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
1457                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
1458                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
1459             }
1460             break;
1461 
1462         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1463             if (!hci_can_send_command_packet_now()) break;
1464             // send connection request - set state first
1465             channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
1466             // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
1467             (void)memcpy(l2cap_outgoing_classic_addr, channel->address, 6);
1468             hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_get_allow_role_switch());
1469             break;
1470 
1471         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
1472             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1473             channel->state = L2CAP_STATE_INVALID;
1474             l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
1475             // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1476             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1477             l2cap_free_channel_entry(channel);
1478             channel = NULL;
1479             break;
1480 
1481         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
1482             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1483             channel->state = L2CAP_STATE_CONFIG;
1484             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1485             l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
1486             break;
1487 
1488         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
1489             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1490             // success, start l2cap handshake
1491             channel->local_sig_id = l2cap_next_sig_id();
1492             channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
1493             l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
1494             l2cap_start_rtx(channel);
1495             break;
1496 
1497         case L2CAP_STATE_CONFIG:
1498             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1499 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1500             // fallback to basic mode if ERTM requested but not not supported by remote
1501             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1502                 if (!l2cap_ertm_mode(channel)){
1503                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1504                     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
1505                 }
1506             }
1507 #endif
1508             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
1509                 uint16_t flags = 0;
1510                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1511                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
1512                     flags = 1;
1513                 } else {
1514                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1515                 }
1516                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
1517                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1518                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS, 0, NULL);
1519 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1520                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
1521                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1522                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1523                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1524                     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);
1525                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM){
1526                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
1527                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1528                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1529                     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);
1530 #endif
1531                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
1532                     channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1533                     uint16_t options_size = l2cap_setup_options_mtu_response(channel, config_options);
1534                     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);
1535                 } else {
1536                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
1537                 }
1538                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1539             }
1540             else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
1541                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1542                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
1543                 channel->local_sig_id = l2cap_next_sig_id();
1544                 uint16_t options_size = l2cap_setup_options_request(channel, config_options);
1545                 l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options);
1546                 l2cap_start_rtx(channel);
1547             }
1548             if (l2cap_channel_ready_for_open(channel)){
1549                 channel->state = L2CAP_STATE_OPEN;
1550                 l2cap_emit_channel_opened(channel, 0);  // success
1551             }
1552             break;
1553 
1554         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1555             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1556             channel->state = L2CAP_STATE_INVALID;
1557             l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1558             // 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 :)
1559             l2cap_finialize_channel_close(channel);  // -- remove from list
1560             channel = NULL;
1561             break;
1562 
1563         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1564             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1565             channel->local_sig_id = l2cap_next_sig_id();
1566             channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1567             l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1568             break;
1569         default:
1570             break;
1571     }
1572 
1573     // handle channel finalize on L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE and L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE
1574     return channel == NULL;
1575 }
1576 
1577 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1578 static void l2cap_run_for_classic_channel_ertm(l2cap_channel_t * channel){
1579 
1580     // ERTM mode
1581     if (channel->mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) return;
1582 
1583     // check if we can still send
1584     if (channel->con_handle == HCI_CON_HANDLE_INVALID) return;
1585     if (!hci_can_send_acl_packet_now(channel->con_handle)) return;
1586 
1587     if (channel->send_supervisor_frame_receiver_ready){
1588         channel->send_supervisor_frame_receiver_ready = 0;
1589         log_info("Send S-Frame: RR %u, final %u", channel->req_seq, channel->set_final_bit_after_packet_with_poll_bit_set);
1590         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);
1591         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1592         l2cap_ertm_send_supervisor_frame(channel, control);
1593         return;
1594     }
1595     if (channel->send_supervisor_frame_receiver_ready_poll){
1596         channel->send_supervisor_frame_receiver_ready_poll = 0;
1597         log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
1598         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
1599         l2cap_ertm_send_supervisor_frame(channel, control);
1600         return;
1601     }
1602     if (channel->send_supervisor_frame_receiver_not_ready){
1603         channel->send_supervisor_frame_receiver_not_ready = 0;
1604         log_info("Send S-Frame: RNR %u", channel->req_seq);
1605         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
1606         l2cap_ertm_send_supervisor_frame(channel, control);
1607         return;
1608     }
1609     if (channel->send_supervisor_frame_reject){
1610         channel->send_supervisor_frame_reject = 0;
1611         log_info("Send S-Frame: REJ %u", channel->req_seq);
1612         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 0, 0, channel->req_seq);
1613         l2cap_ertm_send_supervisor_frame(channel, control);
1614         return;
1615     }
1616     if (channel->send_supervisor_frame_selective_reject){
1617         channel->send_supervisor_frame_selective_reject = 0;
1618         log_info("Send S-Frame: SREJ %u", channel->expected_tx_seq);
1619         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);
1620         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1621         l2cap_ertm_send_supervisor_frame(channel, control);
1622         return;
1623     }
1624 
1625     if (channel->srej_active){
1626         int i;
1627         for (i=0;i<channel->num_tx_buffers;i++){
1628             l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
1629             if (tx_state->retransmission_requested) {
1630                 tx_state->retransmission_requested = 0;
1631                 uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set;
1632                 channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1633                 l2cap_ertm_send_information_frame(channel, i, final);
1634                 break;
1635             }
1636         }
1637         if (i == channel->num_tx_buffers){
1638             // no retransmission request found
1639             channel->srej_active = 0;
1640         } else {
1641             // packet was sent
1642             return;
1643         }
1644     }
1645 }
1646 #endif /* ERTM */
1647 #endif /* Classic */
1648 
1649 static void l2cap_run_signaling_response(void) {
1650 
1651     // check pending signaling responses
1652     while (signaling_responses_pending){
1653 
1654         hci_con_handle_t handle = signaling_responses[0].handle;
1655 
1656         if (!hci_can_send_acl_packet_now(handle)) break;
1657 
1658         uint8_t  sig_id        = signaling_responses[0].sig_id;
1659         uint8_t  response_code = signaling_responses[0].code;
1660         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
1661 #ifdef ENABLE_CLASSIC
1662         uint16_t info_type     = signaling_responses[0].data;  // INFORMATION_REQUEST
1663         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
1664 #endif
1665 
1666         // remove first item before sending (to avoid sending response mutliple times)
1667         signaling_responses_pending--;
1668         int i;
1669         for (i=0; i < signaling_responses_pending; i++){
1670             (void)memcpy(&signaling_responses[i],
1671                          &signaling_responses[i + 1],
1672                          sizeof(l2cap_signaling_response_t));
1673         }
1674 
1675         switch (response_code){
1676 #ifdef ENABLE_CLASSIC
1677             case CONNECTION_REQUEST:
1678                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
1679                 // also disconnect if result is 0x0003 - security blocked
1680                 if (result == 0x0003){
1681                     hci_disconnect_security_block(handle);
1682                 }
1683                 break;
1684             case ECHO_REQUEST:
1685                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
1686                 break;
1687             case INFORMATION_REQUEST:
1688                 switch (info_type){
1689                     case L2CAP_INFO_TYPE_CONNECTIONLESS_MTU: {
1690                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
1691                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(connectionless_mtu), &connectionless_mtu);
1692                         }
1693                         break;
1694                     case L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED: {
1695                             uint32_t features = l2cap_extended_features_mask();
1696                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(features), &features);
1697                         }
1698                         break;
1699                     case L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED: {
1700                             uint8_t map[8];
1701                             memset(map, 0, 8);
1702                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
1703                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(map), &map);
1704                         }
1705                         break;
1706                     default:
1707                         // all other types are not supported
1708                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 1, 0, NULL);
1709                         break;
1710                 }
1711                 break;
1712             case COMMAND_REJECT:
1713                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
1714                 break;
1715 #endif
1716 #ifdef ENABLE_BLE
1717             case LE_CREDIT_BASED_CONNECTION_REQUEST:
1718                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
1719                 break;
1720             case COMMAND_REJECT_LE:
1721                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
1722                 break;
1723 #endif
1724             default:
1725                 // should not happen
1726                 break;
1727         }
1728     }
1729 }
1730 
1731 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1732 static bool l2ap_run_ertm(void){
1733     // send l2cap information request if neccessary
1734     btstack_linked_list_iterator_t it;
1735     hci_connections_get_iterator(&it);
1736     while(btstack_linked_list_iterator_has_next(&it)){
1737         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1738         if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST){
1739             if (!hci_can_send_acl_packet_now(connection->con_handle)) break;
1740             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
1741             uint8_t sig_id = l2cap_next_sig_id();
1742             uint8_t info_type = L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED;
1743             l2cap_send_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
1744             return true;
1745         }
1746     }
1747     return false;
1748 }
1749 #endif
1750 
1751 #ifdef ENABLE_LE_DATA_CHANNELS
1752 static void l2cap_run_le_data_channels(void){
1753     btstack_linked_list_iterator_t it;
1754     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1755     while (btstack_linked_list_iterator_has_next(&it)){
1756         uint16_t mps;
1757         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1758 
1759         if (channel->channel_type != L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL) continue;
1760 
1761         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1762         switch (channel->state){
1763             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
1764                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1765                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
1766                 // le psm, source cid, mtu, mps, initial credits
1767                 channel->local_sig_id = l2cap_next_sig_id();
1768                 channel->credits_incoming =  channel->new_credits_incoming;
1769                 channel->new_credits_incoming = 0;
1770                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
1771                 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);
1772                 break;
1773             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
1774                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1775                 // TODO: support larger MPS
1776                 channel->state = L2CAP_STATE_OPEN;
1777                 channel->credits_incoming =  channel->new_credits_incoming;
1778                 channel->new_credits_incoming = 0;
1779                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
1780                 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);
1781                 // notify client
1782                 l2cap_emit_le_channel_opened(channel, 0);
1783                 break;
1784             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
1785                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1786                 channel->state = L2CAP_STATE_INVALID;
1787                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
1788                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1789                 btstack_linked_list_iterator_remove(&it);
1790                 l2cap_free_channel_entry(channel);
1791                 break;
1792             case L2CAP_STATE_OPEN:
1793                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1794 
1795                 // send credits
1796                 if (channel->new_credits_incoming){
1797                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
1798                     channel->local_sig_id = l2cap_next_sig_id();
1799                     uint16_t new_credits = channel->new_credits_incoming;
1800                     channel->new_credits_incoming = 0;
1801                     channel->credits_incoming += new_credits;
1802                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
1803                 }
1804                 break;
1805 
1806             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1807                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1808                 channel->local_sig_id = l2cap_next_sig_id();
1809                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1810                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1811                 break;
1812             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1813                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1814                 channel->state = L2CAP_STATE_INVALID;
1815                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1816                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
1817                 break;
1818             default:
1819                 break;
1820         }
1821     }
1822 }
1823 #endif
1824 
1825 // MARK: L2CAP_RUN
1826 // process outstanding signaling tasks
1827 static void l2cap_run(void){
1828 
1829     // log_info("l2cap_run: entered");
1830     l2cap_run_signaling_response();
1831 
1832 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1833     bool done = l2ap_run_ertm();
1834     if (done) return;
1835 #endif
1836 
1837 #if defined(ENABLE_CLASSIC) || defined(ENABLE_BLE)
1838     btstack_linked_list_iterator_t it;
1839 #endif
1840 
1841 #ifdef ENABLE_CLASSIC
1842     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1843     while (btstack_linked_list_iterator_has_next(&it)){
1844 
1845         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1846 
1847         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CLASSIC) continue;
1848 
1849         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1850         bool finalized = l2cap_run_for_classic_channel(channel);
1851 
1852         if (!finalized) {
1853 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1854             l2cap_run_for_classic_channel_ertm(channel);
1855 #endif
1856         }
1857     }
1858 #endif
1859 
1860 #ifdef ENABLE_LE_DATA_CHANNELS
1861     l2cap_run_le_data_channels();
1862 #endif
1863 
1864 #ifdef ENABLE_BLE
1865     // send l2cap con paramter update if necessary
1866     hci_connections_get_iterator(&it);
1867     while(btstack_linked_list_iterator_has_next(&it)){
1868         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1869         if ((connection->address_type != BD_ADDR_TYPE_LE_PUBLIC) && (connection->address_type != BD_ADDR_TYPE_LE_RANDOM)) continue;
1870         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
1871         switch (connection->le_con_parameter_update_state){
1872             case CON_PARAMETER_UPDATE_SEND_REQUEST:
1873                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1874                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, l2cap_next_sig_id(),
1875                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
1876                 break;
1877             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
1878                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
1879                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
1880                 break;
1881             case CON_PARAMETER_UPDATE_DENY:
1882                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1883                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
1884                 break;
1885             default:
1886                 break;
1887         }
1888     }
1889 #endif
1890 
1891     // log_info("l2cap_run: exit");
1892 }
1893 
1894 #ifdef ENABLE_CLASSIC
1895 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
1896     if ((channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE) || (channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION)) {
1897         log_info("connection complete con_handle %04x - for channel %p cid 0x%04x", (int) con_handle, channel, channel->local_cid);
1898         // success, start l2cap handshake
1899         channel->con_handle = con_handle;
1900         // check remote SSP feature first
1901         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
1902     }
1903 }
1904 
1905 static void l2cap_ready_to_connect(l2cap_channel_t * channel){
1906 
1907 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1908     // assumption: outgoing connection
1909     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
1910     if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
1911         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
1912         channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
1913         return;
1914     }
1915 #endif
1916 
1917     // fine, go ahead
1918     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
1919 }
1920 
1921 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
1922     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
1923 
1924     // we have been waiting for remote supported features
1925     if (channel->required_security_level > LEVEL_0){
1926         // request security level
1927         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
1928         gap_request_security_level(channel->con_handle, channel->required_security_level);
1929         return;
1930     }
1931 
1932     l2cap_ready_to_connect(channel);
1933 }
1934 #endif
1935 
1936 #ifdef L2CAP_USES_CHANNELS
1937 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,
1938     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
1939 
1940     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1941     if (!channel) {
1942         return NULL;
1943     }
1944 
1945     // fill in
1946     channel->packet_handler = packet_handler;
1947     channel->channel_type   = channel_type;
1948     bd_addr_copy(channel->address, address);
1949     channel->address_type = address_type;
1950     channel->psm = psm;
1951     channel->local_mtu  = local_mtu;
1952     channel->remote_mtu = L2CAP_DEFAULT_MTU;
1953     channel->required_security_level = security_level;
1954 
1955     //
1956     channel->local_cid = l2cap_next_local_cid();
1957     channel->con_handle = HCI_CON_HANDLE_INVALID;
1958 
1959     // set initial state
1960     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
1961     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
1962     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
1963     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
1964 
1965     log_info("create channel %p, local_cid 0x%04x", channel, channel->local_cid);
1966 
1967     return channel;
1968 }
1969 
1970 static void l2cap_free_channel_entry(l2cap_channel_t * channel){
1971     log_info("free channel %p, local_cid 0x%04x", channel, channel->local_cid);
1972     // assert all timers are stopped
1973     l2cap_stop_rtx(channel);
1974 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1975     l2cap_ertm_stop_retransmission_timer(channel);
1976     l2cap_ertm_stop_monitor_timer(channel);
1977 #endif
1978     // free  memory
1979     btstack_memory_l2cap_channel_free(channel);
1980 }
1981 #endif
1982 
1983 #ifdef ENABLE_CLASSIC
1984 
1985 /**
1986  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
1987  * @param packet_handler
1988  * @param address
1989  * @param psm
1990  * @param mtu
1991  * @param local_cid
1992  */
1993 
1994 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){
1995     // limit MTU to the size of our outgoing HCI buffer
1996     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1997 
1998 	// determine security level based on psm
1999 	const gap_security_level_t security_level = l2cap_security_level_0_allowed_for_PSM(psm) ? LEVEL_0 : gap_get_security_level();
2000 	log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x mtu %u -> local mtu %u, sec level %u", bd_addr_to_str(address), psm, mtu, local_mtu, (int) security_level);
2001 
2002     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, address, BD_ADDR_TYPE_ACL, psm, local_mtu, security_level);
2003     if (!channel) {
2004         return BTSTACK_MEMORY_ALLOC_FAILED;
2005     }
2006 
2007 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2008     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2009 #endif
2010 
2011     // add to connections list
2012     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2013 
2014     // store local_cid
2015     if (out_local_cid){
2016        *out_local_cid = channel->local_cid;
2017     }
2018 
2019 	// state: L2CAP_STATE_WILL_SEND_CREATE_CONNECTION
2020 
2021     // check if hci connection is already usable,
2022     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
2023     if (conn && conn->con_handle != HCI_CON_HANDLE_INVALID){
2024     	// simulate connection complete
2025 	    l2cap_handle_connection_complete(conn->con_handle, channel);
2026 
2027 		// state: L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES
2028 
2029         // check if remote supported features are already received
2030         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
2031         	// simulate remote features received
2032             l2cap_handle_remote_supported_features_received(channel);
2033         }
2034     }
2035 
2036     l2cap_run();
2037 
2038     return ERROR_CODE_SUCCESS;
2039 }
2040 
2041 void l2cap_disconnect(uint16_t local_cid, uint8_t reason){
2042     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
2043     // find channel for local_cid
2044     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2045     if (channel) {
2046         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2047     }
2048     // process
2049     l2cap_run();
2050 }
2051 
2052 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
2053     // mark all channels before emitting open events as these could trigger new connetion requests to the same device
2054     btstack_linked_list_iterator_t it;
2055     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2056     while (btstack_linked_list_iterator_has_next(&it)){
2057         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2058         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2059         if (bd_addr_cmp( channel->address, address) != 0) continue;
2060         // channel for this address found
2061         switch (channel->state){
2062             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2063             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2064                 channel->state = L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD;
2065                 break;
2066             default:
2067                 break;
2068         }
2069     }
2070     // emit and free marked entries. restart loop to deal with list changes
2071     int done = 0;
2072     while (!done) {
2073         done = 1;
2074         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2075         while (btstack_linked_list_iterator_has_next(&it)){
2076             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2077             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2078             if (channel->state == L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD){
2079                 done = 0;
2080                 // failure, forward error code
2081                 l2cap_handle_channel_open_failed(channel, status);
2082                 // discard channel
2083                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2084                 l2cap_free_channel_entry(channel);
2085                 break;
2086             }
2087         }
2088     }
2089 
2090 }
2091 
2092 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
2093     btstack_linked_list_iterator_t it;
2094     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2095     while (btstack_linked_list_iterator_has_next(&it)){
2096         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2097         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2098         if ( ! bd_addr_cmp( channel->address, address) ){
2099             l2cap_handle_connection_complete(handle, channel);
2100         }
2101     }
2102     // process
2103     l2cap_run();
2104 }
2105 #endif
2106 
2107 static bool l2cap_channel_ready_to_send(l2cap_channel_t * channel){
2108     switch (channel->channel_type){
2109 #ifdef ENABLE_CLASSIC
2110         case L2CAP_CHANNEL_TYPE_CLASSIC:
2111 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2112             // send if we have more data and remote windows isn't full yet
2113             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2114                 if (channel->unacked_frames >= btstack_min(channel->num_stored_tx_frames, channel->remote_tx_window_size)) return false;
2115                 return hci_can_send_acl_classic_packet_now() != 0;
2116             }
2117 #endif
2118             if (!channel->waiting_for_can_send_now) return false;
2119             return (hci_can_send_acl_classic_packet_now() != 0);
2120         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2121             if (!channel->waiting_for_can_send_now) return false;
2122             return hci_can_send_acl_classic_packet_now() != 0;
2123 #endif
2124 #ifdef ENABLE_BLE
2125         case L2CAP_CHANNEL_TYPE_LE_FIXED:
2126             if (!channel->waiting_for_can_send_now) return false;
2127             return hci_can_send_acl_le_packet_now() != 0;
2128 #ifdef ENABLE_LE_DATA_CHANNELS
2129         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
2130             if (channel->send_sdu_buffer == NULL) return false;
2131             if (channel->credits_outgoing == 0u) return false;
2132             return hci_can_send_acl_le_packet_now() != 0;
2133 #endif
2134 #endif
2135         default:
2136             return false;
2137     }
2138 }
2139 
2140 static void l2cap_channel_trigger_send(l2cap_channel_t * channel){
2141     switch (channel->channel_type){
2142 #ifdef ENABLE_CLASSIC
2143         case L2CAP_CHANNEL_TYPE_CLASSIC:
2144 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2145             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2146                 l2cap_ertm_channel_send_information_frame(channel);
2147                 return;
2148             }
2149 #endif
2150             channel->waiting_for_can_send_now = 0;
2151             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2152             break;
2153         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2154             channel->waiting_for_can_send_now = 0;
2155             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2156             break;
2157 #endif
2158 #ifdef ENABLE_BLE
2159         case L2CAP_CHANNEL_TYPE_LE_FIXED:
2160             channel->waiting_for_can_send_now = 0;
2161             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2162             break;
2163 #ifdef ENABLE_LE_DATA_CHANNELS
2164         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
2165             l2cap_le_send_pdu(channel);
2166             break;
2167 #endif
2168 #endif
2169         default:
2170             break;
2171     }
2172 }
2173 
2174 static void l2cap_notify_channel_can_send(void){
2175     bool done = false;
2176     while (!done){
2177         done = true;
2178         btstack_linked_list_iterator_t it;
2179         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2180         while (btstack_linked_list_iterator_has_next(&it)){
2181             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2182             bool ready = l2cap_channel_ready_to_send(channel);
2183             if (!ready) continue;
2184 
2185             // requeue channel for fairness
2186             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2187             btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2188 
2189             // trigger sending
2190             l2cap_channel_trigger_send(channel);
2191 
2192             // exit inner loop as we just broke the iterator, but try again
2193             done = false;
2194             break;
2195         }
2196     }
2197 }
2198 
2199 #ifdef L2CAP_USES_CHANNELS
2200 
2201 static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){
2202     // open cannot fail for for incoming connections
2203     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0;
2204 
2205     // check state
2206     switch (channel->state){
2207         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2208         case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2209         case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES:
2210         case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2211         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
2212         case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES:
2213         case L2CAP_STATE_WAIT_CONNECT_RSP:
2214         case L2CAP_STATE_CONFIG:
2215         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
2216         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
2217         case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE:
2218         case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD:
2219             return 1;
2220 
2221         case L2CAP_STATE_OPEN:
2222         case L2CAP_STATE_CLOSED:
2223         case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES:
2224         case L2CAP_STATE_WAIT_DISCONNECT:
2225         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY:
2226         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
2227         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
2228         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2229         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
2230         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
2231         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
2232         case L2CAP_STATE_INVALID:
2233         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2234             return 0;
2235 
2236         default:
2237             // get a "warning" about new states
2238             btstack_assert(false);
2239             return 0;
2240     }
2241 }
2242 #endif
2243 
2244 #ifdef ENABLE_CLASSIC
2245 static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){
2246     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2247         l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2248     } else {
2249         l2cap_handle_channel_closed(channel);
2250     }
2251     l2cap_free_channel_entry(channel);
2252 }
2253 #endif
2254 
2255 #ifdef ENABLE_LE_DATA_CHANNELS
2256 static void l2cap_handle_hci_le_disconnect_event(l2cap_channel_t * channel){
2257     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2258         l2cap_emit_le_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2259     } else {
2260         l2cap_emit_le_channel_closed(channel);
2261     }
2262     l2cap_free_channel_entry(channel);
2263 }
2264 #endif
2265 
2266 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
2267 
2268     UNUSED(packet_type); // ok: registered with hci_event_callback_registration
2269     UNUSED(cid);         // ok: there is no channel
2270     UNUSED(size);        // ok: fixed format events read from HCI buffer
2271 
2272 #ifdef ENABLE_CLASSIC
2273     bd_addr_t address;
2274     hci_connection_t * hci_connection;
2275     int hci_con_used;
2276 #endif
2277 #ifdef L2CAP_USES_CHANNELS
2278     hci_con_handle_t handle;
2279     btstack_linked_list_iterator_t it;
2280 #endif
2281 
2282     switch(hci_event_packet_get_type(packet)){
2283 
2284         // Notify channel packet handler if they can send now
2285         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2286         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
2287         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
2288             l2cap_run();    // try sending signaling packets first
2289             l2cap_notify_channel_can_send();
2290             break;
2291 
2292         case HCI_EVENT_COMMAND_STATUS:
2293 #ifdef ENABLE_CLASSIC
2294             // check command status for create connection for errors
2295             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
2296                 // cache outgoing address and reset
2297                 (void)memcpy(address, l2cap_outgoing_classic_addr, 6);
2298                 memset(l2cap_outgoing_classic_addr, 0, 6);
2299                 // error => outgoing connection failed
2300                 uint8_t status = hci_event_command_status_get_status(packet);
2301                 if (status){
2302                     l2cap_handle_connection_failed_for_addr(address, status);
2303                 }
2304             }
2305 #endif
2306             l2cap_run();    // try sending signaling packets first
2307             break;
2308 
2309 #ifdef ENABLE_CLASSIC
2310         // handle connection complete events
2311         case HCI_EVENT_CONNECTION_COMPLETE:
2312             reverse_bd_addr(&packet[5], address);
2313             if (packet[2] == 0){
2314                 handle = little_endian_read_16(packet, 3);
2315                 l2cap_handle_connection_success_for_addr(address, handle);
2316             } else {
2317                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
2318             }
2319             break;
2320 
2321         // handle successful create connection cancel command
2322         case HCI_EVENT_COMMAND_COMPLETE:
2323             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
2324                 if (packet[5] == 0){
2325                     reverse_bd_addr(&packet[6], address);
2326                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
2327                     l2cap_handle_connection_failed_for_addr(address, 0x16);
2328                 }
2329             }
2330             l2cap_run();    // try sending signaling packets first
2331             break;
2332 #endif
2333 
2334 #ifdef L2CAP_USES_CHANNELS
2335         // handle disconnection complete events
2336         case HCI_EVENT_DISCONNECTION_COMPLETE:
2337             handle = little_endian_read_16(packet, 3);
2338             // send l2cap open failed or closed events for all channels on this handle and free them
2339             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2340             while (btstack_linked_list_iterator_has_next(&it)){
2341                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2342                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2343                 if (channel->con_handle != handle) continue;
2344                 btstack_linked_list_iterator_remove(&it);
2345                 switch(channel->channel_type){
2346 #ifdef ENABLE_CLASSIC
2347                     case L2CAP_CHANNEL_TYPE_CLASSIC:
2348                         l2cap_handle_hci_disconnect_event(channel);
2349                         break;
2350 #endif
2351 #ifdef ENABLE_LE_DATA_CHANNELS
2352                     case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
2353                         l2cap_handle_hci_le_disconnect_event(channel);
2354                         break;
2355 #endif
2356                     default:
2357                         break;
2358                 }
2359             }
2360             break;
2361 #endif
2362 
2363 
2364         // HCI Connection Timeouts
2365 #ifdef ENABLE_CLASSIC
2366         case L2CAP_EVENT_TIMEOUT_CHECK:
2367             handle = little_endian_read_16(packet, 2);
2368             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
2369             if (hci_authentication_active_for_handle(handle)) break;
2370             hci_con_used = 0;
2371             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2372             while (btstack_linked_list_iterator_has_next(&it)){
2373                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2374                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2375                 if (channel->con_handle != handle) continue;
2376                 hci_con_used = 1;
2377                 break;
2378             }
2379             if (hci_con_used) break;
2380             if (!hci_can_send_command_packet_now()) break;
2381             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
2382             break;
2383 
2384         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2385         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
2386             handle = little_endian_read_16(packet, 3);
2387             hci_connection = hci_connection_for_handle(handle);
2388             if (hci_connection == NULL) break;
2389             if ((hci_connection->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) == 0) break;
2390             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2391             while (btstack_linked_list_iterator_has_next(&it)){
2392                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2393                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2394                 if (channel->con_handle != handle) continue;
2395                 log_info("remote supported features, channel %p, cid %04x - state %u", channel, channel->local_cid, channel->state);
2396                 l2cap_handle_remote_supported_features_received(channel);
2397             }
2398             break;
2399 
2400         case GAP_EVENT_SECURITY_LEVEL:
2401             handle = little_endian_read_16(packet, 2);
2402             log_info("l2cap - security level update for handle 0x%04x", handle);
2403             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2404             while (btstack_linked_list_iterator_has_next(&it)){
2405                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2406                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2407                 if (channel->con_handle != handle) continue;
2408 
2409                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
2410                 gap_security_level_t required_level = channel->required_security_level;
2411 
2412                 log_info("channel %p, cid %04x - state %u: actual %u >= required %u?", channel, channel->local_cid, channel->state, actual_level, required_level);
2413 
2414                 switch (channel->state){
2415                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2416                         if (actual_level >= required_level){
2417 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2418                             // we need to know if ERTM is supported before sending a config response
2419                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
2420                             if (connection->l2cap_state.information_state != L2CAP_INFORMATION_STATE_DONE){
2421                                 connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2422                                 channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
2423                                 break;
2424                             }
2425 #endif
2426                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2427                             l2cap_emit_incoming_connection(channel);
2428                         } else {
2429                             channel->reason = 0x0003; // security block
2430                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2431                         }
2432                         break;
2433 
2434                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2435                         if (actual_level >= required_level){
2436                             l2cap_ready_to_connect(channel);
2437                         } else {
2438                             // disconnnect, authentication not good enough
2439                             hci_disconnect_security_block(handle);
2440                         }
2441                         break;
2442 
2443                     default:
2444                         break;
2445                 }
2446             }
2447             break;
2448 #endif
2449 
2450         default:
2451             break;
2452     }
2453 
2454     l2cap_run();
2455 }
2456 
2457 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t cid, uint16_t data){
2458     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused."
2459     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
2460         signaling_responses[signaling_responses_pending].handle = handle;
2461         signaling_responses[signaling_responses_pending].code = code;
2462         signaling_responses[signaling_responses_pending].sig_id = sig_id;
2463         signaling_responses[signaling_responses_pending].cid = cid;
2464         signaling_responses[signaling_responses_pending].data = data;
2465         signaling_responses_pending++;
2466         l2cap_run();
2467     }
2468 }
2469 
2470 #ifdef ENABLE_CLASSIC
2471 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
2472     channel->remote_sig_id = identifier;
2473     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
2474     l2cap_run();
2475 }
2476 
2477 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
2478 
2479     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
2480     l2cap_service_t *service = l2cap_get_service(psm);
2481     if (!service) {
2482         // 0x0002 PSM not supported
2483         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2484         return;
2485     }
2486 
2487     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
2488     if (!hci_connection) {
2489         //
2490         log_error("no hci_connection for handle %u", handle);
2491         return;
2492     }
2493 
2494     // alloc structure
2495     // log_info("l2cap_handle_connection_request register channel");
2496     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, hci_connection->address, BD_ADDR_TYPE_ACL,
2497     psm, service->mtu, service->required_security_level);
2498     if (!channel){
2499         // 0x0004 No resources available
2500         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2501         return;
2502     }
2503 
2504     channel->con_handle = handle;
2505     channel->remote_cid = source_cid;
2506     channel->remote_sig_id = sig_id;
2507 
2508     // limit local mtu to max acl packet length - l2cap header
2509     if (channel->local_mtu > l2cap_max_mtu()) {
2510         channel->local_mtu = l2cap_max_mtu();
2511     }
2512 
2513     // set initial state
2514     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
2515     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
2516 
2517     // add to connections list
2518     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2519 
2520     // assert security requirements
2521     gap_request_security_level(handle, channel->required_security_level);
2522 }
2523 
2524 void l2cap_accept_connection(uint16_t local_cid){
2525     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
2526     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2527     if (!channel) {
2528         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
2529         return;
2530     }
2531 
2532 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2533     // configure L2CAP Basic mode
2534     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
2535 #endif
2536 
2537     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
2538 
2539     // process
2540     l2cap_run();
2541 }
2542 
2543 void l2cap_decline_connection(uint16_t local_cid){
2544     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
2545     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
2546     if (!channel) {
2547         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
2548         return;
2549     }
2550     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2551     channel->reason = 0x04; // no resources available
2552     l2cap_run();
2553 }
2554 
2555 // @pre command len is valid, see check in l2cap_signaling_handler_channel
2556 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
2557 
2558 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2559     uint8_t use_fcs = 1;
2560 #endif
2561 
2562     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2563 
2564     uint16_t flags = little_endian_read_16(command, 6);
2565     if (flags & 1) {
2566         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
2567     }
2568 
2569     // accept the other's configuration options
2570     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2571     uint16_t pos     = 8;
2572     while (pos < end_pos){
2573         uint8_t option_hint = command[pos] >> 7;
2574         uint8_t option_type = command[pos] & 0x7f;
2575         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
2576         pos++;
2577         uint8_t length = command[pos++];
2578         // MTU { type(8): 1, len(8):2, MTU(16) }
2579         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) && (length == 2)){
2580             channel->remote_mtu = little_endian_read_16(command, pos);
2581             log_info("Remote MTU %u", channel->remote_mtu);
2582             if (channel->remote_mtu > l2cap_max_mtu()){
2583                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
2584                 channel->remote_mtu = l2cap_max_mtu();
2585             }
2586             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
2587         }
2588         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
2589         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT) && (length == 2)){
2590             channel->flush_timeout = little_endian_read_16(command, pos);
2591             log_info("Flush timeout: %u ms", channel->flush_timeout);
2592         }
2593 
2594 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2595         // Retransmission and Flow Control Option
2596         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2597             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
2598             switch(channel->mode){
2599                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2600                     // Store remote config
2601                     channel->remote_tx_window_size = command[pos+1];
2602                     channel->remote_max_transmit   = command[pos+2];
2603                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
2604                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
2605                     channel->remote_mps = little_endian_read_16(command, pos + 7);
2606                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
2607                         channel->remote_tx_window_size,
2608                         channel->remote_max_transmit,
2609                         channel->remote_retransmission_timeout_ms,
2610                         channel->remote_monitor_timeout_ms,
2611                         channel->remote_mps);
2612                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
2613                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
2614                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2615                     } else {
2616                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2617                     }
2618                     break;
2619                 case L2CAP_CHANNEL_MODE_BASIC:
2620                     switch (mode){
2621                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2622                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
2623                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
2624                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2625                             }
2626                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
2627                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
2628                             break;
2629                         default: // case L2CAP_CHANNEL_MODE_BASIC:
2630                             // TODO store and evaluate configuration
2631                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2632                             break;
2633                     }
2634                     break;
2635                 default:
2636                     break;
2637             }
2638         }
2639         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
2640             use_fcs = command[pos];
2641         }
2642 #endif
2643         // check for unknown options
2644         if ((option_hint == 0) && ((option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) || (option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE))){
2645             log_info("l2cap cid %u, unknown options", channel->local_cid);
2646             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
2647         }
2648         pos += length;
2649     }
2650 
2651 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2652         // "FCS" has precedence over "No FCS"
2653         uint8_t update = channel->fcs_option || use_fcs;
2654         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
2655         channel->fcs_option = update;
2656         // If ERTM mandatory, but remote didn't send Retransmission and Flowcontrol options -> disconnect
2657         if (((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM) == 0) & (channel->ertm_mandatory)){
2658             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2659         }
2660 #endif
2661 }
2662 
2663 // @pre command len is valid, see check in l2cap_signaling_handler_channel
2664 static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
2665     log_info("l2cap_signaling_handle_configure_response");
2666 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2667     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2668     uint16_t pos     = 10;
2669     while (pos < end_pos){
2670         uint8_t option_hint = command[pos] >> 7;
2671         uint8_t option_type = command[pos] & 0x7f;
2672         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
2673         pos++;
2674         uint8_t length = command[pos++];
2675 
2676         // Retransmission and Flow Control Option
2677         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2678             switch (channel->mode){
2679                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2680                     if (channel->ertm_mandatory){
2681                         // ??
2682                     } else {
2683                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
2684                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2685                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
2686                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2687                         }
2688                     }
2689                     break;
2690                 case L2CAP_CHANNEL_MODE_BASIC:
2691                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2692                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
2693                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2694                     }
2695                     break;
2696                 default:
2697                     break;
2698             }
2699         }
2700 
2701         // check for unknown options
2702         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
2703             log_info("l2cap cid %u, unknown options", channel->local_cid);
2704             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
2705         }
2706 
2707         pos += length;
2708     }
2709 #else
2710     UNUSED(channel);  // ok: no code
2711     UNUSED(result);   // ok: no code
2712     UNUSED(command);  // ok: no code
2713 #endif
2714 }
2715 
2716 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
2717     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
2718     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
2719     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
2720     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
2721     if (channel->state == L2CAP_STATE_OPEN) return 0;
2722     return 1;
2723 }
2724 
2725 
2726 // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
2727 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
2728 
2729     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2730     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2731     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2732     uint16_t result = 0;
2733 
2734     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
2735 
2736     // handle DISCONNECT REQUESTS seperately
2737     if (code == DISCONNECTION_REQUEST){
2738         switch (channel->state){
2739             case L2CAP_STATE_CONFIG:
2740             case L2CAP_STATE_OPEN:
2741             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2742             case L2CAP_STATE_WAIT_DISCONNECT:
2743                 l2cap_handle_disconnect_request(channel, identifier);
2744                 break;
2745 
2746             default:
2747                 // ignore in other states
2748                 break;
2749         }
2750         return;
2751     }
2752 
2753     // @STATEMACHINE(l2cap)
2754     switch (channel->state) {
2755 
2756         case L2CAP_STATE_WAIT_CONNECT_RSP:
2757             switch (code){
2758                 case CONNECTION_RESPONSE:
2759                     if (cmd_len < 8){
2760                         // command imcomplete
2761                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2762                         break;
2763                     }
2764                     l2cap_stop_rtx(channel);
2765                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2766                     switch (result) {
2767                         case 0:
2768                             // successful connection
2769                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2770                             channel->state = L2CAP_STATE_CONFIG;
2771                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2772                             break;
2773                         case 1:
2774                             // connection pending. get some coffee, but start the ERTX
2775                             l2cap_start_ertx(channel);
2776                             break;
2777                         default:
2778                             // channel closed
2779                             channel->state = L2CAP_STATE_CLOSED;
2780                             // map l2cap connection response result to BTstack status enumeration
2781                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
2782 
2783                             // drop link key if security block
2784                             if ((L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result) == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
2785                                 gap_drop_link_key_for_bd_addr(channel->address);
2786                             }
2787 
2788                             // discard channel
2789                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2790                             l2cap_free_channel_entry(channel);
2791                             break;
2792                     }
2793                     break;
2794 
2795                 default:
2796                     //@TODO: implement other signaling packets
2797                     break;
2798             }
2799             break;
2800 
2801         case L2CAP_STATE_CONFIG:
2802             switch (code) {
2803                 case CONFIGURE_REQUEST:
2804                     if (cmd_len < 4){
2805                         // command incomplete
2806                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2807                         break;
2808                     }
2809                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
2810                     l2cap_signaling_handle_configure_request(channel, command);
2811                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
2812                         // only done if continuation not set
2813                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
2814                     }
2815                     break;
2816                 case CONFIGURE_RESPONSE:
2817                     if (cmd_len < 6){
2818                         // command incomplete
2819                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2820                         break;
2821                     }
2822                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2823                     l2cap_stop_rtx(channel);
2824                     l2cap_signaling_handle_configure_response(channel, result, command);
2825                     switch (result){
2826                         case 0: // success
2827                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
2828                             break;
2829                         case 4: // pending
2830                             l2cap_start_ertx(channel);
2831                             break;
2832                         default:
2833 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2834                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
2835                                 // remote does not offer ertm but it's required
2836                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2837                                 break;
2838                             }
2839 #endif
2840                             // retry on negative result
2841                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2842                             break;
2843                     }
2844                     break;
2845                 default:
2846                     break;
2847             }
2848             if (l2cap_channel_ready_for_open(channel)){
2849 
2850 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2851                 // assert that packet can be stored in fragment buffers in ertm
2852                 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
2853                     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
2854                     uint16_t usable_mtu = channel->num_tx_buffers == 1 ? effective_mps : channel->num_tx_buffers * effective_mps - 2;
2855                     if (usable_mtu < channel->remote_mtu){
2856                         log_info("Remote MTU %u > max storable ERTM packet, only using MTU = %u", channel->remote_mtu, usable_mtu);
2857                         channel->remote_mtu = usable_mtu;
2858                     }
2859                 }
2860 #endif
2861                 // for open:
2862                 channel->state = L2CAP_STATE_OPEN;
2863                 l2cap_emit_channel_opened(channel, 0);
2864             }
2865             break;
2866 
2867         case L2CAP_STATE_WAIT_DISCONNECT:
2868             switch (code) {
2869                 case DISCONNECTION_RESPONSE:
2870                     l2cap_finialize_channel_close(channel);
2871                     break;
2872                 default:
2873                     //@TODO: implement other signaling packets
2874                     break;
2875             }
2876             break;
2877 
2878         case L2CAP_STATE_CLOSED:
2879             // @TODO handle incoming requests
2880             break;
2881 
2882         case L2CAP_STATE_OPEN:
2883             //@TODO: implement other signaling packets, e.g. re-configure
2884             break;
2885         default:
2886             break;
2887     }
2888     // log_info("new state %u", channel->state);
2889 }
2890 
2891 
2892 // @pre command len is valid, see check in l2cap_acl_classic_handler
2893 static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
2894 
2895     btstack_linked_list_iterator_t it;
2896 
2897     // get code, signalind identifier and command len
2898     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2899     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2900     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2901 
2902     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
2903     if ((code < 1) || (code == ECHO_RESPONSE) || (code > INFORMATION_RESPONSE)){
2904         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2905         return;
2906     }
2907 
2908     // general commands without an assigned channel
2909     switch(code) {
2910 
2911         case CONNECTION_REQUEST:
2912             if (cmd_len == 4){
2913                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2914                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
2915                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
2916             } else {
2917                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2918             }
2919             return;
2920 
2921         case ECHO_REQUEST:
2922             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
2923             return;
2924 
2925         case INFORMATION_REQUEST:
2926             if (cmd_len == 2) {
2927                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2928                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
2929             } else {
2930                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2931             }
2932             return;
2933 
2934 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2935         case INFORMATION_RESPONSE: {
2936             hci_connection_t * connection = hci_connection_for_handle(handle);
2937             if (!connection) return;
2938             if (connection->l2cap_state.information_state != L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE) return;
2939 
2940             // get extended features from response if valid
2941             connection->l2cap_state.extended_feature_mask = 0;
2942             if (cmd_len >= 6) {
2943                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2944                 uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
2945                 if (result == 0 && info_type == L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) {
2946                     connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2947                 }
2948             }
2949             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
2950             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
2951 
2952             // trigger connection request
2953             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2954             while (btstack_linked_list_iterator_has_next(&it)){
2955                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2956                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2957                 if (channel->con_handle != handle) continue;
2958 
2959                 // incoming connection: ask user for channel configuration, esp. if ertm will be mandatory
2960                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
2961                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2962                     l2cap_emit_incoming_connection(channel);
2963                     continue;
2964                 }
2965 
2966                 // outgoing connection
2967                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
2968 
2969                     // if ERTM was requested, but is not listed in extended feature mask:
2970                     if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2971 
2972                         if (channel->ertm_mandatory){
2973                             // bail if ERTM is mandatory
2974                             channel->state = L2CAP_STATE_CLOSED;
2975                             // map l2cap connection response result to BTstack status enumeration
2976                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
2977                             // discard channel
2978                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2979                             l2cap_free_channel_entry(channel);
2980                             continue;
2981 
2982                         } else {
2983                             // fallback to Basic mode
2984                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
2985                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2986                         }
2987                     }
2988 
2989                     // respond to connection request
2990                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
2991                     continue;
2992                 }
2993             }
2994             return;
2995         }
2996 #endif
2997 
2998         default:
2999             break;
3000     }
3001 
3002     // Get potential destination CID
3003     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3004 
3005     // Find channel for this sig_id and connection handle
3006     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3007     while (btstack_linked_list_iterator_has_next(&it)){
3008         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3009         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3010         if (channel->con_handle != handle) continue;
3011         if (code & 1) {
3012             // match odd commands (responses) by previous signaling identifier
3013             if (channel->local_sig_id == sig_id) {
3014                 l2cap_signaling_handler_channel(channel, command);
3015                 break;
3016             }
3017         } else {
3018             // match even commands (requests) by local channel id
3019             if (channel->local_cid == dest_cid) {
3020                 l2cap_signaling_handler_channel(channel, command);
3021                 break;
3022             }
3023         }
3024     }
3025 }
3026 #endif
3027 
3028 #ifdef ENABLE_BLE
3029 
3030 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
3031     uint8_t event[6];
3032     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
3033     event[1] = 4;
3034     little_endian_store_16(event, 2, con_handle);
3035     little_endian_store_16(event, 4, result);
3036     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3037     if (!l2cap_event_packet_handler) return;
3038     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
3039 }
3040 
3041 // @returns valid
3042 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
3043     hci_connection_t * connection;
3044     uint16_t result;
3045     uint8_t  event[12];
3046 
3047 #ifdef ENABLE_LE_DATA_CHANNELS
3048     btstack_linked_list_iterator_t it;
3049     l2cap_channel_t * channel;
3050     uint16_t local_cid;
3051     uint16_t le_psm;
3052     uint16_t new_credits;
3053     uint16_t credits_before;
3054     l2cap_service_t * service;
3055     uint16_t source_cid;
3056 #endif
3057 
3058     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3059     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3060     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
3061 
3062     switch (code){
3063 
3064         case CONNECTION_PARAMETER_UPDATE_REQUEST:
3065             // check size
3066             if (len < 8u) return 0u;
3067             connection = hci_connection_for_handle(handle);
3068             if (connection){
3069                 if (connection->role != HCI_ROLE_MASTER){
3070                     // reject command without notifying upper layer when not in master role
3071                     return 0;
3072                 }
3073                 le_connection_parameter_range_t existing_range;
3074                 gap_get_connection_parameter_range(&existing_range);
3075                 uint16_t le_conn_interval_min   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3076                 uint16_t le_conn_interval_max   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3077                 uint16_t le_conn_latency        = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3078                 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
3079 
3080                 int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
3081                 if (update_parameter){
3082                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
3083                     connection->le_conn_interval_min = le_conn_interval_min;
3084                     connection->le_conn_interval_max = le_conn_interval_max;
3085                     connection->le_conn_latency = le_conn_latency;
3086                     connection->le_supervision_timeout = le_supervision_timeout;
3087                 } else {
3088                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
3089                 }
3090                 connection->le_con_param_update_identifier = sig_id;
3091             }
3092 
3093             if (!l2cap_event_packet_handler) break;
3094 
3095             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
3096             event[1] = 8;
3097             little_endian_store_16(event, 2, handle);
3098             (void)memcpy(&event[4], &command[4], 8);
3099             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3100             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
3101             break;
3102 
3103         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
3104             // check size
3105             if (len < 2u) return 0u;
3106             result = little_endian_read_16(command, 4);
3107             l2cap_emit_connection_parameter_update_response(handle, result);
3108             break;
3109 
3110 #ifdef ENABLE_LE_DATA_CHANNELS
3111 
3112         case COMMAND_REJECT:
3113             // Find channel for this sig_id and connection handle
3114             channel = NULL;
3115             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3116             while (btstack_linked_list_iterator_has_next(&it)){
3117                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3118                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
3119                 if (a_channel->con_handle   != handle) continue;
3120                 if (a_channel->local_sig_id != sig_id) continue;
3121                 channel = a_channel;
3122                 break;
3123             }
3124             if (!channel) break;
3125 
3126             // if received while waiting for le connection response, assume legacy device
3127             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
3128                 channel->state = L2CAP_STATE_CLOSED;
3129                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
3130                 l2cap_emit_le_channel_opened(channel, 0x0002);
3131 
3132                 // discard channel
3133                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3134                 l2cap_free_channel_entry(channel);
3135                 break;
3136             }
3137             break;
3138 
3139         case LE_CREDIT_BASED_CONNECTION_REQUEST:
3140             // check size
3141             if (len < 10u) return 0u;
3142 
3143             // get hci connection, bail if not found (must not happen)
3144             connection = hci_connection_for_handle(handle);
3145             if (!connection) return 0;
3146 
3147             // check if service registered
3148             le_psm  = little_endian_read_16(command, 4);
3149             service = l2cap_le_get_service(le_psm);
3150             source_cid = little_endian_read_16(command, 6);
3151 
3152             if (service){
3153                 if (source_cid < 0x40u){
3154                     // 0x0009 Connection refused - Invalid Source CID
3155                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
3156                     return 1;
3157                 }
3158 
3159                 // go through list of channels for this ACL connection and check if we get a match
3160                 btstack_linked_list_iterator_init(&it, &l2cap_channels);
3161                 while (btstack_linked_list_iterator_has_next(&it)){
3162                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3163                     if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
3164                     if (a_channel->con_handle != handle) continue;
3165                     if (a_channel->remote_cid != source_cid) continue;
3166                     // 0x000a Connection refused - Source CID already allocated
3167                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
3168                     return 1;
3169                 }
3170 
3171                 // security: check encryption
3172                 if (service->required_security_level >= LEVEL_2){
3173                     if (gap_encryption_key_size(handle) == 0){
3174                         // 0x0008 Connection refused - insufficient encryption
3175                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
3176                         return 1;
3177                     }
3178                     // anything less than 16 byte key size is insufficient
3179                     if (gap_encryption_key_size(handle) < 16){
3180                         // 0x0007 Connection refused – insufficient encryption key size
3181                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
3182                         return 1;
3183                     }
3184                 }
3185 
3186                 // security: check authencation
3187                 if (service->required_security_level >= LEVEL_3){
3188                     if (!gap_authenticated(handle)){
3189                         // 0x0005 Connection refused – insufficient authentication
3190                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
3191                         return 1;
3192                     }
3193                 }
3194 
3195                 // security: check authorization
3196                 if (service->required_security_level >= LEVEL_4){
3197                     if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
3198                         // 0x0006 Connection refused – insufficient authorization
3199                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
3200                         return 1;
3201                     }
3202                 }
3203 
3204                 // allocate channel
3205                 channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL, connection->address,
3206                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
3207                 if (!channel){
3208                     // 0x0004 Connection refused – no resources available
3209                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
3210                     return 1;
3211                 }
3212 
3213                 channel->con_handle = handle;
3214                 channel->remote_cid = source_cid;
3215                 channel->remote_sig_id = sig_id;
3216                 channel->remote_mtu = little_endian_read_16(command, 8);
3217                 channel->remote_mps = little_endian_read_16(command, 10);
3218                 channel->credits_outgoing = little_endian_read_16(command, 12);
3219 
3220                 // set initial state
3221                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
3222                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
3223 
3224                 // add to connections list
3225                 btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
3226 
3227                 // post connection request event
3228                 l2cap_emit_le_incoming_connection(channel);
3229 
3230             } else {
3231                 // Connection refused – LE_PSM not supported
3232                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
3233             }
3234             break;
3235 
3236         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
3237             // check size
3238             if (len < 10u) return 0u;
3239 
3240             // Find channel for this sig_id and connection handle
3241             channel = NULL;
3242             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3243             while (btstack_linked_list_iterator_has_next(&it)){
3244                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3245                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
3246                 if (a_channel->con_handle   != handle) continue;
3247                 if (a_channel->local_sig_id != sig_id) continue;
3248                 channel = a_channel;
3249                 break;
3250             }
3251             if (!channel) break;
3252 
3253             // cid + 0
3254             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
3255             if (result){
3256                 channel->state = L2CAP_STATE_CLOSED;
3257                 // map l2cap connection response result to BTstack status enumeration
3258                 l2cap_emit_le_channel_opened(channel, result);
3259 
3260                 // discard channel
3261                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3262                 l2cap_free_channel_entry(channel);
3263                 break;
3264             }
3265 
3266             // success
3267             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3268             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3269             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3270             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
3271             channel->state = L2CAP_STATE_OPEN;
3272             l2cap_emit_le_channel_opened(channel, result);
3273             break;
3274 
3275         case LE_FLOW_CONTROL_CREDIT:
3276             // check size
3277             if (len < 4u) return 0u;
3278 
3279             // find channel
3280             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3281             channel = l2cap_get_channel_for_local_cid(local_cid);
3282             if (!channel) {
3283                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
3284                 break;
3285             }
3286             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3287             credits_before = channel->credits_outgoing;
3288             channel->credits_outgoing += new_credits;
3289             // check for credit overrun
3290             if (credits_before > channel->credits_outgoing){
3291                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
3292                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3293                 break;
3294             }
3295             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
3296             break;
3297 
3298         case DISCONNECTION_REQUEST:
3299 
3300             // check size
3301             if (len < 4u) return 0u;
3302 
3303             // find channel
3304             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3305             channel = l2cap_get_channel_for_local_cid(local_cid);
3306             if (!channel) {
3307                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
3308                 break;
3309             }
3310             channel->remote_sig_id = sig_id;
3311             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
3312             break;
3313 
3314 #endif
3315 
3316         case DISCONNECTION_RESPONSE:
3317             break;
3318 
3319         default:
3320             // command unknown -> reject command
3321             return 0;
3322     }
3323     return 1;
3324 }
3325 #endif
3326 
3327 #ifdef ENABLE_CLASSIC
3328 static void l2cap_acl_classic_handler_for_channel(l2cap_channel_t * l2cap_channel, uint8_t * packet, uint16_t size){
3329 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3330     if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3331 
3332         int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
3333 
3334         // assert control + FCS fields are inside
3335         if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) return;
3336 
3337         if (l2cap_channel->fcs_option){
3338             // verify FCS (required if one side requested it)
3339             uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
3340             uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
3341 
3342 #ifdef L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL
3343             // simulate fcs error
3344                         static int counter = 0;
3345                         if (++counter == L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL) {
3346                             log_info("Simulate fcs error");
3347                             fcs_calculated++;
3348                             counter = 0;
3349                         }
3350 #endif
3351 
3352             if (fcs_calculated == fcs_packet){
3353                 log_info("Packet FCS 0x%04x verified", fcs_packet);
3354             } else {
3355                 log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
3356                 // ERTM State Machine in Bluetooth Spec does not handle 'I-Frame with invalid FCS'
3357                 return;
3358             }
3359         }
3360 
3361         // switch on packet type
3362         uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3363         uint8_t  req_seq = (control >> 8) & 0x3f;
3364         int final = (control >> 7) & 0x01;
3365         if (control & 1){
3366             // S-Frame
3367             int poll  = (control >> 4) & 0x01;
3368             l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
3369             log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
3370             l2cap_ertm_tx_packet_state_t * tx_state;
3371             switch (s){
3372                 case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
3373                     log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
3374                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3375                     if (poll && final){
3376                         // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
3377                         log_error("P=F=1 in S-Frame");
3378                         break;
3379                     }
3380                     if (poll){
3381                         // check if we did request selective retransmission before <==> we have stored SDU segments
3382                         int i;
3383                         int num_stored_out_of_order_packets = 0;
3384                         for (i=0;i<l2cap_channel->num_rx_buffers;i++){
3385                             int index = l2cap_channel->rx_store_index + i;
3386                             if (index >= l2cap_channel->num_rx_buffers){
3387                                 index -= l2cap_channel->num_rx_buffers;
3388                             }
3389                             l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3390                             if (!rx_state->valid) continue;
3391                             num_stored_out_of_order_packets++;
3392                         }
3393                         if (num_stored_out_of_order_packets){
3394                             l2cap_channel->send_supervisor_frame_selective_reject = 1;
3395                         } else {
3396                             l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
3397                         }
3398                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
3399                     }
3400                     if (final){
3401                         // Stop-MonitorTimer
3402                         l2cap_ertm_stop_monitor_timer(l2cap_channel);
3403                         // If UnackedFrames > 0 then Start-RetransTimer
3404                         if (l2cap_channel->unacked_frames){
3405                             l2cap_ertm_start_retransmission_timer(l2cap_channel);
3406                         }
3407                         // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3408                         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
3409                     }
3410                     break;
3411                 case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
3412                     log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
3413                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3414                     // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
3415                     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
3416                     break;
3417                 case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
3418                     log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
3419                     break;
3420                 case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
3421                     log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
3422                     if (poll){
3423                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3424                     }
3425                     // find requested i-frame
3426                     tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
3427                     if (tx_state){
3428                         log_info("Retransmission for tx_seq %u requested", req_seq);
3429                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
3430                         tx_state->retransmission_requested = 1;
3431                         l2cap_channel->srej_active = 1;
3432                     }
3433                     break;
3434                 default:
3435                     break;
3436             }
3437         } else {
3438             // I-Frame
3439             // get control
3440             l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
3441             uint8_t tx_seq = (control >> 1) & 0x3f;
3442             log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
3443             log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
3444             log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
3445             l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3446             if (final){
3447                 // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3448                 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
3449             }
3450 
3451             // get SDU
3452             const uint8_t * payload_data = &packet[COMPLETE_L2CAP_HEADER+2];
3453             uint16_t        payload_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
3454 
3455             // assert SDU size is smaller or equal to our buffers
3456             uint16_t max_payload_size = 0;
3457             switch (sar){
3458                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
3459                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
3460                     // SDU Length + MPS
3461                     max_payload_size = l2cap_channel->local_mps + 2;
3462                     break;
3463                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
3464                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
3465                     max_payload_size = l2cap_channel->local_mps;
3466                     break;
3467                 default:
3468                     btstack_assert(false);
3469                     break;
3470             }
3471             if (payload_len > max_payload_size){
3472                 log_info("payload len %u > max payload %u -> drop packet", payload_len, max_payload_size);
3473                 return;
3474             }
3475 
3476             // check ordering
3477             if (l2cap_channel->expected_tx_seq == tx_seq){
3478                 log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
3479                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3480                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3481 
3482                 // process SDU
3483                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, payload_data, payload_len);
3484 
3485                 // process stored segments
3486                 while (true){
3487                     int index = l2cap_channel->rx_store_index;
3488                     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3489                     if (!rx_state->valid) break;
3490 
3491                     log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
3492                     l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3493                     l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3494 
3495                     rx_state->valid = 0;
3496                     l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
3497 
3498                     // update rx store index
3499                     index++;
3500                     if (index >= l2cap_channel->num_rx_buffers){
3501                         index = 0;
3502                     }
3503                     l2cap_channel->rx_store_index = index;
3504                 }
3505 
3506                 //
3507                 l2cap_channel->send_supervisor_frame_receiver_ready = 1;
3508 
3509             } else {
3510                 int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
3511                 if (delta < 2){
3512                     // store segment
3513                     l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, payload_data, payload_len);
3514 
3515                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
3516                     l2cap_channel->send_supervisor_frame_selective_reject = 1;
3517                 } else {
3518                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
3519                     l2cap_channel->send_supervisor_frame_reject = 1;
3520                 }
3521             }
3522         }
3523         return;
3524     }
3525 #endif
3526     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3527 
3528 }
3529 #endif
3530 
3531 static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3532 #ifdef ENABLE_CLASSIC
3533     l2cap_channel_t * l2cap_channel;
3534     l2cap_fixed_channel_t * l2cap_fixed_channel;
3535 
3536     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3537     switch (channel_id) {
3538 
3539         case L2CAP_CID_SIGNALING: {
3540             uint32_t command_offset = 8;
3541             while ((command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET) < size) {
3542                 // assert signaling command is fully inside packet
3543                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3544                 uint32_t next_command_offset = command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
3545                 if (next_command_offset > size){
3546                     log_error("l2cap signaling command len invalid -> drop");
3547                     break;
3548                 }
3549                 // handle signaling command
3550                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
3551                 // go to next command
3552                 command_offset = next_command_offset;
3553             }
3554             break;
3555         }
3556         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
3557             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL);
3558             if (!l2cap_fixed_channel) break;
3559             if (!l2cap_fixed_channel->packet_handler) break;
3560             (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3561             break;
3562 
3563         default:
3564             // Find channel for this channel_id and connection handle
3565             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
3566             if (l2cap_channel) {
3567                 l2cap_acl_classic_handler_for_channel(l2cap_channel, packet, size);
3568             }
3569             break;
3570     }
3571 #else
3572     UNUSED(handle); // ok: no code
3573     UNUSED(packet); // ok: no code
3574     UNUSED(size);   // ok: no code
3575 #endif
3576 }
3577 
3578 static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3579 #ifdef ENABLE_BLE
3580 
3581     l2cap_fixed_channel_t * l2cap_fixed_channel;
3582 
3583 #ifdef ENABLE_LE_DATA_CHANNELS
3584     l2cap_channel_t * l2cap_channel;
3585 #endif
3586     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3587     switch (channel_id) {
3588 
3589         case L2CAP_CID_SIGNALING_LE: {
3590             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
3591             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
3592             if ((COMPLETE_L2CAP_HEADER + 4u + len) > size) break;
3593             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
3594             if (!valid){
3595                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3596             }
3597             break;
3598         }
3599 
3600         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
3601             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL);
3602             if (!l2cap_fixed_channel) break;
3603             if (!l2cap_fixed_channel->packet_handler) break;
3604             (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3605             break;
3606 
3607         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
3608             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
3609             if (!l2cap_fixed_channel) break;
3610             if (!l2cap_fixed_channel->packet_handler) break;
3611             (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3612             break;
3613 
3614         default:
3615 
3616 #ifdef ENABLE_LE_DATA_CHANNELS
3617             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
3618             if (l2cap_channel) {
3619                 // credit counting
3620                 if (l2cap_channel->credits_incoming == 0u){
3621                     log_error("LE Data Channel packet received but no incoming credits");
3622                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3623                     break;
3624                 }
3625                 l2cap_channel->credits_incoming--;
3626 
3627                 // automatic credits
3628                 if ((l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK) && l2cap_channel->automatic_credits){
3629                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
3630                 }
3631 
3632                 // first fragment
3633                 uint16_t pos = 0;
3634                 if (!l2cap_channel->receive_sdu_len){
3635                     uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3636                     if(sdu_len > l2cap_channel->local_mtu) break;   // SDU would be larger than our buffer
3637                     l2cap_channel->receive_sdu_len = sdu_len;
3638                     l2cap_channel->receive_sdu_pos = 0;
3639                     pos  += 2u;
3640                     size -= 2u;
3641                 }
3642                 uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
3643                 uint16_t remaining_space = l2cap_channel->local_mtu - l2cap_channel->receive_sdu_pos;
3644                 if (fragment_size > remaining_space) break;         // SDU would cause buffer overrun
3645                 (void)memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos],
3646                              &packet[COMPLETE_L2CAP_HEADER + pos],
3647                              fragment_size);
3648                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
3649                 // done?
3650                 log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
3651                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
3652                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
3653                     l2cap_channel->receive_sdu_len = 0;
3654                 }
3655             } else {
3656                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
3657             }
3658 #endif
3659             break;
3660     }
3661 #else
3662     UNUSED(handle); // ok: no code
3663     UNUSED(packet); // ok: no code
3664     UNUSED(size);   // ok: no code
3665 #endif
3666 }
3667 
3668 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
3669     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
3670     UNUSED(channel);        // ok: there is no channel
3671 
3672     // Assert full L2CAP header present
3673     if (size < COMPLETE_L2CAP_HEADER) return;
3674 
3675     // Dispatch to Classic or LE handler (SCO packets are not dispatched to L2CAP)
3676     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
3677     hci_connection_t *conn = hci_connection_for_handle(handle);
3678     if (!conn) return;
3679     if (conn->address_type == BD_ADDR_TYPE_ACL){
3680         l2cap_acl_classic_handler(handle, packet, size);
3681     } else {
3682         l2cap_acl_le_handler(handle, packet, size);
3683     }
3684 
3685     l2cap_run();
3686 }
3687 
3688 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
3689 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
3690     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
3691     if (!channel) return;
3692     channel->packet_handler = the_packet_handler;
3693 }
3694 
3695 #ifdef ENABLE_CLASSIC
3696 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
3697 void l2cap_finialize_channel_close(l2cap_channel_t * channel){
3698     channel->state = L2CAP_STATE_CLOSED;
3699     l2cap_handle_channel_closed(channel);
3700     // discard channel
3701     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3702     l2cap_free_channel_entry(channel);
3703 }
3704 #endif
3705 
3706 #ifdef L2CAP_USES_CHANNELS
3707 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3708     btstack_linked_list_iterator_t it;
3709     btstack_linked_list_iterator_init(&it, services);
3710     while (btstack_linked_list_iterator_has_next(&it)){
3711         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
3712         if ( service->psm == psm){
3713             return service;
3714         };
3715     }
3716     return NULL;
3717 }
3718 #endif
3719 
3720 #ifdef ENABLE_CLASSIC
3721 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
3722     return l2cap_get_service_internal(&l2cap_services, psm);
3723 }
3724 
3725 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
3726 
3727     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
3728 
3729     // check for alread registered psm
3730     l2cap_service_t *service = l2cap_get_service(psm);
3731     if (service) {
3732         log_error("l2cap_register_service: PSM %u already registered", psm);
3733         return L2CAP_SERVICE_ALREADY_REGISTERED;
3734     }
3735 
3736     // alloc structure
3737     service = btstack_memory_l2cap_service_get();
3738     if (!service) {
3739         log_error("l2cap_register_service: no memory for l2cap_service_t");
3740         return BTSTACK_MEMORY_ALLOC_FAILED;
3741     }
3742 
3743     // fill in
3744     service->psm = psm;
3745     service->mtu = mtu;
3746     service->packet_handler = service_packet_handler;
3747     service->required_security_level = security_level;
3748 
3749     // add to services list
3750     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
3751 
3752     // enable page scan
3753     gap_connectable_control(1);
3754 
3755     return ERROR_CODE_SUCCESS;
3756 }
3757 
3758 uint8_t l2cap_unregister_service(uint16_t psm){
3759 
3760     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
3761 
3762     l2cap_service_t *service = l2cap_get_service(psm);
3763     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3764     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
3765     btstack_memory_l2cap_service_free(service);
3766 
3767     // disable page scan when no services registered
3768     if (btstack_linked_list_empty(&l2cap_services)) {
3769         gap_connectable_control(0);
3770     }
3771     return ERROR_CODE_SUCCESS;
3772 }
3773 #endif
3774 
3775 
3776 #ifdef ENABLE_LE_DATA_CHANNELS
3777 
3778 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
3779     if (!channel->waiting_for_can_send_now) return;
3780     if (channel->send_sdu_buffer) return;
3781     channel->waiting_for_can_send_now = 0;
3782     log_debug("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
3783     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
3784 }
3785 
3786 // 1BH2222
3787 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
3788     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",
3789              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
3790     uint8_t event[19];
3791     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
3792     event[1] = sizeof(event) - 2u;
3793     event[2] = channel->address_type;
3794     reverse_bd_addr(channel->address, &event[3]);
3795     little_endian_store_16(event,  9, channel->con_handle);
3796     little_endian_store_16(event, 11, channel->psm);
3797     little_endian_store_16(event, 13, channel->local_cid);
3798     little_endian_store_16(event, 15, channel->remote_cid);
3799     little_endian_store_16(event, 17, channel->remote_mtu);
3800     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3801     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3802 }
3803 // 11BH22222
3804 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
3805     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",
3806              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
3807              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
3808     uint8_t event[23];
3809     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
3810     event[1] = sizeof(event) - 2u;
3811     event[2] = status;
3812     event[3] = channel->address_type;
3813     reverse_bd_addr(channel->address, &event[4]);
3814     little_endian_store_16(event, 10, channel->con_handle);
3815     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
3816     little_endian_store_16(event, 13, channel->psm);
3817     little_endian_store_16(event, 15, channel->local_cid);
3818     little_endian_store_16(event, 17, channel->remote_cid);
3819     little_endian_store_16(event, 19, channel->local_mtu);
3820     little_endian_store_16(event, 21, channel->remote_mtu);
3821     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3822     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3823 }
3824 // 2
3825 static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel){
3826     log_info("L2CAP_EVENT_LE_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
3827     uint8_t event[4];
3828     event[0] = L2CAP_EVENT_LE_CHANNEL_CLOSED;
3829     event[1] = sizeof(event) - 2u;
3830     little_endian_store_16(event, 2, channel->local_cid);
3831     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3832     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3833 }
3834 
3835 static void l2cap_le_send_pdu(l2cap_channel_t *channel){
3836     btstack_assert(channel != NULL);
3837     btstack_assert(channel->send_sdu_buffer != NULL);
3838     btstack_assert(channel->credits_outgoing > 0);
3839 
3840     // send part of SDU
3841     hci_reserve_packet_buffer();
3842     uint8_t * acl_buffer = hci_get_outgoing_packet_buffer();
3843     uint8_t * l2cap_payload = acl_buffer + 8;
3844     uint16_t pos = 0;
3845     if (!channel->send_sdu_pos){
3846         // store SDU len
3847         channel->send_sdu_pos += 2u;
3848         little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
3849         pos += 2u;
3850     }
3851     uint16_t payload_size = btstack_min(channel->send_sdu_len + 2u - channel->send_sdu_pos, channel->remote_mps - pos);
3852     log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
3853     (void)memcpy(&l2cap_payload[pos],
3854                  &channel->send_sdu_buffer[channel->send_sdu_pos - 2u],
3855                  payload_size); // -2 for virtual SDU len
3856     pos += payload_size;
3857     channel->send_sdu_pos += payload_size;
3858     l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
3859 
3860     channel->credits_outgoing--;
3861 
3862     hci_send_acl_packet_buffer(8u + pos);
3863 
3864     if (channel->send_sdu_pos >= (channel->send_sdu_len + 2u)){
3865         channel->send_sdu_buffer = NULL;
3866         // send done event
3867         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
3868         // inform about can send now
3869         l2cap_le_notify_channel_can_send(channel);
3870     }
3871 }
3872 
3873 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
3874 void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
3875     channel->state = L2CAP_STATE_CLOSED;
3876     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
3877     // discard channel
3878     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3879     l2cap_free_channel_entry(channel);
3880 }
3881 
3882 static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
3883     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
3884 }
3885 
3886 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
3887 
3888     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
3889 
3890     // check for alread registered psm
3891     l2cap_service_t *service = l2cap_le_get_service(psm);
3892     if (service) {
3893         return L2CAP_SERVICE_ALREADY_REGISTERED;
3894     }
3895 
3896     // alloc structure
3897     service = btstack_memory_l2cap_service_get();
3898     if (!service) {
3899         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
3900         return BTSTACK_MEMORY_ALLOC_FAILED;
3901     }
3902 
3903     // fill in
3904     service->psm = psm;
3905     service->mtu = 0;
3906     service->packet_handler = packet_handler;
3907     service->required_security_level = security_level;
3908 
3909     // add to services list
3910     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
3911 
3912     // done
3913     return ERROR_CODE_SUCCESS;
3914 }
3915 
3916 uint8_t l2cap_le_unregister_service(uint16_t psm) {
3917     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
3918     l2cap_service_t *service = l2cap_le_get_service(psm);
3919     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3920 
3921     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
3922     btstack_memory_l2cap_service_free(service);
3923     return ERROR_CODE_SUCCESS;
3924 }
3925 
3926 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
3927     // get channel
3928     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3929     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3930 
3931     // validate state
3932     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3933         return ERROR_CODE_COMMAND_DISALLOWED;
3934     }
3935 
3936     // set state accept connection
3937     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
3938     channel->receive_sdu_buffer = receive_sdu_buffer;
3939     channel->local_mtu = mtu;
3940     channel->new_credits_incoming = initial_credits;
3941     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
3942 
3943     // test
3944     // channel->new_credits_incoming = 1;
3945 
3946     // go
3947     l2cap_run();
3948     return ERROR_CODE_SUCCESS;
3949 }
3950 
3951 /**
3952  * @brief Deny incoming LE Data Channel connection due to resource constraints
3953  * @param local_cid             L2CAP LE Data Channel Identifier
3954  */
3955 
3956 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
3957     // get channel
3958     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3959     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3960 
3961     // validate state
3962     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3963         return ERROR_CODE_COMMAND_DISALLOWED;
3964     }
3965 
3966     // set state decline connection
3967     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
3968     channel->reason = 0x04; // no resources available
3969     l2cap_run();
3970     return ERROR_CODE_SUCCESS;
3971 }
3972 
3973 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
3974     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
3975     uint16_t * out_local_cid) {
3976 
3977     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
3978 
3979 
3980     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3981     if (!connection) {
3982         log_error("no hci_connection for handle 0x%04x", con_handle);
3983         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3984     }
3985 
3986     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);
3987     if (!channel) {
3988         return BTSTACK_MEMORY_ALLOC_FAILED;
3989     }
3990     log_info("l2cap_le_create_channel %p", channel);
3991 
3992     // store local_cid
3993     if (out_local_cid){
3994        *out_local_cid = channel->local_cid;
3995     }
3996 
3997     // provide buffer
3998     channel->con_handle = con_handle;
3999     channel->receive_sdu_buffer = receive_sdu_buffer;
4000     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
4001     channel->new_credits_incoming = initial_credits;
4002     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
4003 
4004     // add to connections list
4005     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
4006 
4007     // go
4008     l2cap_run();
4009     return ERROR_CODE_SUCCESS;
4010 }
4011 
4012 /**
4013  * @brief Provide credtis for LE Data Channel
4014  * @param local_cid             L2CAP LE Data Channel Identifier
4015  * @param credits               Number additional credits for peer
4016  */
4017 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
4018 
4019     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4020     if (!channel) {
4021         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
4022         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4023     }
4024 
4025     // check state
4026     if (channel->state != L2CAP_STATE_OPEN){
4027         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
4028     }
4029 
4030     // assert incoming credits + credits <= 0xffff
4031     uint32_t total_credits = channel->credits_incoming;
4032     total_credits += channel->new_credits_incoming;
4033     total_credits += credits;
4034     if (total_credits > 0xffffu){
4035         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
4036             channel->new_credits_incoming, credits);
4037     }
4038 
4039     // set credits_granted
4040     channel->new_credits_incoming += credits;
4041 
4042     // go
4043     l2cap_run();
4044     return ERROR_CODE_SUCCESS;
4045 }
4046 
4047 /**
4048  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
4049  * @param local_cid             L2CAP LE Data Channel Identifier
4050  */
4051 int l2cap_le_can_send_now(uint16_t local_cid){
4052     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4053     if (!channel) {
4054         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
4055         return 0;
4056     }
4057 
4058     // check state
4059     if (channel->state != L2CAP_STATE_OPEN) return 0;
4060 
4061     // check queue
4062     if (channel->send_sdu_buffer) return 0;
4063 
4064     // fine, go ahead
4065     return 1;
4066 }
4067 
4068 /**
4069  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
4070  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
4071  *       so packet handler should be ready to handle it
4072  * @param local_cid             L2CAP LE Data Channel Identifier
4073  */
4074 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
4075     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4076     if (!channel) {
4077         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
4078         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4079     }
4080     channel->waiting_for_can_send_now = 1;
4081     l2cap_le_notify_channel_can_send(channel);
4082     return ERROR_CODE_SUCCESS;
4083 }
4084 
4085 /**
4086  * @brief Send data via LE Data Channel
4087  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
4088  * @param local_cid             L2CAP LE Data Channel Identifier
4089  * @param data                  data to send
4090  * @param size                  data size
4091  */
4092 uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
4093 
4094     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4095     if (!channel) {
4096         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4097         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4098     }
4099 
4100     if (len > channel->remote_mtu){
4101         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
4102         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
4103     }
4104 
4105     if (channel->send_sdu_buffer){
4106         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
4107         return BTSTACK_ACL_BUFFERS_FULL;
4108     }
4109 
4110     channel->send_sdu_buffer = data;
4111     channel->send_sdu_len    = len;
4112     channel->send_sdu_pos    = 0;
4113 
4114     l2cap_notify_channel_can_send();
4115     return ERROR_CODE_SUCCESS;
4116 }
4117 
4118 /**
4119  * @brief Disconnect from LE Data Channel
4120  * @param local_cid             L2CAP LE Data Channel Identifier
4121  */
4122 uint8_t l2cap_le_disconnect(uint16_t local_cid)
4123 {
4124     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4125     if (!channel) {
4126         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4127         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4128     }
4129 
4130     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4131     l2cap_run();
4132     return ERROR_CODE_SUCCESS;
4133 }
4134 
4135 #endif
4136