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