xref: /btstack/src/l2cap.c (revision 2bea1b8d8ad877bc7e2bfb7a6ab5eb3c76ba1c60)
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             if (channel->remote_mtu > l2cap_max_mtu()){
1910                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
1911                 channel->remote_mtu = l2cap_max_mtu();
1912             }
1913             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1914         }
1915         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
1916         if (option_type == 2 && length == 2){
1917             channel->flush_timeout = little_endian_read_16(command, pos);
1918         }
1919 
1920 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1921         // Retransmission and Flow Control Option
1922         if (option_type == 4 && length == 9){
1923             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
1924             switch(channel->mode){
1925                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
1926                     // Store remote config
1927                     channel->remote_tx_window_size = command[pos+1];
1928                     channel->remote_max_transmit   = command[pos+2];
1929                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
1930                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
1931                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u",
1932                         channel->remote_tx_window_size,
1933                         channel->remote_max_transmit,
1934                         channel->remote_retransmission_timeout_ms,
1935                         channel->remote_monitor_timeout_ms);
1936                     // we store remote MPS in remote_mtu, might need to get re-evaluated
1937                     channel->remote_mtu = little_endian_read_16(command, pos + 7);
1938                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
1939                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1940                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1941                     } else {
1942                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1943                     }
1944                     break;
1945                 case L2CAP_CHANNEL_MODE_BASIC:
1946                     switch (mode){
1947                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
1948                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
1949                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
1950                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1951                             }
1952                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
1953                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1954                             break;
1955                         default: // case L2CAP_CHANNEL_MODE_BASIC:
1956                             // TODO store and evaluate configuration
1957                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1958                             break;
1959                     }
1960                     break;
1961                 default:
1962                     break;
1963             }
1964         }
1965 #endif
1966         // check for unknown options
1967         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
1968             log_info("l2cap cid %u, unknown options", channel->local_cid);
1969             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
1970         }
1971         pos += length;
1972     }
1973 }
1974 
1975 static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
1976     log_info("l2cap_signaling_handle_configure_response");
1977 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1978     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1979     uint16_t pos     = 10;
1980     while (pos < end_pos){
1981         uint8_t option_hint = command[pos] >> 7;
1982         uint8_t option_type = command[pos] & 0x7f;
1983         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
1984         pos++;
1985         uint8_t length = command[pos++];
1986 
1987         // Retransmission and Flow Control Option
1988         if (option_type == 4 && length == 9){
1989             switch (channel->mode){
1990                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
1991                     if (channel->ertm_mandatory){
1992                         // ??
1993                     } else {
1994                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
1995                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
1996                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
1997                         }
1998                     }
1999                     break;
2000                 case L2CAP_CHANNEL_MODE_BASIC:
2001                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2002                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
2003                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2004                     }
2005                     break;
2006                 default:
2007                     break;
2008             }
2009         }
2010 
2011         // check for unknown options
2012         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
2013             log_info("l2cap cid %u, unknown options", channel->local_cid);
2014             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
2015         }
2016 
2017         pos += length;
2018     }
2019 #endif
2020 }
2021 
2022 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
2023     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
2024     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
2025     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
2026     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
2027     if (channel->state == L2CAP_STATE_OPEN) return 0;
2028     return 1;
2029 }
2030 
2031 
2032 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
2033 
2034     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2035     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2036     uint16_t result = 0;
2037 
2038     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
2039 
2040     // handle DISCONNECT REQUESTS seperately
2041     if (code == DISCONNECTION_REQUEST){
2042         switch (channel->state){
2043             case L2CAP_STATE_CONFIG:
2044             case L2CAP_STATE_OPEN:
2045             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2046             case L2CAP_STATE_WAIT_DISCONNECT:
2047                 l2cap_handle_disconnect_request(channel, identifier);
2048                 break;
2049 
2050             default:
2051                 // ignore in other states
2052                 break;
2053         }
2054         return;
2055     }
2056 
2057     // @STATEMACHINE(l2cap)
2058     switch (channel->state) {
2059 
2060         case L2CAP_STATE_WAIT_CONNECT_RSP:
2061             switch (code){
2062                 case CONNECTION_RESPONSE:
2063                     l2cap_stop_rtx(channel);
2064                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2065                     switch (result) {
2066                         case 0:
2067                             // successful connection
2068                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2069                             channel->state = L2CAP_STATE_CONFIG;
2070                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2071                             break;
2072                         case 1:
2073                             // connection pending. get some coffee, but start the ERTX
2074                             l2cap_start_ertx(channel);
2075                             break;
2076                         default:
2077                             // channel closed
2078                             channel->state = L2CAP_STATE_CLOSED;
2079                             // map l2cap connection response result to BTstack status enumeration
2080                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
2081 
2082                             // drop link key if security block
2083                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
2084                                 gap_drop_link_key_for_bd_addr(channel->address);
2085                             }
2086 
2087                             // discard channel
2088                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2089                             btstack_memory_l2cap_channel_free(channel);
2090                             break;
2091                     }
2092                     break;
2093 
2094                 default:
2095                     //@TODO: implement other signaling packets
2096                     break;
2097             }
2098             break;
2099 
2100         case L2CAP_STATE_CONFIG:
2101             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2102             switch (code) {
2103                 case CONFIGURE_REQUEST:
2104                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
2105                     l2cap_signaling_handle_configure_request(channel, command);
2106                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
2107                         // only done if continuation not set
2108                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
2109                     }
2110                     break;
2111                 case CONFIGURE_RESPONSE:
2112                     l2cap_stop_rtx(channel);
2113                     l2cap_signaling_handle_configure_response(channel, result, command);
2114                     switch (result){
2115                         case 0: // success
2116                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
2117                             break;
2118                         case 4: // pending
2119                             l2cap_start_ertx(channel);
2120                             break;
2121                         default:
2122 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2123                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
2124                                 // remote does not offer ertm but it's required
2125                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2126                                 break;
2127                             }
2128 #endif
2129                             // retry on negative result
2130                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2131                             break;
2132                     }
2133                     break;
2134                 default:
2135                     break;
2136             }
2137             if (l2cap_channel_ready_for_open(channel)){
2138                 // for open:
2139                 channel->state = L2CAP_STATE_OPEN;
2140                 l2cap_emit_channel_opened(channel, 0);
2141             }
2142             break;
2143 
2144         case L2CAP_STATE_WAIT_DISCONNECT:
2145             switch (code) {
2146                 case DISCONNECTION_RESPONSE:
2147                     l2cap_finialize_channel_close(channel);
2148                     break;
2149                 default:
2150                     //@TODO: implement other signaling packets
2151                     break;
2152             }
2153             break;
2154 
2155         case L2CAP_STATE_CLOSED:
2156             // @TODO handle incoming requests
2157             break;
2158 
2159         case L2CAP_STATE_OPEN:
2160             //@TODO: implement other signaling packets, e.g. re-configure
2161             break;
2162         default:
2163             break;
2164     }
2165     // log_info("new state %u", channel->state);
2166 }
2167 
2168 
2169 static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
2170 
2171     btstack_linked_list_iterator_t it;
2172 
2173     // get code, signalind identifier and command len
2174     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2175     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2176 
2177     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
2178     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_RESPONSE){
2179         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2180         return;
2181     }
2182 
2183     // general commands without an assigned channel
2184     switch(code) {
2185 
2186         case CONNECTION_REQUEST: {
2187             uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2188             uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
2189             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
2190             return;
2191         }
2192 
2193         case ECHO_REQUEST:
2194             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
2195             return;
2196 
2197         case INFORMATION_REQUEST: {
2198             uint16_t infoType = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2199             l2cap_register_signaling_response(handle, code, sig_id, 0, infoType);
2200             return;
2201         }
2202 
2203 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2204         case INFORMATION_RESPONSE: {
2205             hci_connection_t * connection = hci_connection_for_handle(handle);
2206             if (!connection) return;
2207             uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2208             uint16_t result =  little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
2209             if (result != 0) return;
2210             if (info_type != 0x02) return;
2211             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
2212             connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2213             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
2214             // trigger connection request
2215             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2216             while (btstack_linked_list_iterator_has_next(&it)){
2217                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2218                 if (channel->con_handle != handle) continue;
2219                 // bail if ERTM was requested but is not supported
2220                 if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2221                     if (channel->ertm_mandatory){
2222                         // channel closed
2223                         channel->state = L2CAP_STATE_CLOSED;
2224                         // map l2cap connection response result to BTstack status enumeration
2225                         l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTD);
2226                         // discard channel
2227                         btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2228                         btstack_memory_l2cap_channel_free(channel);
2229                         continue;
2230                     } else {
2231                         // fallback to Basic mode
2232                         channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2233                     }
2234                 }
2235                 // start connecting
2236                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
2237                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
2238                 }
2239                 // respond to connection request
2240                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
2241                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2242                     l2cap_emit_incoming_connection(channel);
2243                 }
2244             }
2245             return;
2246         }
2247 #endif
2248 
2249         default:
2250             break;
2251     }
2252 
2253 
2254     // Get potential destination CID
2255     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2256 
2257     // Find channel for this sig_id and connection handle
2258     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2259     while (btstack_linked_list_iterator_has_next(&it)){
2260         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2261         if (channel->con_handle != handle) continue;
2262         if (code & 1) {
2263             // match odd commands (responses) by previous signaling identifier
2264             if (channel->local_sig_id == sig_id) {
2265                 l2cap_signaling_handler_channel(channel, command);
2266                 break;
2267             }
2268         } else {
2269             // match even commands (requests) by local channel id
2270             if (channel->local_cid == dest_cid) {
2271                 l2cap_signaling_handler_channel(channel, command);
2272                 break;
2273             }
2274         }
2275     }
2276 }
2277 #endif
2278 
2279 #ifdef ENABLE_BLE
2280 
2281 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
2282     uint8_t event[6];
2283     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
2284     event[1] = 4;
2285     little_endian_store_16(event, 2, con_handle);
2286     little_endian_store_16(event, 4, result);
2287     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2288     if (!l2cap_event_packet_handler) return;
2289     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
2290 }
2291 
2292 // @returns valid
2293 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
2294     hci_connection_t * connection;
2295     uint16_t result;
2296     uint8_t  event[10];
2297 
2298 #ifdef ENABLE_LE_DATA_CHANNELS
2299     btstack_linked_list_iterator_t it;
2300     l2cap_channel_t * channel;
2301     uint16_t local_cid;
2302     uint16_t le_psm;
2303     uint16_t new_credits;
2304     uint16_t credits_before;
2305     l2cap_service_t * service;
2306     uint16_t source_cid;
2307 #endif
2308 
2309     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2310     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u", code, sig_id);
2311 
2312     switch (code){
2313 
2314         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
2315             result = little_endian_read_16(command, 4);
2316             l2cap_emit_connection_parameter_update_response(handle, result);
2317             break;
2318 
2319         case CONNECTION_PARAMETER_UPDATE_REQUEST:
2320             connection = hci_connection_for_handle(handle);
2321             if (connection){
2322                 if (connection->role != HCI_ROLE_MASTER){
2323                     // reject command without notifying upper layer when not in master role
2324                     return 0;
2325                 }
2326                 int update_parameter = 1;
2327                 le_connection_parameter_range_t existing_range;
2328                 gap_get_connection_parameter_range(&existing_range);
2329                 uint16_t le_conn_interval_min = little_endian_read_16(command,8);
2330                 uint16_t le_conn_interval_max = little_endian_read_16(command,10);
2331                 uint16_t le_conn_latency = little_endian_read_16(command,12);
2332                 uint16_t le_supervision_timeout = little_endian_read_16(command,14);
2333 
2334                 if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
2335                 if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
2336 
2337                 if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
2338                 if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
2339 
2340                 if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
2341                 if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
2342 
2343                 if (update_parameter){
2344                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
2345                     connection->le_conn_interval_min = le_conn_interval_min;
2346                     connection->le_conn_interval_max = le_conn_interval_max;
2347                     connection->le_conn_latency = le_conn_latency;
2348                     connection->le_supervision_timeout = le_supervision_timeout;
2349                 } else {
2350                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
2351                 }
2352                 connection->le_con_param_update_identifier = sig_id;
2353             }
2354 
2355             if (!l2cap_event_packet_handler) break;
2356 
2357             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
2358             event[1] = 8;
2359             memcpy(&event[2], &command[4], 8);
2360             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2361             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
2362             break;
2363 
2364 #ifdef ENABLE_LE_DATA_CHANNELS
2365 
2366         case COMMAND_REJECT:
2367             // Find channel for this sig_id and connection handle
2368             channel = NULL;
2369             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2370             while (btstack_linked_list_iterator_has_next(&it)){
2371                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2372                 if (a_channel->con_handle   != handle) continue;
2373                 if (a_channel->local_sig_id != sig_id) continue;
2374                 channel = a_channel;
2375                 break;
2376             }
2377             if (!channel) break;
2378 
2379             // if received while waiting for le connection response, assume legacy device
2380             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
2381                 channel->state = L2CAP_STATE_CLOSED;
2382                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
2383                 l2cap_emit_le_channel_opened(channel, 0x0002);
2384 
2385                 // discard channel
2386                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2387                 btstack_memory_l2cap_channel_free(channel);
2388                 break;
2389             }
2390             break;
2391 
2392         case LE_CREDIT_BASED_CONNECTION_REQUEST:
2393 
2394             // get hci connection, bail if not found (must not happen)
2395             connection = hci_connection_for_handle(handle);
2396             if (!connection) return 0;
2397 
2398             // check if service registered
2399             le_psm  = little_endian_read_16(command, 4);
2400             service = l2cap_le_get_service(le_psm);
2401             source_cid = little_endian_read_16(command, 6);
2402 
2403             if (service){
2404                 if (source_cid < 0x40){
2405                     // 0x0009 Connection refused - Invalid Source CID
2406                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
2407                     return 1;
2408                 }
2409 
2410                 // go through list of channels for this ACL connection and check if we get a match
2411                 btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2412                 while (btstack_linked_list_iterator_has_next(&it)){
2413                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2414                     if (a_channel->con_handle != handle) continue;
2415                     if (a_channel->remote_cid != source_cid) continue;
2416                     // 0x000a Connection refused - Source CID already allocated
2417                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
2418                     return 1;
2419                 }
2420 
2421                 // security: check encryption
2422                 if (service->required_security_level >= LEVEL_2){
2423                     if (sm_encryption_key_size(handle) == 0){
2424                         // 0x0008 Connection refused - insufficient encryption
2425                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
2426                         return 1;
2427                     }
2428                     // anything less than 16 byte key size is insufficient
2429                     if (sm_encryption_key_size(handle) < 16){
2430                         // 0x0007 Connection refused – insufficient encryption key size
2431                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
2432                         return 1;
2433                     }
2434                 }
2435 
2436                 // security: check authencation
2437                 if (service->required_security_level >= LEVEL_3){
2438                     if (!sm_authenticated(handle)){
2439                         // 0x0005 Connection refused – insufficient authentication
2440                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
2441                         return 1;
2442                     }
2443                 }
2444 
2445                 // security: check authorization
2446                 if (service->required_security_level >= LEVEL_4){
2447                     if (sm_authorization_state(handle) != AUTHORIZATION_GRANTED){
2448                         // 0x0006 Connection refused – insufficient authorization
2449                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
2450                         return 1;
2451                     }
2452                 }
2453 
2454                 // allocate channel
2455                 channel = l2cap_create_channel_entry(service->packet_handler, connection->address,
2456                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
2457                 if (!channel){
2458                     // 0x0004 Connection refused – no resources available
2459                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2460                     return 1;
2461                 }
2462 
2463                 channel->con_handle = handle;
2464                 channel->remote_cid = source_cid;
2465                 channel->remote_sig_id = sig_id;
2466                 channel->remote_mtu = little_endian_read_16(command, 8);
2467                 channel->remote_mps = little_endian_read_16(command, 10);
2468                 channel->credits_outgoing = little_endian_read_16(command, 12);
2469 
2470                 // set initial state
2471                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2472                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
2473 
2474                 // add to connections list
2475                 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2476 
2477                 // post connection request event
2478                 l2cap_emit_le_incoming_connection(channel);
2479 
2480             } else {
2481                 // Connection refused – LE_PSM not supported
2482                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2483             }
2484             break;
2485 
2486         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
2487             // Find channel for this sig_id and connection handle
2488             channel = NULL;
2489             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2490             while (btstack_linked_list_iterator_has_next(&it)){
2491                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2492                 if (a_channel->con_handle   != handle) continue;
2493                 if (a_channel->local_sig_id != sig_id) continue;
2494                 channel = a_channel;
2495                 break;
2496             }
2497             if (!channel) break;
2498 
2499             // cid + 0
2500             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
2501             if (result){
2502                 channel->state = L2CAP_STATE_CLOSED;
2503                 // map l2cap connection response result to BTstack status enumeration
2504                 l2cap_emit_le_channel_opened(channel, result);
2505 
2506                 // discard channel
2507                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2508                 btstack_memory_l2cap_channel_free(channel);
2509                 break;
2510             }
2511 
2512             // success
2513             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
2514             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
2515             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
2516             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
2517             channel->state = L2CAP_STATE_OPEN;
2518             l2cap_emit_le_channel_opened(channel, result);
2519             break;
2520 
2521         case LE_FLOW_CONTROL_CREDIT:
2522             // find channel
2523             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
2524             channel = l2cap_le_get_channel_for_local_cid(local_cid);
2525             if (!channel) {
2526                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
2527                 break;
2528             }
2529             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
2530             credits_before = channel->credits_outgoing;
2531             channel->credits_outgoing += new_credits;
2532             // check for credit overrun
2533             if (credits_before > channel->credits_outgoing){
2534                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
2535                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2536                 break;
2537             }
2538             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
2539             break;
2540 
2541         case DISCONNECTION_REQUEST:
2542             // find channel
2543             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
2544             channel = l2cap_le_get_channel_for_local_cid(local_cid);
2545             if (!channel) {
2546                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
2547                 break;
2548             }
2549             channel->remote_sig_id = sig_id;
2550             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
2551             break;
2552 
2553 #endif
2554 
2555         case DISCONNECTION_RESPONSE:
2556             break;
2557 
2558         default:
2559             // command unknown -> reject command
2560             return 0;
2561     }
2562     return 1;
2563 }
2564 #endif
2565 
2566 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size ){
2567     UNUSED(packet_type);
2568     UNUSED(channel);
2569 
2570     l2cap_channel_t * l2cap_channel;
2571     UNUSED(l2cap_channel);
2572 
2573     // Get Channel ID
2574     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
2575     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
2576 
2577     switch (channel_id) {
2578 
2579 #ifdef ENABLE_CLASSIC
2580         case L2CAP_CID_SIGNALING: {
2581             uint16_t command_offset = 8;
2582             while (command_offset < size) {
2583                 // handle signaling commands
2584                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
2585 
2586                 // increment command_offset
2587                 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2588             }
2589             break;
2590         }
2591 #endif
2592 
2593 #ifdef ENABLE_BLE
2594         case L2CAP_CID_SIGNALING_LE: {
2595             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
2596             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
2597             if (!valid){
2598                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2599             }
2600             break;
2601         }
2602 #endif
2603 
2604         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
2605             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback) {
2606                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2607             }
2608             break;
2609 
2610         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
2611             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback) {
2612                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2613             }
2614             break;
2615 
2616         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
2617             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback) {
2618                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2619             }
2620             break;
2621 
2622         default:
2623 #ifdef ENABLE_CLASSIC
2624             // Find channel for this channel_id and connection handle
2625             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
2626             if (l2cap_channel) {
2627 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2628                 if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
2629 
2630                     // verify FCS
2631                     uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
2632                     uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
2633                     log_info("Packet FCS 0x%04x, calculated FCS 0x%04x", fcs_packet, fcs_calculated);
2634                     if (fcs_calculated != fcs_packet){
2635                         log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
2636                         // TODO: trigger retransmission or something like that
2637                         break;
2638                     }
2639 
2640                     // switch on packet type
2641                     uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
2642                     uint8_t  req_seq = (control >> 8) & 0x3f;
2643                     int final = (control >> 7) & 0x01;
2644                     if (control & 1){
2645                         // S-Frame
2646                         int poll  = (control >> 4) & 0x01;
2647                         l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
2648                         log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
2649                         l2cap_ertm_tx_packet_state_t * tx_state;
2650                         switch (s){
2651                             case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
2652                                 log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
2653                                 l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
2654                                 if (poll && final){
2655                                     // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
2656                                     log_error("P=F=1 in S-Frame");
2657                                     break;
2658                                 }
2659                                 if (poll){
2660                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
2661                                     l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
2662                                 }
2663                                 if (final){
2664                                     // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
2665                                     l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
2666                                 }
2667                                 break;
2668                             case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
2669                                 log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
2670                                 l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
2671                                 // rsetart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_handle_req_seq)
2672                                 l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
2673                                 break;
2674                             case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
2675                                 log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
2676                                 break;
2677                             case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
2678                                 log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
2679                                 if (poll){
2680                                     l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
2681                                 }
2682                                 // find requested i-frame
2683                                 tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
2684                                 if (tx_state){
2685                                     log_info("Retransmission for tx_seq %u requested", req_seq);
2686                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
2687                                     tx_state->retransmission_requested = 1;
2688                                     l2cap_channel->srej_active = 1;
2689                                 }
2690                                 break;
2691                             default:
2692                                 break;
2693                         }
2694                         break;
2695                     } else {
2696                         // I-Frame
2697                         // get control
2698                         l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
2699                         uint8_t tx_seq = (control >> 1) & 0x3f;
2700                         log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
2701                         log_info("SAR: pos %u", l2cap_channel->rx_packets_state->pos);
2702                         log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
2703                         l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
2704                         if (final){
2705                             // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
2706                             l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
2707                         }
2708                         // check ordering
2709                         if (l2cap_channel->expected_tx_seq == tx_seq){
2710                             log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
2711                             l2cap_channel->req_seq = (tx_seq+1) & 0x3f;
2712                             l2cap_channel->send_supervisor_frame_receiver_ready = 1;
2713                             l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
2714                             uint16_t sdu_length;
2715                             uint16_t segment_length;
2716                             uint16_t payload_offset;
2717                             switch (sar){
2718                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
2719                                     payload_offset = COMPLETE_L2CAP_HEADER+2;
2720                                     segment_length = payload_offset-2;
2721                                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER+2], segment_length);
2722                                     break;
2723                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
2724                                     // TODO: use current packet
2725                                     // TODO: check if reassembly started
2726                                     // TODO: check len against local mtu
2727                                     sdu_length = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER+2);
2728                                     payload_offset = COMPLETE_L2CAP_HEADER+4;
2729                                     segment_length = size - payload_offset-2;
2730                                     memcpy(&l2cap_channel->rx_packets_data[0], &packet[payload_offset], segment_length);
2731                                     l2cap_channel->rx_packets_state->sdu_length = sdu_length;
2732                                     l2cap_channel->rx_packets_state->pos = segment_length;
2733                                     break;
2734                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
2735                                     payload_offset = COMPLETE_L2CAP_HEADER+2;
2736                                     segment_length = size - payload_offset-2;
2737                                     memcpy(&l2cap_channel->rx_packets_data[l2cap_channel->rx_packets_state->pos], &packet[payload_offset], segment_length);
2738                                     l2cap_channel->rx_packets_state->pos += segment_length;
2739                                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->rx_packets_data, l2cap_channel->rx_packets_state[0].pos);
2740                                     break;
2741                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
2742                                     payload_offset = COMPLETE_L2CAP_HEADER+2;
2743                                     segment_length = size - payload_offset-2;
2744                                     memcpy(&l2cap_channel->rx_packets_data[l2cap_channel->rx_packets_state->pos], &packet[payload_offset], segment_length);
2745                                     l2cap_channel->rx_packets_state->pos += segment_length;
2746                                     break;
2747                             }
2748                         } else {
2749                             int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
2750                             if (delta < 2){
2751                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
2752                                 l2cap_channel->send_supervisor_frame_selective_reject = 1;
2753                             } else {
2754                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
2755                                 l2cap_channel->send_supervisor_frame_reject = 1;
2756                             }
2757                         }
2758                     }
2759                     break;
2760                 }
2761 #endif
2762                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2763             }
2764 #endif
2765 #ifdef ENABLE_LE_DATA_CHANNELS
2766             l2cap_channel = l2cap_le_get_channel_for_local_cid(channel_id);
2767             if (l2cap_channel) {
2768                 // credit counting
2769                 if (l2cap_channel->credits_incoming == 0){
2770                     log_error("LE Data Channel packet received but no incoming credits");
2771                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2772                     break;
2773                 }
2774                 l2cap_channel->credits_incoming--;
2775 
2776                 // automatic credits
2777                 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){
2778                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
2779                 }
2780 
2781                 // first fragment
2782                 uint16_t pos = 0;
2783                 if (!l2cap_channel->receive_sdu_len){
2784                     l2cap_channel->receive_sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
2785                     l2cap_channel->receive_sdu_pos = 0;
2786                     pos  += 2;
2787                     size -= 2;
2788                 }
2789                 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], size-COMPLETE_L2CAP_HEADER);
2790                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
2791                 // done?
2792                 log_info("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
2793                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
2794                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
2795                     l2cap_channel->receive_sdu_len = 0;
2796                 }
2797             } else {
2798                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
2799             }
2800 #endif
2801             break;
2802     }
2803 
2804     l2cap_run();
2805 }
2806 
2807 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
2808 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
2809     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
2810     if (index < 0) return;
2811     fixed_channels[index].callback = the_packet_handler;
2812 }
2813 
2814 #ifdef ENABLE_CLASSIC
2815 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
2816 void l2cap_finialize_channel_close(l2cap_channel_t * channel){
2817     channel->state = L2CAP_STATE_CLOSED;
2818     l2cap_emit_channel_closed(channel);
2819     // discard channel
2820     l2cap_stop_rtx(channel);
2821     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2822     btstack_memory_l2cap_channel_free(channel);
2823 }
2824 
2825 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
2826     btstack_linked_list_iterator_t it;
2827     btstack_linked_list_iterator_init(&it, services);
2828     while (btstack_linked_list_iterator_has_next(&it)){
2829         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
2830         if ( service->psm == psm){
2831             return service;
2832         };
2833     }
2834     return NULL;
2835 }
2836 
2837 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
2838     return l2cap_get_service_internal(&l2cap_services, psm);
2839 }
2840 
2841 
2842 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
2843 
2844     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
2845 
2846     // check for alread registered psm
2847     l2cap_service_t *service = l2cap_get_service(psm);
2848     if (service) {
2849         log_error("l2cap_register_service: PSM %u already registered", psm);
2850         return L2CAP_SERVICE_ALREADY_REGISTERED;
2851     }
2852 
2853     // alloc structure
2854     service = btstack_memory_l2cap_service_get();
2855     if (!service) {
2856         log_error("l2cap_register_service: no memory for l2cap_service_t");
2857         return BTSTACK_MEMORY_ALLOC_FAILED;
2858     }
2859 
2860     // fill in
2861     service->psm = psm;
2862     service->mtu = mtu;
2863     service->packet_handler = service_packet_handler;
2864     service->required_security_level = security_level;
2865 
2866     // add to services list
2867     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
2868 
2869     // enable page scan
2870     gap_connectable_control(1);
2871 
2872     return 0;
2873 }
2874 
2875 uint8_t l2cap_unregister_service(uint16_t psm){
2876 
2877     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
2878 
2879     l2cap_service_t *service = l2cap_get_service(psm);
2880     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2881     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
2882     btstack_memory_l2cap_service_free(service);
2883 
2884     // disable page scan when no services registered
2885     if (btstack_linked_list_empty(&l2cap_services)) {
2886         gap_connectable_control(0);
2887     }
2888     return 0;
2889 }
2890 #endif
2891 
2892 
2893 #ifdef ENABLE_LE_DATA_CHANNELS
2894 
2895 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
2896     if (!channel->waiting_for_can_send_now) return;
2897     if (channel->send_sdu_buffer) return;
2898     channel->waiting_for_can_send_now = 0;
2899     log_info("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
2900     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
2901 }
2902 
2903 // 1BH2222
2904 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
2905     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",
2906              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
2907     uint8_t event[19];
2908     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
2909     event[1] = sizeof(event) - 2;
2910     event[2] = channel->address_type;
2911     reverse_bd_addr(channel->address, &event[3]);
2912     little_endian_store_16(event,  9, channel->con_handle);
2913     little_endian_store_16(event, 11, channel->psm);
2914     little_endian_store_16(event, 13, channel->local_cid);
2915     little_endian_store_16(event, 15, channel->remote_cid);
2916     little_endian_store_16(event, 17, channel->remote_mtu);
2917     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2918     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
2919 }
2920 // 11BH22222
2921 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
2922     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",
2923              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
2924              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
2925     uint8_t event[23];
2926     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
2927     event[1] = sizeof(event) - 2;
2928     event[2] = status;
2929     event[3] = channel->address_type;
2930     reverse_bd_addr(channel->address, &event[4]);
2931     little_endian_store_16(event, 10, channel->con_handle);
2932     event[12] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
2933     little_endian_store_16(event, 13, channel->psm);
2934     little_endian_store_16(event, 15, channel->local_cid);
2935     little_endian_store_16(event, 17, channel->remote_cid);
2936     little_endian_store_16(event, 19, channel->local_mtu);
2937     little_endian_store_16(event, 21, channel->remote_mtu);
2938     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2939     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
2940 }
2941 
2942 static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid){
2943     btstack_linked_list_iterator_t it;
2944     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2945     while (btstack_linked_list_iterator_has_next(&it)){
2946         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2947         if ( channel->local_cid == local_cid) {
2948             return channel;
2949         }
2950     }
2951     return NULL;
2952 }
2953 
2954 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
2955 void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
2956     channel->state = L2CAP_STATE_CLOSED;
2957     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
2958     // discard channel
2959     btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2960     btstack_memory_l2cap_channel_free(channel);
2961 }
2962 
2963 static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
2964     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
2965 }
2966 
2967 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
2968 
2969     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
2970 
2971     // check for alread registered psm
2972     l2cap_service_t *service = l2cap_le_get_service(psm);
2973     if (service) {
2974         return L2CAP_SERVICE_ALREADY_REGISTERED;
2975     }
2976 
2977     // alloc structure
2978     service = btstack_memory_l2cap_service_get();
2979     if (!service) {
2980         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
2981         return BTSTACK_MEMORY_ALLOC_FAILED;
2982     }
2983 
2984     // fill in
2985     service->psm = psm;
2986     service->mtu = 0;
2987     service->packet_handler = packet_handler;
2988     service->required_security_level = security_level;
2989 
2990     // add to services list
2991     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
2992 
2993     // done
2994     return 0;
2995 }
2996 
2997 uint8_t l2cap_le_unregister_service(uint16_t psm) {
2998     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
2999     l2cap_service_t *service = l2cap_le_get_service(psm);
3000     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3001 
3002     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
3003     btstack_memory_l2cap_service_free(service);
3004     return 0;
3005 }
3006 
3007 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
3008     // get channel
3009     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3010     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3011 
3012     // validate state
3013     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3014         return ERROR_CODE_COMMAND_DISALLOWED;
3015     }
3016 
3017     // set state accept connection
3018     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
3019     channel->receive_sdu_buffer = receive_sdu_buffer;
3020     channel->local_mtu = mtu;
3021     channel->new_credits_incoming = initial_credits;
3022     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
3023 
3024     // test
3025     // channel->new_credits_incoming = 1;
3026 
3027     // go
3028     l2cap_run();
3029     return 0;
3030 }
3031 
3032 /**
3033  * @brief Deny incoming LE Data Channel connection due to resource constraints
3034  * @param local_cid             L2CAP LE Data Channel Identifier
3035  */
3036 
3037 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
3038     // get channel
3039     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3040     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3041 
3042     // validate state
3043     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3044         return ERROR_CODE_COMMAND_DISALLOWED;
3045     }
3046 
3047     // set state decline connection
3048     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
3049     channel->reason = 0x04; // no resources available
3050     l2cap_run();
3051     return 0;
3052 }
3053 
3054 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
3055     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
3056     uint16_t * out_local_cid) {
3057 
3058     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
3059 
3060 
3061     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3062     if (!connection) {
3063         log_error("no hci_connection for handle 0x%04x", con_handle);
3064         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3065     }
3066 
3067     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, connection->address, connection->address_type, psm, mtu, security_level);
3068     if (!channel) {
3069         return BTSTACK_MEMORY_ALLOC_FAILED;
3070     }
3071     log_info("l2cap_le_create_channel %p", channel);
3072 
3073     // store local_cid
3074     if (out_local_cid){
3075        *out_local_cid = channel->local_cid;
3076     }
3077 
3078     // provide buffer
3079     channel->con_handle = con_handle;
3080     channel->receive_sdu_buffer = receive_sdu_buffer;
3081     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
3082     channel->new_credits_incoming = initial_credits;
3083     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
3084 
3085     // add to connections list
3086     btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
3087 
3088     // go
3089     l2cap_run();
3090     return 0;
3091 }
3092 
3093 /**
3094  * @brief Provide credtis for LE Data Channel
3095  * @param local_cid             L2CAP LE Data Channel Identifier
3096  * @param credits               Number additional credits for peer
3097  */
3098 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
3099 
3100     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3101     if (!channel) {
3102         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
3103         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3104     }
3105 
3106     // check state
3107     if (channel->state != L2CAP_STATE_OPEN){
3108         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
3109     }
3110 
3111     // assert incoming credits + credits <= 0xffff
3112     uint32_t total_credits = channel->credits_incoming;
3113     total_credits += channel->new_credits_incoming;
3114     total_credits += credits;
3115     if (total_credits > 0xffff){
3116         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
3117             channel->new_credits_incoming, credits);
3118     }
3119 
3120     // set credits_granted
3121     channel->new_credits_incoming += credits;
3122 
3123     // go
3124     l2cap_run();
3125     return 0;
3126 }
3127 
3128 /**
3129  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
3130  * @param local_cid             L2CAP LE Data Channel Identifier
3131  */
3132 int l2cap_le_can_send_now(uint16_t local_cid){
3133     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3134     if (!channel) {
3135         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
3136         return 0;
3137     }
3138 
3139     // check state
3140     if (channel->state != L2CAP_STATE_OPEN) return 0;
3141 
3142     // check queue
3143     if (channel->send_sdu_buffer) return 0;
3144 
3145     // fine, go ahead
3146     return 1;
3147 }
3148 
3149 /**
3150  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
3151  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
3152  *       so packet handler should be ready to handle it
3153  * @param local_cid             L2CAP LE Data Channel Identifier
3154  */
3155 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
3156     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3157     if (!channel) {
3158         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
3159         return 0;
3160     }
3161     channel->waiting_for_can_send_now = 1;
3162     l2cap_le_notify_channel_can_send(channel);
3163     return 0;
3164 }
3165 
3166 /**
3167  * @brief Send data via LE Data Channel
3168  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
3169  * @param local_cid             L2CAP LE Data Channel Identifier
3170  * @param data                  data to send
3171  * @param size                  data size
3172  */
3173 uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
3174 
3175     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3176     if (!channel) {
3177         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
3178         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3179     }
3180 
3181     if (len > channel->remote_mtu){
3182         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
3183         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
3184     }
3185 
3186     if (channel->send_sdu_buffer){
3187         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
3188         return BTSTACK_ACL_BUFFERS_FULL;
3189     }
3190 
3191     channel->send_sdu_buffer = data;
3192     channel->send_sdu_len    = len;
3193     channel->send_sdu_pos    = 0;
3194 
3195     l2cap_run();
3196     return 0;
3197 }
3198 
3199 /**
3200  * @brief Disconnect from LE Data Channel
3201  * @param local_cid             L2CAP LE Data Channel Identifier
3202  */
3203 uint8_t l2cap_le_disconnect(uint16_t local_cid)
3204 {
3205     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3206     if (!channel) {
3207         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
3208         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3209     }
3210 
3211     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3212     l2cap_run();
3213     return 0;
3214 }
3215 
3216 #endif
3217