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