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