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