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