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