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