xref: /btstack/src/l2cap.c (revision 9c6e867ea60e26979e8ba80bb3e93f18d65239e2)
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         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1567         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1568         switch (channel->state){
1569             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
1570                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1571                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
1572                 // le psm, source cid, mtu, mps, initial credits
1573                 channel->local_sig_id = l2cap_next_sig_id();
1574                 channel->credits_incoming =  channel->new_credits_incoming;
1575                 channel->new_credits_incoming = 0;
1576                 l2cap_send_le_signaling_packet( channel->con_handle, LE_CREDIT_BASED_CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid, channel->local_mtu, 23, channel->credits_incoming);
1577                 break;
1578             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
1579                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1580                 // TODO: support larger MPS
1581                 channel->state = L2CAP_STATE_OPEN;
1582                 channel->credits_incoming =  channel->new_credits_incoming;
1583                 channel->new_credits_incoming = 0;
1584                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->local_mtu, 23, channel->credits_incoming, 0);
1585                 // notify client
1586                 l2cap_emit_le_channel_opened(channel, 0);
1587                 break;
1588             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
1589                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1590                 channel->state = L2CAP_STATE_INVALID;
1591                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
1592                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1593                 l2cap_stop_rtx(channel);
1594                 btstack_linked_list_iterator_remove(&it);
1595                 btstack_memory_l2cap_channel_free(channel);
1596                 break;
1597             case L2CAP_STATE_OPEN:
1598                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1599 
1600                 // send credits
1601                 if (channel->new_credits_incoming){
1602                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
1603                     channel->local_sig_id = l2cap_next_sig_id();
1604                     uint16_t new_credits = channel->new_credits_incoming;
1605                     channel->new_credits_incoming = 0;
1606                     channel->credits_incoming += new_credits;
1607                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
1608                     break;
1609                 }
1610 
1611                 // send data
1612                 if (!channel->send_sdu_buffer) break;
1613                 if (!channel->credits_outgoing) break;
1614 
1615                 // send part of SDU
1616                 hci_reserve_packet_buffer();
1617                 acl_buffer = hci_get_outgoing_packet_buffer();
1618                 l2cap_payload = acl_buffer + 8;
1619                 pos = 0;
1620                 if (!channel->send_sdu_pos){
1621                     // store SDU len
1622                     channel->send_sdu_pos += 2;
1623                     little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
1624                     pos += 2;
1625                 }
1626                 payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
1627                 log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
1628                 memcpy(&l2cap_payload[pos], &channel->send_sdu_buffer[channel->send_sdu_pos-2], payload_size); // -2 for virtual SDU len
1629                 pos += payload_size;
1630                 channel->send_sdu_pos += payload_size;
1631                 l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
1632                 // done
1633 
1634                 channel->credits_outgoing--;
1635 
1636                 if (channel->send_sdu_pos >= channel->send_sdu_len + 2){
1637                     channel->send_sdu_buffer = NULL;
1638                     // send done event
1639                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
1640                     // inform about can send now
1641                     l2cap_le_notify_channel_can_send(channel);
1642                 }
1643                 hci_send_acl_packet_buffer(8 + pos);
1644                 break;
1645             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1646                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1647                 channel->local_sig_id = l2cap_next_sig_id();
1648                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1649                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1650                 break;
1651             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1652                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1653                 channel->state = L2CAP_STATE_INVALID;
1654                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1655                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
1656                 break;
1657             default:
1658                 break;
1659         }
1660     }
1661 #endif
1662 
1663 #ifdef ENABLE_BLE
1664     // send l2cap con paramter update if necessary
1665     hci_connections_get_iterator(&it);
1666     while(btstack_linked_list_iterator_has_next(&it)){
1667         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1668         if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue;
1669         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
1670         switch (connection->le_con_parameter_update_state){
1671             case CON_PARAMETER_UPDATE_SEND_REQUEST:
1672                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1673                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier,
1674                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
1675                 break;
1676             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
1677                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
1678                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
1679                 break;
1680             case CON_PARAMETER_UPDATE_DENY:
1681                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1682                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
1683                 break;
1684             default:
1685                 break;
1686         }
1687     }
1688 #endif
1689 
1690     // log_info("l2cap_run: exit");
1691 }
1692 
1693 #ifdef ENABLE_CLASSIC
1694 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
1695     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
1696         log_info("l2cap_handle_connection_complete expected state");
1697         // success, start l2cap handshake
1698         channel->con_handle = con_handle;
1699         // check remote SSP feature first
1700         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
1701     }
1702 }
1703 
1704 static void l2cap_ready_to_connect(l2cap_channel_t * channel){
1705 
1706 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1707     // assumption: outgoing connection
1708     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
1709     if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
1710         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
1711         channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
1712         return;
1713     }
1714 #endif
1715 
1716     // fine, go ahead
1717     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
1718 }
1719 
1720 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
1721     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
1722 
1723     // we have been waiting for remote supported features, if both support SSP,
1724     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));
1725     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
1726         // request security level 2
1727         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
1728         channel->required_security_level = LEVEL_2;
1729         gap_request_security_level(channel->con_handle, LEVEL_2);
1730         return;
1731     }
1732 
1733     l2cap_ready_to_connect(channel);
1734 }
1735 #endif
1736 
1737 #ifdef L2CAP_USES_CHANNELS
1738 static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, bd_addr_t address, bd_addr_type_t address_type,
1739     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
1740 
1741     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1742     if (!channel) {
1743         return NULL;
1744     }
1745 
1746      // Init memory (make valgrind happy)
1747     memset(channel, 0, sizeof(l2cap_channel_t));
1748 
1749     // fill in
1750     channel->packet_handler = packet_handler;
1751     bd_addr_copy(channel->address, address);
1752     channel->address_type = address_type;
1753     channel->psm = psm;
1754     channel->local_mtu  = local_mtu;
1755     channel->remote_mtu = L2CAP_DEFAULT_MTU;
1756     channel->required_security_level = security_level;
1757 
1758     //
1759     channel->local_cid = l2cap_next_local_cid();
1760     channel->con_handle = 0;
1761 
1762     // set initial state
1763     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
1764     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
1765     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
1766     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
1767 
1768     return channel;
1769 }
1770 #endif
1771 
1772 #ifdef ENABLE_CLASSIC
1773 
1774 /**
1775  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
1776  * @param packet_handler
1777  * @param address
1778  * @param psm
1779  * @param mtu
1780  * @param local_cid
1781  */
1782 
1783 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){
1784     // limit MTU to the size of our outtgoing HCI buffer
1785     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1786 
1787     log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x mtu %u -> local mtu %u", bd_addr_to_str(address), psm, mtu, local_mtu);
1788 
1789     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
1790     if (!channel) {
1791         return BTSTACK_MEMORY_ALLOC_FAILED;
1792     }
1793 
1794 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1795     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
1796 #endif
1797 
1798     // add to connections list
1799     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1800 
1801     // store local_cid
1802     if (out_local_cid){
1803        *out_local_cid = channel->local_cid;
1804     }
1805 
1806     // check if hci connection is already usable
1807     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
1808     if (conn){
1809         log_info("l2cap_create_channel, hci connection already exists");
1810         l2cap_handle_connection_complete(conn->con_handle, channel);
1811         // check if remote supported fearures are already received
1812         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
1813             l2cap_handle_remote_supported_features_received(channel);
1814         }
1815     }
1816 
1817     l2cap_run();
1818 
1819     return 0;
1820 }
1821 
1822 void
1823 l2cap_disconnect(uint16_t local_cid, uint8_t reason){
1824     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
1825     // find channel for local_cid
1826     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1827     if (channel) {
1828         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1829     }
1830     // process
1831     l2cap_run();
1832 }
1833 
1834 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
1835     // mark all channels before emitting open events as these could trigger new connetion requests to the same device
1836     btstack_linked_list_iterator_t it;
1837     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1838     while (btstack_linked_list_iterator_has_next(&it)){
1839         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1840         if ( bd_addr_cmp( channel->address, address) != 0) continue;
1841         // channel for this address found
1842         switch (channel->state){
1843             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
1844             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1845                 channel->state = L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD;
1846                 break;
1847             default:
1848                 break;
1849         }
1850     }
1851     // emit and free marked entries. restart loop to deal with list changes
1852     int done = 0;
1853     while (!done) {
1854         done = 1;
1855         btstack_linked_list_iterator_init(&it, &l2cap_channels);
1856         while (btstack_linked_list_iterator_has_next(&it)){
1857             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1858             if (channel->state == L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD){
1859                 done = 0;
1860                 // failure, forward error code
1861                 l2cap_emit_channel_opened(channel, status);
1862                 // discard channel
1863                 l2cap_stop_rtx(channel);
1864                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1865                 btstack_memory_l2cap_channel_free(channel);
1866                 break;
1867             }
1868         }
1869     }
1870 
1871 }
1872 
1873 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
1874     btstack_linked_list_iterator_t it;
1875     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1876     while (btstack_linked_list_iterator_has_next(&it)){
1877         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1878         if ( ! bd_addr_cmp( channel->address, address) ){
1879             l2cap_handle_connection_complete(handle, channel);
1880         }
1881     }
1882     // process
1883     l2cap_run();
1884 }
1885 #endif
1886 
1887 static void l2cap_notify_channel_can_send(void){
1888 
1889 #ifdef ENABLE_CLASSIC
1890     btstack_linked_list_iterator_t it;
1891     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1892     while (btstack_linked_list_iterator_has_next(&it)){
1893         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1894         if (!channel->waiting_for_can_send_now) continue;
1895         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
1896         channel->waiting_for_can_send_now = 0;
1897         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
1898     }
1899 #endif
1900 
1901 #if 1
1902     if (fixed_channel_head_index != FIXED_CHANNEL_FIFO_INVALID_INDEX){
1903         int can_send = 0;
1904         int remove_entry = 1;
1905         uint8_t i = fixed_channel_head_index;
1906         if (fixed_channels[i].callback && fixed_channels[i].waiting_for_can_send_now){
1907             if (l2cap_fixed_channel_table_index_is_le(i)){
1908 #ifdef ENABLE_BLE
1909                 can_send = hci_can_send_acl_le_packet_now();
1910                 remove_entry = can_send;
1911 #endif
1912             } else {
1913 #ifdef ENABLE_CLASSIC
1914                 can_send = hci_can_send_acl_classic_packet_now();
1915                 remove_entry = can_send;
1916 #endif
1917             }
1918         }
1919         // remove entry
1920         if (remove_entry){
1921             fixed_channels[i].waiting_for_can_send_now = 0;
1922             fixed_channel_head_index = fixed_channels[i].next_request;
1923             fixed_channels[i].next_request = FIXED_CHANNEL_FIFO_INVALID_INDEX;
1924             if (fixed_channel_head_index == FIXED_CHANNEL_FIFO_INVALID_INDEX){
1925                 fixed_channel_tail_index = FIXED_CHANNEL_FIFO_INVALID_INDEX;
1926             }
1927         }
1928         // notify
1929         if (can_send) {
1930             l2cap_emit_can_send_now(fixed_channels[i].callback, l2cap_fixed_channel_table_channel_id_for_index(i));
1931         }
1932     }
1933 #else
1934     int i;
1935     for (i=0;i<L2CAP_FIXED_CHANNEL_TABLE_SIZE;i++){
1936         if (!fixed_channels[i].callback) continue;
1937         if (!fixed_channels[i].waiting_for_can_send_now) continue;
1938         int can_send = 0;
1939         if (l2cap_fixed_channel_table_index_is_le(i)){
1940 #ifdef ENABLE_BLE
1941             can_send = hci_can_send_acl_le_packet_now();
1942 #endif
1943         } else {
1944 #ifdef ENABLE_CLASSIC
1945             can_send = hci_can_send_acl_classic_packet_now();
1946 #endif
1947         }
1948         if (!can_send) continue;
1949         fixed_channels[i].waiting_for_can_send_now = 0;
1950         l2cap_emit_can_send_now(fixed_channels[i].callback, l2cap_fixed_channel_table_channel_id_for_index(i));
1951     }
1952 
1953 #endif
1954 
1955 }
1956 
1957 #ifdef L2CAP_USES_CHANNELS
1958 
1959 static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){
1960     // open cannot fail for for incoming connections
1961     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0;
1962 
1963     // check state
1964     switch (channel->state){
1965         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1966         case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
1967         case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES:
1968         case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
1969         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
1970         case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES:
1971         case L2CAP_STATE_WAIT_CONNECT_RSP:
1972         case L2CAP_STATE_CONFIG:
1973         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
1974         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
1975         case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE:
1976         case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD:
1977             return 1;
1978 
1979         case L2CAP_STATE_OPEN:
1980         case L2CAP_STATE_CLOSED:
1981         case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES:
1982         case L2CAP_STATE_WAIT_DISCONNECT:
1983         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY:
1984         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
1985         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
1986         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1987         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1988         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
1989         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
1990         case L2CAP_STATE_INVALID:
1991         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1992             return 0;
1993         // no default here, to get a warning about new states
1994     }
1995     // still, the compiler insists on a return value
1996     return 0;
1997 }
1998 
1999 static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){
2000     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2001         l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2002     } else {
2003         l2cap_emit_channel_closed(channel);
2004     }
2005     btstack_memory_l2cap_channel_free(channel);
2006 }
2007 
2008 #endif
2009 
2010 
2011 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
2012 
2013     UNUSED(packet_type); // ok: registered with hci_event_callback_registration
2014     UNUSED(cid);         // ok: there is no channel
2015     UNUSED(size);        // ok: fixed format events read from HCI buffer
2016 
2017 #ifdef ENABLE_CLASSIC
2018     bd_addr_t address;
2019     int hci_con_used;
2020 #endif
2021 #ifdef L2CAP_USES_CHANNELS
2022     hci_con_handle_t handle;
2023     btstack_linked_list_iterator_t it;
2024 #endif
2025 
2026     switch(hci_event_packet_get_type(packet)){
2027 
2028         // Notify channel packet handler if they can send now
2029         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2030         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
2031             l2cap_run();    // try sending signaling packets first
2032             l2cap_notify_channel_can_send();
2033             break;
2034 
2035         case HCI_EVENT_COMMAND_STATUS:
2036             l2cap_run();    // try sending signaling packets first
2037             break;
2038 
2039 #ifdef ENABLE_CLASSIC
2040         // handle connection complete events
2041         case HCI_EVENT_CONNECTION_COMPLETE:
2042             reverse_bd_addr(&packet[5], address);
2043             if (packet[2] == 0){
2044                 handle = little_endian_read_16(packet, 3);
2045                 l2cap_handle_connection_success_for_addr(address, handle);
2046             } else {
2047                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
2048             }
2049             break;
2050 
2051         // handle successful create connection cancel command
2052         case HCI_EVENT_COMMAND_COMPLETE:
2053             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
2054                 if (packet[5] == 0){
2055                     reverse_bd_addr(&packet[6], address);
2056                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
2057                     l2cap_handle_connection_failed_for_addr(address, 0x16);
2058                 }
2059             }
2060             l2cap_run();    // try sending signaling packets first
2061             break;
2062 #endif
2063 
2064 #ifdef L2CAP_USES_CHANNELS
2065         // handle disconnection complete events
2066         case HCI_EVENT_DISCONNECTION_COMPLETE:
2067             handle = little_endian_read_16(packet, 3);
2068             // send l2cap open failed or closed events for all channels on this handle and free them
2069 #ifdef ENABLE_CLASSIC
2070             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2071             while (btstack_linked_list_iterator_has_next(&it)){
2072                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2073                 if (channel->con_handle != handle) continue;
2074                 btstack_linked_list_iterator_remove(&it);
2075                 l2cap_stop_rtx(channel);
2076                 l2cap_handle_hci_disconnect_event(channel);
2077             }
2078 #endif
2079 #ifdef ENABLE_LE_DATA_CHANNELS
2080             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2081             while (btstack_linked_list_iterator_has_next(&it)){
2082                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2083                 if (channel->con_handle != handle) continue;
2084                 btstack_linked_list_iterator_remove(&it);
2085                 l2cap_handle_hci_disconnect_event(channel);
2086             }
2087 #endif
2088             break;
2089 #endif
2090 
2091         // HCI Connection Timeouts
2092 #ifdef ENABLE_CLASSIC
2093         case L2CAP_EVENT_TIMEOUT_CHECK:
2094             handle = little_endian_read_16(packet, 2);
2095             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
2096             if (hci_authentication_active_for_handle(handle)) break;
2097             hci_con_used = 0;
2098             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2099             while (btstack_linked_list_iterator_has_next(&it)){
2100                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2101                 if (channel->con_handle != handle) continue;
2102                 hci_con_used = 1;
2103                 break;
2104             }
2105             if (hci_con_used) break;
2106             if (!hci_can_send_command_packet_now()) break;
2107             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
2108             break;
2109 
2110         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2111             handle = little_endian_read_16(packet, 3);
2112             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2113             while (btstack_linked_list_iterator_has_next(&it)){
2114                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2115                 if (channel->con_handle != handle) continue;
2116                 l2cap_handle_remote_supported_features_received(channel);
2117                 break;
2118             }
2119             break;
2120 
2121         case GAP_EVENT_SECURITY_LEVEL:
2122             handle = little_endian_read_16(packet, 2);
2123             log_info("l2cap - security level update");
2124             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2125             while (btstack_linked_list_iterator_has_next(&it)){
2126                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2127                 if (channel->con_handle != handle) continue;
2128 
2129                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
2130                 gap_security_level_t required_level = channel->required_security_level;
2131 
2132                 log_info("channel state %u: actual %u >= required %u?", channel->state, actual_level, required_level);
2133 
2134                 switch (channel->state){
2135                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2136                         if (actual_level >= required_level){
2137 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2138                             // we need to know if ERTM is supported before sending a config response
2139                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
2140                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2141                             channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
2142 #else
2143                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2144                             l2cap_emit_incoming_connection(channel);
2145 #endif
2146                         } else {
2147                             channel->reason = 0x0003; // security block
2148                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2149                         }
2150                         break;
2151 
2152                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2153                         if (actual_level >= required_level){
2154                             l2cap_ready_to_connect(channel);
2155                         } else {
2156                             // disconnnect, authentication not good enough
2157                             hci_disconnect_security_block(handle);
2158                         }
2159                         break;
2160 
2161                     default:
2162                         break;
2163                 }
2164             }
2165             break;
2166 #endif
2167 
2168         default:
2169             break;
2170     }
2171 
2172     l2cap_run();
2173 }
2174 
2175 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t cid, uint16_t data){
2176     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused."
2177     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
2178         signaling_responses[signaling_responses_pending].handle = handle;
2179         signaling_responses[signaling_responses_pending].code = code;
2180         signaling_responses[signaling_responses_pending].sig_id = sig_id;
2181         signaling_responses[signaling_responses_pending].cid = cid;
2182         signaling_responses[signaling_responses_pending].data = data;
2183         signaling_responses_pending++;
2184         l2cap_run();
2185     }
2186 }
2187 
2188 #ifdef ENABLE_CLASSIC
2189 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
2190     channel->remote_sig_id = identifier;
2191     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
2192     l2cap_run();
2193 }
2194 
2195 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
2196 
2197     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
2198     l2cap_service_t *service = l2cap_get_service(psm);
2199     if (!service) {
2200         // 0x0002 PSM not supported
2201         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2202         return;
2203     }
2204 
2205     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
2206     if (!hci_connection) {
2207         //
2208         log_error("no hci_connection for handle %u", handle);
2209         return;
2210     }
2211 
2212     // alloc structure
2213     // log_info("l2cap_handle_connection_request register channel");
2214     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, hci_connection->address, BD_ADDR_TYPE_CLASSIC,
2215     psm, service->mtu, service->required_security_level);
2216     if (!channel){
2217         // 0x0004 No resources available
2218         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2219         return;
2220     }
2221 
2222     channel->con_handle = handle;
2223     channel->remote_cid = source_cid;
2224     channel->remote_sig_id = sig_id;
2225 
2226     // limit local mtu to max acl packet length - l2cap header
2227     if (channel->local_mtu > l2cap_max_mtu()) {
2228         channel->local_mtu = l2cap_max_mtu();
2229     }
2230 
2231     // set initial state
2232     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
2233     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
2234 
2235     // add to connections list
2236     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
2237 
2238     // assert security requirements
2239     gap_request_security_level(handle, channel->required_security_level);
2240 }
2241 
2242 void l2cap_accept_connection(uint16_t local_cid){
2243     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
2244     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2245     if (!channel) {
2246         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
2247         return;
2248     }
2249 
2250 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2251     // configure L2CAP Basic mode
2252     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
2253 #endif
2254 
2255     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
2256 
2257     // process
2258     l2cap_run();
2259 }
2260 
2261 void l2cap_decline_connection(uint16_t local_cid){
2262     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
2263     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
2264     if (!channel) {
2265         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
2266         return;
2267     }
2268     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2269     channel->reason = 0x04; // no resources available
2270     l2cap_run();
2271 }
2272 
2273 // @pre command len is valid, see check in l2cap_signaling_handler_channel
2274 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
2275 
2276 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2277     uint8_t use_fcs = 1;
2278 #endif
2279 
2280     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2281 
2282     uint16_t flags = little_endian_read_16(command, 6);
2283     if (flags & 1) {
2284         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
2285     }
2286 
2287     // accept the other's configuration options
2288     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2289     uint16_t pos     = 8;
2290     while (pos < end_pos){
2291         uint8_t option_hint = command[pos] >> 7;
2292         uint8_t option_type = command[pos] & 0x7f;
2293         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
2294         pos++;
2295         uint8_t length = command[pos++];
2296         // MTU { type(8): 1, len(8):2, MTU(16) }
2297         if (option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT && length == 2){
2298             channel->remote_mtu = little_endian_read_16(command, pos);
2299             log_info("Remote MTU %u", channel->remote_mtu);
2300             if (channel->remote_mtu > l2cap_max_mtu()){
2301                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
2302                 channel->remote_mtu = l2cap_max_mtu();
2303             }
2304             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
2305         }
2306         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
2307         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT && length == 2){
2308             channel->flush_timeout = little_endian_read_16(command, pos);
2309             log_info("Flush timeout: %u ms", channel->flush_timeout);
2310         }
2311 
2312 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2313         // Retransmission and Flow Control Option
2314         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2315             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
2316             switch(channel->mode){
2317                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2318                     // Store remote config
2319                     channel->remote_tx_window_size = command[pos+1];
2320                     channel->remote_max_transmit   = command[pos+2];
2321                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
2322                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
2323                     channel->remote_mps = little_endian_read_16(command, pos + 7);
2324                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
2325                         channel->remote_tx_window_size,
2326                         channel->remote_max_transmit,
2327                         channel->remote_retransmission_timeout_ms,
2328                         channel->remote_monitor_timeout_ms,
2329                         channel->remote_mps);
2330                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
2331                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
2332                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2333                     } else {
2334                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
2335                     }
2336                     break;
2337                 case L2CAP_CHANNEL_MODE_BASIC:
2338                     switch (mode){
2339                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2340                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
2341                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
2342                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2343                             }
2344                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
2345                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
2346                             break;
2347                         default: // case L2CAP_CHANNEL_MODE_BASIC:
2348                             // TODO store and evaluate configuration
2349                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
2350                             break;
2351                     }
2352                     break;
2353                 default:
2354                     break;
2355             }
2356         }
2357         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
2358             use_fcs = command[pos];
2359         }
2360 #endif
2361         // check for unknown options
2362         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
2363             log_info("l2cap cid %u, unknown options", channel->local_cid);
2364             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
2365         }
2366         pos += length;
2367     }
2368 
2369 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2370         // "FCS" has precedence over "No FCS"
2371         uint8_t update = channel->fcs_option || use_fcs;
2372         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
2373         channel->fcs_option = update;
2374 #endif
2375 }
2376 
2377 // @pre command len is valid, see check in l2cap_signaling_handler_channel
2378 static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
2379     log_info("l2cap_signaling_handle_configure_response");
2380 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2381     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2382     uint16_t pos     = 10;
2383     while (pos < end_pos){
2384         uint8_t option_hint = command[pos] >> 7;
2385         uint8_t option_type = command[pos] & 0x7f;
2386         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
2387         pos++;
2388         uint8_t length = command[pos++];
2389 
2390         // Retransmission and Flow Control Option
2391         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2392             switch (channel->mode){
2393                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2394                     if (channel->ertm_mandatory){
2395                         // ??
2396                     } else {
2397                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
2398                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2399                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2400                         }
2401                     }
2402                     break;
2403                 case L2CAP_CHANNEL_MODE_BASIC:
2404                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2405                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
2406                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2407                     }
2408                     break;
2409                 default:
2410                     break;
2411             }
2412         }
2413 
2414         // check for unknown options
2415         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
2416             log_info("l2cap cid %u, unknown options", channel->local_cid);
2417             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
2418         }
2419 
2420         pos += length;
2421     }
2422 #else
2423     UNUSED(channel);  // ok: no code
2424     UNUSED(result);   // ok: no code
2425     UNUSED(command);  // ok: no code
2426 #endif
2427 }
2428 
2429 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
2430     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
2431     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
2432     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
2433     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
2434     if (channel->state == L2CAP_STATE_OPEN) return 0;
2435     return 1;
2436 }
2437 
2438 
2439 // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
2440 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
2441 
2442     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2443     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2444     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2445     uint16_t result = 0;
2446 
2447     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
2448 
2449     // handle DISCONNECT REQUESTS seperately
2450     if (code == DISCONNECTION_REQUEST){
2451         switch (channel->state){
2452             case L2CAP_STATE_CONFIG:
2453             case L2CAP_STATE_OPEN:
2454             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2455             case L2CAP_STATE_WAIT_DISCONNECT:
2456                 l2cap_handle_disconnect_request(channel, identifier);
2457                 break;
2458 
2459             default:
2460                 // ignore in other states
2461                 break;
2462         }
2463         return;
2464     }
2465 
2466     // @STATEMACHINE(l2cap)
2467     switch (channel->state) {
2468 
2469         case L2CAP_STATE_WAIT_CONNECT_RSP:
2470             switch (code){
2471                 case CONNECTION_RESPONSE:
2472                     if (cmd_len < 8){
2473                         // command imcomplete
2474                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2475                         break;
2476                     }
2477                     l2cap_stop_rtx(channel);
2478                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2479                     switch (result) {
2480                         case 0:
2481                             // successful connection
2482                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2483                             channel->state = L2CAP_STATE_CONFIG;
2484                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2485                             break;
2486                         case 1:
2487                             // connection pending. get some coffee, but start the ERTX
2488                             l2cap_start_ertx(channel);
2489                             break;
2490                         default:
2491                             // channel closed
2492                             channel->state = L2CAP_STATE_CLOSED;
2493                             // map l2cap connection response result to BTstack status enumeration
2494                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
2495 
2496                             // drop link key if security block
2497                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
2498                                 gap_drop_link_key_for_bd_addr(channel->address);
2499                             }
2500 
2501                             // discard channel
2502                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2503                             btstack_memory_l2cap_channel_free(channel);
2504                             break;
2505                     }
2506                     break;
2507 
2508                 default:
2509                     //@TODO: implement other signaling packets
2510                     break;
2511             }
2512             break;
2513 
2514         case L2CAP_STATE_CONFIG:
2515             switch (code) {
2516                 case CONFIGURE_REQUEST:
2517                     if (cmd_len < 4){
2518                         // command incomplete
2519                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2520                         break;
2521                     }
2522                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
2523                     l2cap_signaling_handle_configure_request(channel, command);
2524                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
2525                         // only done if continuation not set
2526                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
2527                     }
2528                     break;
2529                 case CONFIGURE_RESPONSE:
2530                     if (cmd_len < 6){
2531                         // command incomplete
2532                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2533                         break;
2534                     }
2535                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2536                     l2cap_stop_rtx(channel);
2537                     l2cap_signaling_handle_configure_response(channel, result, command);
2538                     switch (result){
2539                         case 0: // success
2540                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
2541                             break;
2542                         case 4: // pending
2543                             l2cap_start_ertx(channel);
2544                             break;
2545                         default:
2546 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2547                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
2548                                 // remote does not offer ertm but it's required
2549                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2550                                 break;
2551                             }
2552 #endif
2553                             // retry on negative result
2554                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2555                             break;
2556                     }
2557                     break;
2558                 default:
2559                     break;
2560             }
2561             if (l2cap_channel_ready_for_open(channel)){
2562                 // for open:
2563                 channel->state = L2CAP_STATE_OPEN;
2564                 l2cap_emit_channel_opened(channel, 0);
2565             }
2566             break;
2567 
2568         case L2CAP_STATE_WAIT_DISCONNECT:
2569             switch (code) {
2570                 case DISCONNECTION_RESPONSE:
2571                     l2cap_finialize_channel_close(channel);
2572                     break;
2573                 default:
2574                     //@TODO: implement other signaling packets
2575                     break;
2576             }
2577             break;
2578 
2579         case L2CAP_STATE_CLOSED:
2580             // @TODO handle incoming requests
2581             break;
2582 
2583         case L2CAP_STATE_OPEN:
2584             //@TODO: implement other signaling packets, e.g. re-configure
2585             break;
2586         default:
2587             break;
2588     }
2589     // log_info("new state %u", channel->state);
2590 }
2591 
2592 
2593 // @pre command len is valid, see check in l2cap_acl_classic_handler
2594 static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
2595 
2596     btstack_linked_list_iterator_t it;
2597 
2598     // get code, signalind identifier and command len
2599     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2600     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2601     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2602 
2603     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
2604     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_RESPONSE){
2605         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2606         return;
2607     }
2608 
2609     // general commands without an assigned channel
2610     switch(code) {
2611 
2612         case CONNECTION_REQUEST:
2613             if (cmd_len == 4){
2614                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2615                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
2616                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
2617             } else {
2618                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2619             }
2620             return;
2621 
2622         case ECHO_REQUEST:
2623             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
2624             return;
2625 
2626         case INFORMATION_REQUEST:
2627             if (cmd_len == 2) {
2628                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2629                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
2630             } else {
2631                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2632             }
2633             return;
2634 
2635 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2636         case INFORMATION_RESPONSE: {
2637             hci_connection_t * connection = hci_connection_for_handle(handle);
2638             if (!connection) return;
2639             if (cmd_len >= 4) {
2640                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2641                 uint16_t result =  little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
2642                 if (result != 0) return;
2643                 if (info_type != L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) return;
2644                 if (cmd_len >= 6) {
2645                     connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
2646                     connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2647                     log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
2648                     // trigger connection request
2649                     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2650                     while (btstack_linked_list_iterator_has_next(&it)){
2651                         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2652                         if (channel->con_handle != handle) continue;
2653                         // bail if ERTM was requested but is not supported
2654                         if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2655                             if (channel->ertm_mandatory){
2656                                 // channel closed
2657                                 channel->state = L2CAP_STATE_CLOSED;
2658                                 // map l2cap connection response result to BTstack status enumeration
2659                                 l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
2660                                 // discard channel
2661                                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2662                                 btstack_memory_l2cap_channel_free(channel);
2663                                 continue;
2664                             } else {
2665                                 // fallback to Basic mode
2666                                 channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2667                             }
2668                         }
2669                         // start connecting
2670                         if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
2671                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
2672                         }
2673                         // respond to connection request
2674                         if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
2675                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2676                             l2cap_emit_incoming_connection(channel);
2677                         }
2678                     }
2679                     return; // cmd len valid
2680                 }
2681             }
2682             l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2683             return;
2684         }
2685 #endif
2686 
2687         default:
2688             break;
2689     }
2690 
2691     // Get potential destination CID
2692     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2693 
2694     // Find channel for this sig_id and connection handle
2695     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2696     while (btstack_linked_list_iterator_has_next(&it)){
2697         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2698         if (channel->con_handle != handle) continue;
2699         if (code & 1) {
2700             // match odd commands (responses) by previous signaling identifier
2701             if (channel->local_sig_id == sig_id) {
2702                 l2cap_signaling_handler_channel(channel, command);
2703                 break;
2704             }
2705         } else {
2706             // match even commands (requests) by local channel id
2707             if (channel->local_cid == dest_cid) {
2708                 l2cap_signaling_handler_channel(channel, command);
2709                 break;
2710             }
2711         }
2712     }
2713 }
2714 #endif
2715 
2716 #ifdef ENABLE_BLE
2717 
2718 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
2719     uint8_t event[6];
2720     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
2721     event[1] = 4;
2722     little_endian_store_16(event, 2, con_handle);
2723     little_endian_store_16(event, 4, result);
2724     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2725     if (!l2cap_event_packet_handler) return;
2726     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
2727 }
2728 
2729 // @returns valid
2730 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
2731     hci_connection_t * connection;
2732     uint16_t result;
2733     uint8_t  event[10];
2734 
2735 #ifdef ENABLE_LE_DATA_CHANNELS
2736     btstack_linked_list_iterator_t it;
2737     l2cap_channel_t * channel;
2738     uint16_t local_cid;
2739     uint16_t le_psm;
2740     uint16_t new_credits;
2741     uint16_t credits_before;
2742     l2cap_service_t * service;
2743     uint16_t source_cid;
2744 #endif
2745 
2746     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2747     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2748     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
2749 
2750     switch (code){
2751 
2752         case CONNECTION_PARAMETER_UPDATE_REQUEST:
2753             // check size
2754             if (len < 8) return 0;
2755             connection = hci_connection_for_handle(handle);
2756             if (connection){
2757                 if (connection->role != HCI_ROLE_MASTER){
2758                     // reject command without notifying upper layer when not in master role
2759                     return 0;
2760                 }
2761                 int update_parameter = 1;
2762                 le_connection_parameter_range_t existing_range;
2763                 gap_get_connection_parameter_range(&existing_range);
2764                 uint16_t le_conn_interval_min   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2765                 uint16_t le_conn_interval_max   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
2766                 uint16_t le_conn_latency        = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2767                 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
2768 
2769                 if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
2770                 if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
2771 
2772                 if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
2773                 if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
2774 
2775                 if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
2776                 if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
2777 
2778                 if (update_parameter){
2779                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
2780                     connection->le_conn_interval_min = le_conn_interval_min;
2781                     connection->le_conn_interval_max = le_conn_interval_max;
2782                     connection->le_conn_latency = le_conn_latency;
2783                     connection->le_supervision_timeout = le_supervision_timeout;
2784                 } else {
2785                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
2786                 }
2787                 connection->le_con_param_update_identifier = sig_id;
2788             }
2789 
2790             if (!l2cap_event_packet_handler) break;
2791 
2792             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
2793             event[1] = 8;
2794             memcpy(&event[2], &command[4], 8);
2795             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2796             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
2797             break;
2798 
2799         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
2800             // check size
2801             if (len < 2) return 0;
2802             result = little_endian_read_16(command, 4);
2803             l2cap_emit_connection_parameter_update_response(handle, result);
2804             break;
2805 
2806 #ifdef ENABLE_LE_DATA_CHANNELS
2807 
2808         case COMMAND_REJECT:
2809             // Find channel for this sig_id and connection handle
2810             channel = NULL;
2811             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2812             while (btstack_linked_list_iterator_has_next(&it)){
2813                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2814                 if (a_channel->con_handle   != handle) continue;
2815                 if (a_channel->local_sig_id != sig_id) continue;
2816                 channel = a_channel;
2817                 break;
2818             }
2819             if (!channel) break;
2820 
2821             // if received while waiting for le connection response, assume legacy device
2822             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
2823                 channel->state = L2CAP_STATE_CLOSED;
2824                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
2825                 l2cap_emit_le_channel_opened(channel, 0x0002);
2826 
2827                 // discard channel
2828                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2829                 btstack_memory_l2cap_channel_free(channel);
2830                 break;
2831             }
2832             break;
2833 
2834         case LE_CREDIT_BASED_CONNECTION_REQUEST:
2835             // check size
2836             if (len < 10) return 0;
2837 
2838             // get hci connection, bail if not found (must not happen)
2839             connection = hci_connection_for_handle(handle);
2840             if (!connection) return 0;
2841 
2842             // check if service registered
2843             le_psm  = little_endian_read_16(command, 4);
2844             service = l2cap_le_get_service(le_psm);
2845             source_cid = little_endian_read_16(command, 6);
2846 
2847             if (service){
2848                 if (source_cid < 0x40){
2849                     // 0x0009 Connection refused - Invalid Source CID
2850                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
2851                     return 1;
2852                 }
2853 
2854                 // go through list of channels for this ACL connection and check if we get a match
2855                 btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2856                 while (btstack_linked_list_iterator_has_next(&it)){
2857                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2858                     if (a_channel->con_handle != handle) continue;
2859                     if (a_channel->remote_cid != source_cid) continue;
2860                     // 0x000a Connection refused - Source CID already allocated
2861                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
2862                     return 1;
2863                 }
2864 
2865                 // security: check encryption
2866                 if (service->required_security_level >= LEVEL_2){
2867                     if (gap_encryption_key_size(handle) == 0){
2868                         // 0x0008 Connection refused - insufficient encryption
2869                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
2870                         return 1;
2871                     }
2872                     // anything less than 16 byte key size is insufficient
2873                     if (gap_encryption_key_size(handle) < 16){
2874                         // 0x0007 Connection refused – insufficient encryption key size
2875                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
2876                         return 1;
2877                     }
2878                 }
2879 
2880                 // security: check authencation
2881                 if (service->required_security_level >= LEVEL_3){
2882                     if (!gap_authenticated(handle)){
2883                         // 0x0005 Connection refused – insufficient authentication
2884                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
2885                         return 1;
2886                     }
2887                 }
2888 
2889                 // security: check authorization
2890                 if (service->required_security_level >= LEVEL_4){
2891                     if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
2892                         // 0x0006 Connection refused – insufficient authorization
2893                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
2894                         return 1;
2895                     }
2896                 }
2897 
2898                 // allocate channel
2899                 channel = l2cap_create_channel_entry(service->packet_handler, connection->address,
2900                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
2901                 if (!channel){
2902                     // 0x0004 Connection refused – no resources available
2903                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2904                     return 1;
2905                 }
2906 
2907                 channel->con_handle = handle;
2908                 channel->remote_cid = source_cid;
2909                 channel->remote_sig_id = sig_id;
2910                 channel->remote_mtu = little_endian_read_16(command, 8);
2911                 channel->remote_mps = little_endian_read_16(command, 10);
2912                 channel->credits_outgoing = little_endian_read_16(command, 12);
2913 
2914                 // set initial state
2915                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2916                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
2917 
2918                 // add to connections list
2919                 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2920 
2921                 // post connection request event
2922                 l2cap_emit_le_incoming_connection(channel);
2923 
2924             } else {
2925                 // Connection refused – LE_PSM not supported
2926                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2927             }
2928             break;
2929 
2930         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
2931             // check size
2932             if (len < 10) return 0;
2933 
2934             // Find channel for this sig_id and connection handle
2935             channel = NULL;
2936             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2937             while (btstack_linked_list_iterator_has_next(&it)){
2938                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2939                 if (a_channel->con_handle   != handle) continue;
2940                 if (a_channel->local_sig_id != sig_id) continue;
2941                 channel = a_channel;
2942                 break;
2943             }
2944             if (!channel) break;
2945 
2946             // cid + 0
2947             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
2948             if (result){
2949                 channel->state = L2CAP_STATE_CLOSED;
2950                 // map l2cap connection response result to BTstack status enumeration
2951                 l2cap_emit_le_channel_opened(channel, result);
2952 
2953                 // discard channel
2954                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2955                 btstack_memory_l2cap_channel_free(channel);
2956                 break;
2957             }
2958 
2959             // success
2960             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
2961             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
2962             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
2963             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
2964             channel->state = L2CAP_STATE_OPEN;
2965             l2cap_emit_le_channel_opened(channel, result);
2966             break;
2967 
2968         case LE_FLOW_CONTROL_CREDIT:
2969             // check size
2970             if (len < 4) return 0;
2971 
2972             // find channel
2973             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
2974             channel = l2cap_le_get_channel_for_local_cid(local_cid);
2975             if (!channel) {
2976                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
2977                 break;
2978             }
2979             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
2980             credits_before = channel->credits_outgoing;
2981             channel->credits_outgoing += new_credits;
2982             // check for credit overrun
2983             if (credits_before > channel->credits_outgoing){
2984                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
2985                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2986                 break;
2987             }
2988             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
2989             break;
2990 
2991         case DISCONNECTION_REQUEST:
2992 
2993             // check size
2994             if (len < 4) return 0;
2995 
2996             // find channel
2997             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
2998             channel = l2cap_le_get_channel_for_local_cid(local_cid);
2999             if (!channel) {
3000                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
3001                 break;
3002             }
3003             channel->remote_sig_id = sig_id;
3004             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
3005             break;
3006 
3007 #endif
3008 
3009         case DISCONNECTION_RESPONSE:
3010             break;
3011 
3012         default:
3013             // command unknown -> reject command
3014             return 0;
3015     }
3016     return 1;
3017 }
3018 #endif
3019 
3020 static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3021 #ifdef ENABLE_CLASSIC
3022     l2cap_channel_t * l2cap_channel;
3023 
3024     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3025     switch (channel_id) {
3026 
3027         case L2CAP_CID_SIGNALING: {
3028             uint16_t command_offset = 8;
3029             while (command_offset < size) {
3030                 // assert signaling command is fully inside packet
3031                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3032                 uint32_t next_command_offset = ((uint32_t) command_offset) + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
3033                 if (next_command_offset > size){
3034                     log_error("l2cap signaling command len invalid -> drop");
3035                     break;
3036                 }
3037                 // handle signaling command
3038                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
3039                 // go to next command
3040                 command_offset = (uint16_t) next_command_offset;
3041             }
3042             break;
3043         }
3044         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
3045             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback) {
3046                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3047             }
3048             break;
3049 
3050         default:
3051             // Find channel for this channel_id and connection handle
3052             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
3053             if (l2cap_channel) {
3054 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3055                 if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3056 
3057                     int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
3058 
3059                     // assert control + FCS fields are inside
3060                     if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) break;
3061 
3062                     if (l2cap_channel->fcs_option){
3063                         // verify FCS (required if one side requested it)
3064                         uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
3065                         uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
3066                         if (fcs_calculated == fcs_packet){
3067                             log_info("Packet FCS 0x%04x verified", fcs_packet);
3068                         } else {
3069                             log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
3070                             // TODO: trigger retransmission or something like that
3071                             break;
3072                         }
3073                     }
3074 
3075                     // switch on packet type
3076                     uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3077                     uint8_t  req_seq = (control >> 8) & 0x3f;
3078                     int final = (control >> 7) & 0x01;
3079                     if (control & 1){
3080                         // S-Frame
3081                         int poll  = (control >> 4) & 0x01;
3082                         l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
3083                         log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
3084                         l2cap_ertm_tx_packet_state_t * tx_state;
3085                         switch (s){
3086                             case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
3087                                 log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
3088                                 l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3089                                 if (poll && final){
3090                                     // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
3091                                     log_error("P=F=1 in S-Frame");
3092                                     break;
3093                                 }
3094                                 if (poll){
3095                                     // check if we did request selective retransmission before <==> we have stored SDU segments
3096                                     int i;
3097                                     int num_stored_out_of_order_packets = 0;
3098                                     for (i=0;i<l2cap_channel->num_rx_buffers;i++){
3099                                         int index = l2cap_channel->rx_store_index + i;
3100                                         if (index >= l2cap_channel->num_rx_buffers){
3101                                             index -= l2cap_channel->num_rx_buffers;
3102                                         }
3103                                         l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3104                                         if (!rx_state->valid) continue;
3105                                         num_stored_out_of_order_packets++;
3106                                     }
3107                                     if (num_stored_out_of_order_packets){
3108                                         l2cap_channel->send_supervisor_frame_selective_reject = 1;
3109                                     } else {
3110                                         l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
3111                                     }
3112                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
3113                                 }
3114                                 if (final){
3115                                     // Stop-MonitorTimer
3116                                     l2cap_ertm_stop_monitor_timer(l2cap_channel);
3117                                     // If UnackedFrames > 0 then Start-RetransTimer
3118                                     if (l2cap_channel->unacked_frames){
3119                                         l2cap_ertm_start_retransmission_timer(l2cap_channel);
3120                                     }
3121 
3122                                     // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3123                                     l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
3124                                 }
3125                                 break;
3126                             case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
3127                                 log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
3128                                 l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3129                                 // rsetart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
3130                                 l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
3131                                 break;
3132                             case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
3133                                 log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
3134                                 break;
3135                             case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
3136                                 log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
3137                                 if (poll){
3138                                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3139                                 }
3140                                 // find requested i-frame
3141                                 tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
3142                                 if (tx_state){
3143                                     log_info("Retransmission for tx_seq %u requested", req_seq);
3144                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
3145                                     tx_state->retransmission_requested = 1;
3146                                     l2cap_channel->srej_active = 1;
3147                                 }
3148                                 break;
3149                             default:
3150                                 break;
3151                         }
3152                         break;
3153                     } else {
3154                         // I-Frame
3155                         // get control
3156                         l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
3157                         uint8_t tx_seq = (control >> 1) & 0x3f;
3158                         log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
3159                         log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
3160                         log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
3161                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3162                         if (final){
3163                             // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3164                             l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
3165                         }
3166 
3167                         // get SDU
3168                         const uint8_t * sdu_data = &packet[COMPLETE_L2CAP_HEADER+2];
3169                         uint16_t        sdu_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
3170 
3171                         // assert SDU size is smaller or equal to our buffers
3172                         if (sdu_len > l2cap_channel->local_mps) break;
3173 
3174                         // check ordering
3175                         if (l2cap_channel->expected_tx_seq == tx_seq){
3176                             log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
3177                             l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3178                             l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3179 
3180                             // process SDU
3181                             l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, sdu_data, sdu_len);
3182 
3183                             // process stored segments
3184                             while (1){
3185                                 int index = l2cap_channel->rx_store_index;
3186                                 l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3187                                 if (!rx_state->valid) break;
3188 
3189                                 log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
3190                                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3191                                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3192 
3193                                 rx_state->valid = 0;
3194                                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
3195 
3196                                 // update rx store index
3197                                 index++;
3198                                 if (index >= l2cap_channel->num_rx_buffers){
3199                                     index = 0;
3200                                 }
3201                                 l2cap_channel->rx_store_index = index;
3202                             }
3203 
3204                             //
3205                             l2cap_channel->send_supervisor_frame_receiver_ready = 1;
3206 
3207                         } else {
3208                             int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
3209                             if (delta < 2){
3210                                 // store segment
3211                                 l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, sdu_data, sdu_len);
3212 
3213                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
3214                                 l2cap_channel->send_supervisor_frame_selective_reject = 1;
3215                             } else {
3216                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
3217                                 l2cap_channel->send_supervisor_frame_reject = 1;
3218                             }
3219                         }
3220                     }
3221                     break;
3222                 }
3223 #endif
3224                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3225             }
3226             break;
3227     }
3228 #else
3229     UNUSED(handle); // ok: no code
3230     UNUSED(packet); // ok: no code
3231     UNUSED(size);   // ok: no code
3232 #endif
3233 }
3234 
3235 static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3236 #ifdef ENABLE_BLE
3237 
3238 #ifdef ENABLE_LE_DATA_CHANNELS
3239     l2cap_channel_t * l2cap_channel;
3240 #endif
3241     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3242     switch (channel_id) {
3243 
3244         case L2CAP_CID_SIGNALING_LE: {
3245             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
3246             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
3247             if (COMPLETE_L2CAP_HEADER + 4 + len > size) break;
3248             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
3249             if (!valid){
3250                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3251             }
3252             break;
3253         }
3254 
3255         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
3256             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback) {
3257                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3258             }
3259             break;
3260 
3261         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
3262             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback) {
3263                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3264             }
3265             break;
3266 
3267         default:
3268 
3269 #ifdef ENABLE_LE_DATA_CHANNELS
3270             l2cap_channel = l2cap_le_get_channel_for_local_cid(channel_id);
3271             if (l2cap_channel) {
3272                 // credit counting
3273                 if (l2cap_channel->credits_incoming == 0){
3274                     log_error("LE Data Channel packet received but no incoming credits");
3275                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3276                     break;
3277                 }
3278                 l2cap_channel->credits_incoming--;
3279 
3280                 // automatic credits
3281                 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){
3282                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
3283                 }
3284 
3285                 // first fragment
3286                 uint16_t pos = 0;
3287                 if (!l2cap_channel->receive_sdu_len){
3288                     uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3289                     if(sdu_len > l2cap_channel->local_mtu) break;   // SDU would be larger than our buffer
3290                     l2cap_channel->receive_sdu_len = sdu_len;
3291                     l2cap_channel->receive_sdu_pos = 0;
3292                     pos  += 2;
3293                     size -= 2;
3294                 }
3295                 uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
3296                 uint16_t remaining_space = l2cap_channel->local_mtu - l2cap_channel->receive_sdu_pos;
3297                 if (fragment_size > remaining_space) break;         // SDU would cause buffer overrun
3298                 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], fragment_size);
3299                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
3300                 // done?
3301                 log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
3302                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
3303                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
3304                     l2cap_channel->receive_sdu_len = 0;
3305                 }
3306             } else {
3307                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
3308             }
3309 #endif
3310             break;
3311     }
3312 #else
3313     UNUSED(handle); // ok: no code
3314     UNUSED(packet); // ok: no code
3315     UNUSED(size);   // ok: no code
3316 #endif
3317 }
3318 
3319 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
3320     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
3321     UNUSED(channel);        // ok: there is no channel
3322 
3323     // Assert full L2CAP header present
3324     if (size < COMPLETE_L2CAP_HEADER) return;
3325 
3326     // Dispatch to Classic or LE handler
3327     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
3328     hci_connection_t *conn = hci_connection_for_handle(handle);
3329     if (!conn) return;
3330     if (conn->address_type == BD_ADDR_TYPE_CLASSIC){
3331         l2cap_acl_classic_handler(handle, packet, size);
3332     } else {
3333         l2cap_acl_le_handler(handle, packet, size);
3334     }
3335 
3336     l2cap_run();
3337 }
3338 
3339 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
3340 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
3341     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
3342     if (index < 0) return;
3343     fixed_channels[index].callback = the_packet_handler;
3344 }
3345 
3346 #ifdef ENABLE_CLASSIC
3347 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
3348 void l2cap_finialize_channel_close(l2cap_channel_t * channel){
3349     channel->state = L2CAP_STATE_CLOSED;
3350     l2cap_emit_channel_closed(channel);
3351     // discard channel
3352     l2cap_stop_rtx(channel);
3353     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3354     btstack_memory_l2cap_channel_free(channel);
3355 }
3356 
3357 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3358     btstack_linked_list_iterator_t it;
3359     btstack_linked_list_iterator_init(&it, services);
3360     while (btstack_linked_list_iterator_has_next(&it)){
3361         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
3362         if ( service->psm == psm){
3363             return service;
3364         };
3365     }
3366     return NULL;
3367 }
3368 
3369 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
3370     return l2cap_get_service_internal(&l2cap_services, psm);
3371 }
3372 
3373 
3374 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
3375 
3376     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
3377 
3378     // check for alread registered psm
3379     l2cap_service_t *service = l2cap_get_service(psm);
3380     if (service) {
3381         log_error("l2cap_register_service: PSM %u already registered", psm);
3382         return L2CAP_SERVICE_ALREADY_REGISTERED;
3383     }
3384 
3385     // alloc structure
3386     service = btstack_memory_l2cap_service_get();
3387     if (!service) {
3388         log_error("l2cap_register_service: no memory for l2cap_service_t");
3389         return BTSTACK_MEMORY_ALLOC_FAILED;
3390     }
3391 
3392     // fill in
3393     service->psm = psm;
3394     service->mtu = mtu;
3395     service->packet_handler = service_packet_handler;
3396     service->required_security_level = security_level;
3397 
3398     // add to services list
3399     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
3400 
3401     // enable page scan
3402     gap_connectable_control(1);
3403 
3404     return 0;
3405 }
3406 
3407 uint8_t l2cap_unregister_service(uint16_t psm){
3408 
3409     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
3410 
3411     l2cap_service_t *service = l2cap_get_service(psm);
3412     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3413     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
3414     btstack_memory_l2cap_service_free(service);
3415 
3416     // disable page scan when no services registered
3417     if (btstack_linked_list_empty(&l2cap_services)) {
3418         gap_connectable_control(0);
3419     }
3420     return 0;
3421 }
3422 #endif
3423 
3424 
3425 #ifdef ENABLE_LE_DATA_CHANNELS
3426 
3427 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
3428     if (!channel->waiting_for_can_send_now) return;
3429     if (channel->send_sdu_buffer) return;
3430     channel->waiting_for_can_send_now = 0;
3431     log_debug("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
3432     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
3433 }
3434 
3435 // 1BH2222
3436 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
3437     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",
3438              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
3439     uint8_t event[19];
3440     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
3441     event[1] = sizeof(event) - 2;
3442     event[2] = channel->address_type;
3443     reverse_bd_addr(channel->address, &event[3]);
3444     little_endian_store_16(event,  9, channel->con_handle);
3445     little_endian_store_16(event, 11, channel->psm);
3446     little_endian_store_16(event, 13, channel->local_cid);
3447     little_endian_store_16(event, 15, channel->remote_cid);
3448     little_endian_store_16(event, 17, channel->remote_mtu);
3449     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3450     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3451 }
3452 // 11BH22222
3453 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
3454     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",
3455              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
3456              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
3457     uint8_t event[23];
3458     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
3459     event[1] = sizeof(event) - 2;
3460     event[2] = status;
3461     event[3] = channel->address_type;
3462     reverse_bd_addr(channel->address, &event[4]);
3463     little_endian_store_16(event, 10, channel->con_handle);
3464     event[12] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
3465     little_endian_store_16(event, 13, channel->psm);
3466     little_endian_store_16(event, 15, channel->local_cid);
3467     little_endian_store_16(event, 17, channel->remote_cid);
3468     little_endian_store_16(event, 19, channel->local_mtu);
3469     little_endian_store_16(event, 21, channel->remote_mtu);
3470     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3471     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3472 }
3473 
3474 static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid){
3475     btstack_linked_list_iterator_t it;
3476     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
3477     while (btstack_linked_list_iterator_has_next(&it)){
3478         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3479         if ( channel->local_cid == local_cid) {
3480             return channel;
3481         }
3482     }
3483     return NULL;
3484 }
3485 
3486 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
3487 void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
3488     channel->state = L2CAP_STATE_CLOSED;
3489     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
3490     // discard channel
3491     btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
3492     btstack_memory_l2cap_channel_free(channel);
3493 }
3494 
3495 static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
3496     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
3497 }
3498 
3499 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
3500 
3501     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
3502 
3503     // check for alread registered psm
3504     l2cap_service_t *service = l2cap_le_get_service(psm);
3505     if (service) {
3506         return L2CAP_SERVICE_ALREADY_REGISTERED;
3507     }
3508 
3509     // alloc structure
3510     service = btstack_memory_l2cap_service_get();
3511     if (!service) {
3512         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
3513         return BTSTACK_MEMORY_ALLOC_FAILED;
3514     }
3515 
3516     // fill in
3517     service->psm = psm;
3518     service->mtu = 0;
3519     service->packet_handler = packet_handler;
3520     service->required_security_level = security_level;
3521 
3522     // add to services list
3523     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
3524 
3525     // done
3526     return 0;
3527 }
3528 
3529 uint8_t l2cap_le_unregister_service(uint16_t psm) {
3530     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
3531     l2cap_service_t *service = l2cap_le_get_service(psm);
3532     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3533 
3534     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
3535     btstack_memory_l2cap_service_free(service);
3536     return 0;
3537 }
3538 
3539 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
3540     // get channel
3541     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3542     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3543 
3544     // validate state
3545     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3546         return ERROR_CODE_COMMAND_DISALLOWED;
3547     }
3548 
3549     // set state accept connection
3550     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
3551     channel->receive_sdu_buffer = receive_sdu_buffer;
3552     channel->local_mtu = mtu;
3553     channel->new_credits_incoming = initial_credits;
3554     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
3555 
3556     // test
3557     // channel->new_credits_incoming = 1;
3558 
3559     // go
3560     l2cap_run();
3561     return 0;
3562 }
3563 
3564 /**
3565  * @brief Deny incoming LE Data Channel connection due to resource constraints
3566  * @param local_cid             L2CAP LE Data Channel Identifier
3567  */
3568 
3569 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
3570     // get channel
3571     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3572     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3573 
3574     // validate state
3575     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3576         return ERROR_CODE_COMMAND_DISALLOWED;
3577     }
3578 
3579     // set state decline connection
3580     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
3581     channel->reason = 0x04; // no resources available
3582     l2cap_run();
3583     return 0;
3584 }
3585 
3586 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
3587     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
3588     uint16_t * out_local_cid) {
3589 
3590     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
3591 
3592 
3593     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3594     if (!connection) {
3595         log_error("no hci_connection for handle 0x%04x", con_handle);
3596         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3597     }
3598 
3599     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, connection->address, connection->address_type, psm, mtu, security_level);
3600     if (!channel) {
3601         return BTSTACK_MEMORY_ALLOC_FAILED;
3602     }
3603     log_info("l2cap_le_create_channel %p", channel);
3604 
3605     // store local_cid
3606     if (out_local_cid){
3607        *out_local_cid = channel->local_cid;
3608     }
3609 
3610     // provide buffer
3611     channel->con_handle = con_handle;
3612     channel->receive_sdu_buffer = receive_sdu_buffer;
3613     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
3614     channel->new_credits_incoming = initial_credits;
3615     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
3616 
3617     // add to connections list
3618     btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
3619 
3620     // go
3621     l2cap_run();
3622     return 0;
3623 }
3624 
3625 /**
3626  * @brief Provide credtis for LE Data Channel
3627  * @param local_cid             L2CAP LE Data Channel Identifier
3628  * @param credits               Number additional credits for peer
3629  */
3630 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
3631 
3632     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3633     if (!channel) {
3634         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
3635         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3636     }
3637 
3638     // check state
3639     if (channel->state != L2CAP_STATE_OPEN){
3640         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
3641     }
3642 
3643     // assert incoming credits + credits <= 0xffff
3644     uint32_t total_credits = channel->credits_incoming;
3645     total_credits += channel->new_credits_incoming;
3646     total_credits += credits;
3647     if (total_credits > 0xffff){
3648         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
3649             channel->new_credits_incoming, credits);
3650     }
3651 
3652     // set credits_granted
3653     channel->new_credits_incoming += credits;
3654 
3655     // go
3656     l2cap_run();
3657     return 0;
3658 }
3659 
3660 /**
3661  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
3662  * @param local_cid             L2CAP LE Data Channel Identifier
3663  */
3664 int l2cap_le_can_send_now(uint16_t local_cid){
3665     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3666     if (!channel) {
3667         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
3668         return 0;
3669     }
3670 
3671     // check state
3672     if (channel->state != L2CAP_STATE_OPEN) return 0;
3673 
3674     // check queue
3675     if (channel->send_sdu_buffer) return 0;
3676 
3677     // fine, go ahead
3678     return 1;
3679 }
3680 
3681 /**
3682  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
3683  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
3684  *       so packet handler should be ready to handle it
3685  * @param local_cid             L2CAP LE Data Channel Identifier
3686  */
3687 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
3688     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3689     if (!channel) {
3690         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
3691         return 0;
3692     }
3693     channel->waiting_for_can_send_now = 1;
3694     l2cap_le_notify_channel_can_send(channel);
3695     return 0;
3696 }
3697 
3698 /**
3699  * @brief Send data via LE Data Channel
3700  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
3701  * @param local_cid             L2CAP LE Data Channel Identifier
3702  * @param data                  data to send
3703  * @param size                  data size
3704  */
3705 uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
3706 
3707     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3708     if (!channel) {
3709         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
3710         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3711     }
3712 
3713     if (len > channel->remote_mtu){
3714         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
3715         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
3716     }
3717 
3718     if (channel->send_sdu_buffer){
3719         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
3720         return BTSTACK_ACL_BUFFERS_FULL;
3721     }
3722 
3723     channel->send_sdu_buffer = data;
3724     channel->send_sdu_len    = len;
3725     channel->send_sdu_pos    = 0;
3726 
3727     l2cap_run();
3728     return 0;
3729 }
3730 
3731 /**
3732  * @brief Disconnect from LE Data Channel
3733  * @param local_cid             L2CAP LE Data Channel Identifier
3734  */
3735 uint8_t l2cap_le_disconnect(uint16_t local_cid)
3736 {
3737     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3738     if (!channel) {
3739         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
3740         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3741     }
3742 
3743     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3744     l2cap_run();
3745     return 0;
3746 }
3747 
3748 #endif
3749