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