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