xref: /btstack/src/l2cap.c (revision 09e9d05bab154bbd5dd313e0a6d9a7d1650597fc)
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 /*
39  *  l2cap.c
40  *
41  *  Logical Link Control and Adaption Protocl (L2CAP)
42  *
43  *  Created by Matthias Ringwald on 5/16/09.
44  */
45 
46 #include "l2cap.h"
47 #include "hci.h"
48 #include "hci_dump.h"
49 #include "btstack_debug.h"
50 #include "btstack_event.h"
51 #include "btstack_memory.h"
52 
53 #ifdef ENABLE_LE_DATA_CHANNELS
54 #include "ble/sm.h"
55 #endif
56 
57 #include <stdarg.h>
58 #include <string.h>
59 
60 #include <stdio.h>
61 
62 // nr of buffered acl packets in outgoing queue to get max performance
63 #define NR_BUFFERED_ACL_PACKETS 3
64 
65 // used to cache l2cap rejects, echo, and informational requests
66 #define NR_PENDING_SIGNALING_RESPONSES 3
67 
68 // nr of credits provided to remote if credits fall below watermark
69 #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK 5
70 #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT 5
71 
72 // offsets for L2CAP SIGNALING COMMANDS
73 #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
74 #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
75 #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
76 #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
77 
78 // internal table
79 #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL 0
80 #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL  1
81 #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL 2
82 #define L2CAP_FIXED_CHANNEL_TABLE_SIZE (L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL+1)
83 
84 #if defined(ENABLE_LE_DATA_CHANNELS) || defined(ENABLE_CLASSIC)
85 #define L2CAP_USES_CHANNELS
86 #endif
87 
88 // prototypes
89 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
90 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size );
91 static void l2cap_notify_channel_can_send(void);
92 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel);
93 #ifdef ENABLE_CLASSIC
94 static void l2cap_finialize_channel_close(l2cap_channel_t *channel);
95 static inline l2cap_service_t * l2cap_get_service(uint16_t psm);
96 static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
97 static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
98 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel);
99 static int  l2cap_channel_ready_for_open(l2cap_channel_t *channel);
100 #endif
101 #ifdef ENABLE_LE_DATA_CHANNELS
102 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status);
103 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel);
104 static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid);
105 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel);
106 static void l2cap_le_finialize_channel_close(l2cap_channel_t *channel);
107 static inline l2cap_service_t * l2cap_le_get_service(uint16_t psm);
108 #endif
109 
110 typedef struct l2cap_fixed_channel {
111     btstack_packet_handler_t callback;
112     uint8_t waiting_for_can_send_now;
113 } l2cap_fixed_channel_t;
114 
115 #ifdef ENABLE_CLASSIC
116 static btstack_linked_list_t l2cap_channels;
117 static btstack_linked_list_t l2cap_services;
118 static uint8_t require_security_level2_for_outgoing_sdp;
119 #endif
120 
121 #ifdef ENABLE_LE_DATA_CHANNELS
122 static btstack_linked_list_t l2cap_le_channels;
123 static btstack_linked_list_t l2cap_le_services;
124 #endif
125 
126 // used to cache l2cap rejects, echo, and informational requests
127 static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
128 static int signaling_responses_pending;
129 
130 static btstack_packet_callback_registration_t hci_event_callback_registration;
131 
132 static btstack_packet_handler_t l2cap_event_packet_handler;
133 static l2cap_fixed_channel_t fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_SIZE];
134 
135 static uint16_t l2cap_fixed_channel_table_channel_id_for_index(int index){
136     switch (index){
137         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL:
138             return L2CAP_CID_ATTRIBUTE_PROTOCOL;
139         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL:
140             return L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
141         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL:
142             return L2CAP_CID_CONNECTIONLESS_CHANNEL;
143         default:
144             return 0;
145     }
146 }
147 static int l2cap_fixed_channel_table_index_for_channel_id(uint16_t channel_id){
148     switch (channel_id){
149         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
150             return L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL;
151         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
152             return  L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL;
153         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
154             return  L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL;
155         default:
156             return -1;
157         }
158 }
159 
160 static int l2cap_fixed_channel_table_index_is_le(int index){
161     if (index == L2CAP_CID_CONNECTIONLESS_CHANNEL) return 0;
162     return 1;
163 }
164 
165 void l2cap_init(void){
166     signaling_responses_pending = 0;
167 
168 #ifdef ENABLE_CLASSIC
169     l2cap_channels = NULL;
170     l2cap_services = NULL;
171     require_security_level2_for_outgoing_sdp = 0;
172 #endif
173 
174 #ifdef ENABLE_LE_DATA_CHANNELS
175     l2cap_le_services = NULL;
176     l2cap_le_channels = NULL;
177 #endif
178 
179     l2cap_event_packet_handler = NULL;
180     memset(fixed_channels, 0, sizeof(fixed_channels));
181 
182     //
183     // register callback with HCI
184     //
185     hci_event_callback_registration.callback = &l2cap_hci_event_handler;
186     hci_add_event_handler(&hci_event_callback_registration);
187 
188     hci_register_acl_packet_handler(&l2cap_acl_handler);
189 
190     gap_connectable_control(0); // no services yet
191 }
192 
193 void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
194     l2cap_event_packet_handler = handler;
195 }
196 
197 void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
198     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
199     if (index < 0) return;
200     fixed_channels[index].waiting_for_can_send_now = 1;
201     l2cap_notify_channel_can_send();
202 }
203 
204 int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
205     return hci_can_send_acl_packet_now(con_handle);
206 }
207 
208 uint8_t *l2cap_get_outgoing_buffer(void){
209     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
210 }
211 
212 int l2cap_reserve_packet_buffer(void){
213     return hci_reserve_packet_buffer();
214 }
215 
216 void l2cap_release_packet_buffer(void){
217     hci_release_packet_buffer();
218 }
219 
220 static void l2cap_setup_header(uint8_t * acl_buffer, hci_con_handle_t con_handle, uint16_t remote_cid, uint16_t len){
221     int pb = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
222 
223     // 0 - Connection handle : PB=pb : BC=00
224     little_endian_store_16(acl_buffer, 0, con_handle | (pb << 12) | (0 << 14));
225     // 2 - ACL length
226     little_endian_store_16(acl_buffer, 2,  len + 4);
227     // 4 - L2CAP packet length
228     little_endian_store_16(acl_buffer, 4,  len + 0);
229     // 6 - L2CAP channel DEST
230     little_endian_store_16(acl_buffer, 6,  remote_cid);
231 }
232 
233 int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
234 
235     if (!hci_is_packet_buffer_reserved()){
236         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
237         return BTSTACK_ACL_BUFFERS_FULL;
238     }
239 
240     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
241         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
242         return BTSTACK_ACL_BUFFERS_FULL;
243     }
244 
245     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
246 
247     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
248     l2cap_setup_header(acl_buffer, con_handle, cid, len);
249     // send
250     return hci_send_acl_packet_buffer(len+8);
251 }
252 
253 int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
254 
255     if (!hci_can_send_acl_packet_now(con_handle)){
256         log_info("l2cap_send cid 0x%02x, cannot send", cid);
257         return BTSTACK_ACL_BUFFERS_FULL;
258     }
259 
260     hci_reserve_packet_buffer();
261     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
262 
263     memcpy(&acl_buffer[8], data, len);
264 
265     return l2cap_send_prepared_connectionless(con_handle, cid, len);
266 }
267 
268 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
269     log_info("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
270     uint8_t event[4];
271     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
272     event[1] = sizeof(event) - 2;
273     little_endian_store_16(event, 2, channel);
274     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
275     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
276 }
277 
278 #ifdef L2CAP_USES_CHANNELS
279 static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
280     (* (channel->packet_handler))(type, channel->local_cid, data, size);
281 }
282 
283 static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
284     uint8_t event[4];
285     event[0] = event_code;
286     event[1] = sizeof(event) - 2;
287     little_endian_store_16(event, 2, channel->local_cid);
288     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
289     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
290 }
291 #endif
292 
293 #ifdef ENABLE_CLASSIC
294 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
295     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",
296              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
297              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
298     uint8_t event[23];
299     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
300     event[1] = sizeof(event) - 2;
301     event[2] = status;
302     reverse_bd_addr(channel->address, &event[3]);
303     little_endian_store_16(event,  9, channel->con_handle);
304     little_endian_store_16(event, 11, channel->psm);
305     little_endian_store_16(event, 13, channel->local_cid);
306     little_endian_store_16(event, 15, channel->remote_cid);
307     little_endian_store_16(event, 17, channel->local_mtu);
308     little_endian_store_16(event, 19, channel->remote_mtu);
309     little_endian_store_16(event, 21, channel->flush_timeout);
310     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
311     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
312 }
313 
314 static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
315     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
316     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
317 }
318 
319 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
320     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
321              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
322     uint8_t event[16];
323     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
324     event[1] = sizeof(event) - 2;
325     reverse_bd_addr(channel->address, &event[2]);
326     little_endian_store_16(event,  8, channel->con_handle);
327     little_endian_store_16(event, 10, channel->psm);
328     little_endian_store_16(event, 12, channel->local_cid);
329     little_endian_store_16(event, 14, channel->remote_cid);
330     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
331     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
332 }
333 
334 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
335     btstack_linked_list_iterator_t it;
336     btstack_linked_list_iterator_init(&it, &l2cap_channels);
337     while (btstack_linked_list_iterator_has_next(&it)){
338         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
339         if ( channel->local_cid == local_cid) {
340             return channel;
341         }
342     }
343     return NULL;
344 }
345 
346 ///
347 
348 void l2cap_request_can_send_now_event(uint16_t local_cid){
349     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
350     if (!channel) return;
351     channel->waiting_for_can_send_now = 1;
352     l2cap_notify_channel_can_send();
353 }
354 
355 int  l2cap_can_send_packet_now(uint16_t local_cid){
356     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
357     if (!channel) return 0;
358     return hci_can_send_acl_packet_now(channel->con_handle);
359 }
360 
361 int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
362     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
363     if (!channel) return 0;
364     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
365 }
366 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
367     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
368     if (channel) {
369         return channel->remote_mtu;
370     }
371     return 0;
372 }
373 
374 static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
375     btstack_linked_list_iterator_t it;
376     btstack_linked_list_iterator_init(&it, &l2cap_channels);
377     while (btstack_linked_list_iterator_has_next(&it)){
378         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
379         if ( &channel->rtx == ts) {
380             return channel;
381         }
382     }
383     return NULL;
384 }
385 
386 static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
387     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
388     if (!channel) return;
389 
390     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
391 
392     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
393     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
394     // notify client
395     l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
396 
397     // discard channel
398     // no need to stop timer here, it is removed from list during timer callback
399     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
400     btstack_memory_l2cap_channel_free(channel);
401 }
402 
403 static void l2cap_stop_rtx(l2cap_channel_t * channel){
404     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
405     btstack_run_loop_remove_timer(&channel->rtx);
406 }
407 
408 static void l2cap_start_rtx(l2cap_channel_t * channel){
409     l2cap_stop_rtx(channel);
410     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
411     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
412     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
413     btstack_run_loop_add_timer(&channel->rtx);
414 }
415 
416 static void l2cap_start_ertx(l2cap_channel_t * channel){
417     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
418     l2cap_stop_rtx(channel);
419     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
420     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
421     btstack_run_loop_add_timer(&channel->rtx);
422 }
423 
424 void l2cap_require_security_level_2_for_outgoing_sdp(void){
425     require_security_level2_for_outgoing_sdp = 1;
426 }
427 
428 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
429     return (psm == PSM_SDP) && (!require_security_level2_for_outgoing_sdp);
430 }
431 
432 static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
433     if (!hci_can_send_acl_packet_now(handle)){
434         log_info("l2cap_send_signaling_packet, cannot send");
435         return BTSTACK_ACL_BUFFERS_FULL;
436     }
437 
438     // log_info("l2cap_send_signaling_packet type %u", cmd);
439     hci_reserve_packet_buffer();
440     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
441     va_list argptr;
442     va_start(argptr, identifier);
443     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
444     va_end(argptr);
445     // log_info("l2cap_send_signaling_packet con %u!", handle);
446     return hci_send_acl_packet_buffer(len);
447 }
448 
449 int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
450 
451     if (!hci_is_packet_buffer_reserved()){
452         log_error("l2cap_send_prepared called without reserving packet first");
453         return BTSTACK_ACL_BUFFERS_FULL;
454     }
455 
456     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
457     if (!channel) {
458         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
459         return -1;   // TODO: define error
460     }
461 
462     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
463         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
464         return BTSTACK_ACL_BUFFERS_FULL;
465     }
466 
467     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
468 
469     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
470     l2cap_setup_header(acl_buffer, channel->con_handle, channel->remote_cid, len);
471     // send
472     return hci_send_acl_packet_buffer(len+8);
473 }
474 
475 int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
476 
477     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
478     if (!channel) {
479         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
480         return -1;   // TODO: define error
481     }
482 
483     if (len > channel->remote_mtu){
484         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
485         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
486     }
487 
488     if (!hci_can_send_acl_packet_now(channel->con_handle)){
489         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
490         return BTSTACK_ACL_BUFFERS_FULL;
491     }
492 
493     hci_reserve_packet_buffer();
494     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
495 
496     memcpy(&acl_buffer[8], data, len);
497 
498     return l2cap_send_prepared(local_cid, len);
499 }
500 
501 int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
502     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
503 }
504 
505 static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
506     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
507 }
508 
509 static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
510     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
511 }
512 #endif
513 
514 
515 #ifdef ENABLE_BLE
516 static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
517 
518     if (!hci_can_send_acl_packet_now(handle)){
519         log_info("l2cap_send_le_signaling_packet, cannot send");
520         return BTSTACK_ACL_BUFFERS_FULL;
521     }
522 
523     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
524     hci_reserve_packet_buffer();
525     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
526     va_list argptr;
527     va_start(argptr, identifier);
528     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
529     va_end(argptr);
530     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
531     return hci_send_acl_packet_buffer(len);
532 }
533 #endif
534 
535 uint16_t l2cap_max_mtu(void){
536     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
537 }
538 
539 uint16_t l2cap_max_le_mtu(void){
540     return l2cap_max_mtu();
541 }
542 
543 // MARK: L2CAP_RUN
544 // process outstanding signaling tasks
545 static void l2cap_run(void){
546 
547     // log_info("l2cap_run: entered");
548 
549     // check pending signaling responses
550     while (signaling_responses_pending){
551 
552         hci_con_handle_t handle = signaling_responses[0].handle;
553 
554         if (!hci_can_send_acl_packet_now(handle)) break;
555 
556         uint8_t  sig_id = signaling_responses[0].sig_id;
557         uint16_t infoType = signaling_responses[0].data;    // INFORMATION_REQUEST
558         uint16_t result   = signaling_responses[0].data;    // CONNECTION_REQUEST, COMMAND_REJECT
559         uint8_t  response_code = signaling_responses[0].code;
560 
561         // avoid warnings
562         (void) infoType;
563 
564         // remove first item before sending (to avoid sending response mutliple times)
565         signaling_responses_pending--;
566         int i;
567         for (i=0; i < signaling_responses_pending; i++){
568             memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t));
569         }
570 
571         switch (response_code){
572 #ifdef ENABLE_CLASSIC
573             case CONNECTION_REQUEST:
574                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, 0, 0, result, 0);
575                 // also disconnect if result is 0x0003 - security blocked
576                 if (result == 0x0003){
577                     hci_disconnect_security_block(handle);
578                 }
579                 break;
580             case ECHO_REQUEST:
581                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
582                 break;
583             case INFORMATION_REQUEST:
584                 switch (infoType){
585                     case 1: { // Connectionless MTU
586                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
587                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(connectionless_mtu), &connectionless_mtu);
588                         }
589                         break;
590                     case 2: { // Extended Features Supported
591                             // extended features request supported, features: fixed channels, unicast connectionless data reception
592                             uint32_t features = 0x280;
593                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(features), &features);
594                         }
595                         break;
596                     case 3: { // Fixed Channels Supported
597                             uint8_t map[8];
598                             memset(map, 0, 8);
599                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
600                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(map), &map);
601                         }
602                         break;
603                     default:
604                         // all other types are not supported
605                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
606                         break;
607                 }
608                 break;
609             case COMMAND_REJECT:
610                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
611                 break;
612 #endif
613 #ifdef ENABLE_BLE
614             case LE_CREDIT_BASED_CONNECTION_REQUEST:
615                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
616                 break;
617             case COMMAND_REJECT_LE:
618                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
619                 break;
620 #endif
621             default:
622                 // should not happen
623                 break;
624         }
625     }
626 
627     btstack_linked_list_iterator_t it;
628     (void) it;
629 
630 #ifdef ENABLE_CLASSIC
631     uint8_t  config_options[4];
632     btstack_linked_list_iterator_init(&it, &l2cap_channels);
633     while (btstack_linked_list_iterator_has_next(&it)){
634 
635         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
636         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
637         switch (channel->state){
638 
639             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
640             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
641                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
642                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
643                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
644                     l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
645                 }
646                 break;
647 
648             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
649                 if (!hci_can_send_command_packet_now()) break;
650                 // send connection request - set state first
651                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
652                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
653                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
654                 break;
655 
656             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
657                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
658                 channel->state = L2CAP_STATE_INVALID;
659                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
660                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
661                 l2cap_stop_rtx(channel);
662                 btstack_linked_list_iterator_remove(&it);
663                 btstack_memory_l2cap_channel_free(channel);
664                 break;
665 
666             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
667                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
668                 channel->state = L2CAP_STATE_CONFIG;
669                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
670                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
671                 break;
672 
673             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
674                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
675                 // success, start l2cap handshake
676                 channel->local_sig_id = l2cap_next_sig_id();
677                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
678                 l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
679                 l2cap_start_rtx(channel);
680                 break;
681 
682             case L2CAP_STATE_CONFIG:
683                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
684                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
685                     uint16_t flags = 0;
686                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
687                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
688                         flags = 1;
689                     } else {
690                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
691                     }
692                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
693                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS, 0, NULL);
694                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
695                         config_options[0] = 1; // MTU
696                         config_options[1] = 2; // len param
697                         little_endian_store_16( (uint8_t*)&config_options, 2, channel->remote_mtu);
698                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 4, &config_options);
699                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
700                     } else {
701                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 0, NULL);
702                     }
703                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
704                 }
705                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
706                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
707                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
708                     channel->local_sig_id = l2cap_next_sig_id();
709                     config_options[0] = 1; // MTU
710                     config_options[1] = 2; // len param
711                     little_endian_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
712                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, 4, &config_options);
713                     l2cap_start_rtx(channel);
714                 }
715                 if (l2cap_channel_ready_for_open(channel)){
716                     channel->state = L2CAP_STATE_OPEN;
717                     l2cap_emit_channel_opened(channel, 0);  // success
718                 }
719                 break;
720 
721             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
722                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
723                 channel->state = L2CAP_STATE_INVALID;
724                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
725                 // 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 :)
726                 l2cap_finialize_channel_close(channel);  // -- remove from list
727                 break;
728 
729             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
730                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
731                 channel->local_sig_id = l2cap_next_sig_id();
732                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
733                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
734                 break;
735             default:
736                 break;
737         }
738     }
739 #endif
740 
741 #ifdef ENABLE_LE_DATA_CHANNELS
742     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
743     while (btstack_linked_list_iterator_has_next(&it)){
744         uint8_t  * acl_buffer;
745         uint8_t  * l2cap_payload;
746         uint16_t pos;
747         uint16_t payload_size;
748         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
749         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
750         switch (channel->state){
751             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
752                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
753                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
754                 // le psm, source cid, mtu, mps, initial credits
755                 channel->local_sig_id = l2cap_next_sig_id();
756                 channel->credits_incoming =  channel->new_credits_incoming;
757                 channel->new_credits_incoming = 0;
758                 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);
759                 break;
760             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
761                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
762                 // TODO: support larger MPS
763                 channel->state = L2CAP_STATE_OPEN;
764                 channel->credits_incoming =  channel->new_credits_incoming;
765                 channel->new_credits_incoming = 0;
766                 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);
767                 // notify client
768                 l2cap_emit_le_channel_opened(channel, 0);
769                 break;
770             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
771                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
772                 channel->state = L2CAP_STATE_INVALID;
773                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
774                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
775                 l2cap_stop_rtx(channel);
776                 btstack_linked_list_iterator_remove(&it);
777                 btstack_memory_l2cap_channel_free(channel);
778                 break;
779             case L2CAP_STATE_OPEN:
780                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
781 
782                 // send credits
783                 if (channel->new_credits_incoming){
784                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
785                     channel->local_sig_id = l2cap_next_sig_id();
786                     uint16_t new_credits = channel->new_credits_incoming;
787                     channel->new_credits_incoming = 0;
788                     channel->credits_incoming += new_credits;
789                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
790                     break;
791                 }
792 
793                 // send data
794                 if (!channel->send_sdu_buffer) break;
795                 if (!channel->credits_outgoing) break;
796 
797                 // send part of SDU
798                 hci_reserve_packet_buffer();
799                 acl_buffer = hci_get_outgoing_packet_buffer();
800                 l2cap_payload = acl_buffer + 8;
801                 pos = 0;
802                 if (!channel->send_sdu_pos){
803                     // store SDU len
804                     channel->send_sdu_pos += 2;
805                     little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
806                     pos += 2;
807                 }
808                 payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
809                 log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
810                 memcpy(&l2cap_payload[pos], &channel->send_sdu_buffer[channel->send_sdu_pos-2], payload_size); // -2 for virtual SDU len
811                 pos += payload_size;
812                 channel->send_sdu_pos += payload_size;
813                 l2cap_setup_header(acl_buffer, channel->con_handle, channel->remote_cid, pos);
814                 // done
815 
816                 channel->credits_outgoing--;
817 
818                 if (channel->send_sdu_pos >= channel->send_sdu_len + 2){
819                     channel->send_sdu_buffer = NULL;
820                     // send done event
821                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
822                     // inform about can send now
823                     l2cap_le_notify_channel_can_send(channel);
824                 }
825                 hci_send_acl_packet_buffer(8 + pos);
826                 break;
827             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
828                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
829                 channel->local_sig_id = l2cap_next_sig_id();
830                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
831                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
832                 break;
833             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
834                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
835                 channel->state = L2CAP_STATE_INVALID;
836                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
837                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
838                 break;
839             default:
840                 break;
841         }
842     }
843 #endif
844 
845 #ifdef ENABLE_BLE
846     // send l2cap con paramter update if necessary
847     hci_connections_get_iterator(&it);
848     while(btstack_linked_list_iterator_has_next(&it)){
849         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
850         if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue;
851         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
852         switch (connection->le_con_parameter_update_state){
853             case CON_PARAMETER_UPDATE_SEND_REQUEST:
854                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
855                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier,
856                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
857                 break;
858             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
859                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
860                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
861                 break;
862             case CON_PARAMETER_UPDATE_DENY:
863                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
864                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
865                 break;
866             default:
867                 break;
868         }
869     }
870 #endif
871 
872     // log_info("l2cap_run: exit");
873 }
874 
875 #ifdef ENABLE_CLASSIC
876 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
877     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
878         log_info("l2cap_handle_connection_complete expected state");
879         // success, start l2cap handshake
880         channel->con_handle = con_handle;
881         // check remote SSP feature first
882         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
883     }
884 }
885 
886 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
887     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
888 
889     // we have been waiting for remote supported features, if both support SSP,
890     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));
891     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
892         // request security level 2
893         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
894         gap_request_security_level(channel->con_handle, LEVEL_2);
895         return;
896     }
897     // fine, go ahead
898     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
899 }
900 #endif
901 
902 #ifdef L2CAP_USES_CHANNELS
903 static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, bd_addr_t address, bd_addr_type_t address_type,
904     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
905 
906     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
907     if (!channel) {
908         return NULL;
909     }
910 
911      // Init memory (make valgrind happy)
912     memset(channel, 0, sizeof(l2cap_channel_t));
913 
914     // fill in
915     channel->packet_handler = packet_handler;
916     bd_addr_copy(channel->address, address);
917     channel->address_type = address_type;
918     channel->psm = psm;
919     channel->local_mtu  = local_mtu;
920     channel->remote_mtu = L2CAP_MINIMAL_MTU;
921     channel->required_security_level = security_level;
922 
923     //
924     channel->local_cid = l2cap_next_local_cid();
925     channel->con_handle = 0;
926 
927     // set initial state
928     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
929     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
930     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
931     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
932     return channel;
933 }
934 #endif
935 
936 #ifdef ENABLE_CLASSIC
937 
938 /**
939  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
940  * @param packet_handler
941  * @param address
942  * @param psm
943  * @param mtu
944  * @param local_cid
945  */
946 
947 uint8_t l2cap_create_channel(btstack_packet_handler_t channel_packet_handler, bd_addr_t address, uint16_t psm, uint16_t local_mtu, uint16_t * out_local_cid){
948     log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x mtu %u", bd_addr_to_str(address), psm, local_mtu);
949 
950     if (local_mtu > l2cap_max_mtu()) {
951         local_mtu = l2cap_max_mtu();
952     }
953 
954     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
955     if (!channel) {
956         return BTSTACK_MEMORY_ALLOC_FAILED;
957     }
958 
959     // add to connections list
960     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
961 
962     // store local_cid
963     if (out_local_cid){
964        *out_local_cid = channel->local_cid;
965     }
966 
967     // check if hci connection is already usable
968     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
969     if (conn){
970         log_info("l2cap_create_channel, hci connection already exists");
971         l2cap_handle_connection_complete(conn->con_handle, channel);
972         // check if remote supported fearures are already received
973         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
974             l2cap_handle_remote_supported_features_received(channel);
975         }
976     }
977 
978     l2cap_run();
979 
980     return 0;
981 }
982 
983 void
984 l2cap_disconnect(uint16_t local_cid, uint8_t reason){
985     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
986     // find channel for local_cid
987     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
988     if (channel) {
989         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
990     }
991     // process
992     l2cap_run();
993 }
994 
995 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
996     btstack_linked_list_iterator_t it;
997     btstack_linked_list_iterator_init(&it, &l2cap_channels);
998     while (btstack_linked_list_iterator_has_next(&it)){
999         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1000         if ( bd_addr_cmp( channel->address, address) != 0) continue;
1001         // channel for this address found
1002         switch (channel->state){
1003             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
1004             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1005                 // failure, forward error code
1006                 l2cap_emit_channel_opened(channel, status);
1007                 // discard channel
1008                 l2cap_stop_rtx(channel);
1009                 btstack_linked_list_iterator_remove(&it);
1010                 btstack_memory_l2cap_channel_free(channel);
1011                 break;
1012             default:
1013                 break;
1014         }
1015     }
1016 }
1017 
1018 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
1019     btstack_linked_list_iterator_t it;
1020     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1021     while (btstack_linked_list_iterator_has_next(&it)){
1022         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1023         if ( ! bd_addr_cmp( channel->address, address) ){
1024             l2cap_handle_connection_complete(handle, channel);
1025         }
1026     }
1027     // process
1028     l2cap_run();
1029 }
1030 #endif
1031 
1032 static void l2cap_notify_channel_can_send(void){
1033 
1034 #ifdef ENABLE_CLASSIC
1035     btstack_linked_list_iterator_t it;
1036     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1037     while (btstack_linked_list_iterator_has_next(&it)){
1038         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1039         if (!channel->waiting_for_can_send_now) continue;
1040         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
1041         channel->waiting_for_can_send_now = 0;
1042         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
1043     }
1044 #endif
1045 
1046     int i;
1047     for (i=0;i<L2CAP_FIXED_CHANNEL_TABLE_SIZE;i++){
1048         if (!fixed_channels[i].callback) continue;
1049         if (!fixed_channels[i].waiting_for_can_send_now) continue;
1050         int can_send;
1051         if (l2cap_fixed_channel_table_index_is_le(i)){
1052             can_send = hci_can_send_acl_le_packet_now();
1053         } else {
1054             can_send = hci_can_send_acl_classic_packet_now();
1055         }
1056         if (!can_send) continue;
1057         fixed_channels[i].waiting_for_can_send_now = 0;
1058         l2cap_emit_can_send_now(fixed_channels[i].callback, l2cap_fixed_channel_table_channel_id_for_index(i));
1059     }
1060 }
1061 
1062 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
1063 
1064     bd_addr_t address;
1065     hci_con_handle_t handle;
1066     int hci_con_used;
1067     btstack_linked_list_iterator_t it;
1068 
1069     // avoid unused warnings
1070     (void) address;
1071     (void) hci_con_used;
1072     (void) it;
1073 
1074     switch(hci_event_packet_get_type(packet)){
1075 
1076         // Notify channel packet handler if they can send now
1077         case HCI_EVENT_TRANSPORT_PACKET_SENT:
1078         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
1079             l2cap_run();    // try sending signaling packets first
1080             l2cap_notify_channel_can_send();
1081             break;
1082 
1083         case HCI_EVENT_COMMAND_STATUS:
1084             l2cap_run();    // try sending signaling packets first
1085             break;
1086 
1087 #ifdef ENABLE_CLASSIC
1088         // handle connection complete events
1089         case HCI_EVENT_CONNECTION_COMPLETE:
1090             reverse_bd_addr(&packet[5], address);
1091             if (packet[2] == 0){
1092                 handle = little_endian_read_16(packet, 3);
1093                 l2cap_handle_connection_success_for_addr(address, handle);
1094             } else {
1095                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
1096             }
1097             break;
1098 
1099         // handle successful create connection cancel command
1100         case HCI_EVENT_COMMAND_COMPLETE:
1101             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
1102                 if (packet[5] == 0){
1103                     reverse_bd_addr(&packet[6], address);
1104                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
1105                     l2cap_handle_connection_failed_for_addr(address, 0x16);
1106                 }
1107             }
1108             l2cap_run();    // try sending signaling packets first
1109             break;
1110 #endif
1111 
1112         // handle disconnection complete events
1113         case HCI_EVENT_DISCONNECTION_COMPLETE:
1114             // send l2cap disconnect events for all channels on this handle and free them
1115             handle = little_endian_read_16(packet, 3);
1116 #ifdef ENABLE_CLASSIC
1117             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1118             while (btstack_linked_list_iterator_has_next(&it)){
1119                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1120                 if (channel->con_handle != handle) continue;
1121                 l2cap_emit_channel_closed(channel);
1122                 l2cap_stop_rtx(channel);
1123                 btstack_linked_list_iterator_remove(&it);
1124                 btstack_memory_l2cap_channel_free(channel);
1125             }
1126 #endif
1127 #ifdef ENABLE_LE_DATA_CHANNELS
1128             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1129             while (btstack_linked_list_iterator_has_next(&it)){
1130                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1131                 if (channel->con_handle != handle) continue;
1132                 l2cap_emit_channel_closed(channel);
1133                 btstack_linked_list_iterator_remove(&it);
1134                 btstack_memory_l2cap_channel_free(channel);
1135             }
1136 #endif
1137             break;
1138 
1139         // HCI Connection Timeouts
1140 #ifdef ENABLE_CLASSIC
1141         case L2CAP_EVENT_TIMEOUT_CHECK:
1142             handle = little_endian_read_16(packet, 2);
1143             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
1144             if (hci_authentication_active_for_handle(handle)) break;
1145             hci_con_used = 0;
1146             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1147             while (btstack_linked_list_iterator_has_next(&it)){
1148                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1149                 if (channel->con_handle != handle) continue;
1150                 hci_con_used = 1;
1151                 break;
1152             }
1153             if (hci_con_used) break;
1154             if (!hci_can_send_command_packet_now()) break;
1155             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
1156             break;
1157 
1158         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1159             handle = little_endian_read_16(packet, 3);
1160             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1161             while (btstack_linked_list_iterator_has_next(&it)){
1162                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1163                 if (channel->con_handle != handle) continue;
1164                 l2cap_handle_remote_supported_features_received(channel);
1165                 break;
1166             }
1167             break;
1168 
1169         case GAP_EVENT_SECURITY_LEVEL:
1170             handle = little_endian_read_16(packet, 2);
1171             log_info("l2cap - security level update");
1172             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1173             while (btstack_linked_list_iterator_has_next(&it)){
1174                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1175                 if (channel->con_handle != handle) continue;
1176 
1177                 log_info("l2cap - state %u", channel->state);
1178 
1179                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
1180                 gap_security_level_t required_level = channel->required_security_level;
1181 
1182                 switch (channel->state){
1183                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1184                         if (actual_level >= required_level){
1185                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
1186                             l2cap_emit_incoming_connection(channel);
1187                         } else {
1188                             channel->reason = 0x0003; // security block
1189                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
1190                         }
1191                         break;
1192 
1193                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
1194                         if (actual_level >= required_level){
1195                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
1196                         } else {
1197                             // disconnnect, authentication not good enough
1198                             hci_disconnect_security_block(handle);
1199                         }
1200                         break;
1201 
1202                     default:
1203                         break;
1204                 }
1205             }
1206             break;
1207 #endif
1208 
1209         default:
1210             break;
1211     }
1212 
1213     l2cap_run();
1214 }
1215 
1216 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t data){
1217     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused."
1218     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
1219         signaling_responses[signaling_responses_pending].handle = handle;
1220         signaling_responses[signaling_responses_pending].code = code;
1221         signaling_responses[signaling_responses_pending].sig_id = sig_id;
1222         signaling_responses[signaling_responses_pending].data = data;
1223         signaling_responses_pending++;
1224         l2cap_run();
1225     }
1226 }
1227 
1228 #ifdef ENABLE_CLASSIC
1229 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
1230     channel->remote_sig_id = identifier;
1231     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
1232     l2cap_run();
1233 }
1234 
1235 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
1236 
1237     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
1238     l2cap_service_t *service = l2cap_get_service(psm);
1239     if (!service) {
1240         // 0x0002 PSM not supported
1241         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0002);
1242         return;
1243     }
1244 
1245     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
1246     if (!hci_connection) {
1247         //
1248         log_error("no hci_connection for handle %u", handle);
1249         return;
1250     }
1251 
1252     // alloc structure
1253     // log_info("l2cap_handle_connection_request register channel");
1254     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, hci_connection->address, BD_ADDR_TYPE_CLASSIC,
1255     psm, service->mtu, service->required_security_level);
1256     if (!channel){
1257         // 0x0004 No resources available
1258         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0004);
1259         return;
1260     }
1261 
1262     channel->con_handle = handle;
1263     channel->remote_cid = source_cid;
1264     channel->remote_sig_id = sig_id;
1265 
1266     // limit local mtu to max acl packet length - l2cap header
1267     if (channel->local_mtu > l2cap_max_mtu()) {
1268         channel->local_mtu = l2cap_max_mtu();
1269     }
1270 
1271     // set initial state
1272     channel->state =     L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
1273     channel->state_var = L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND;
1274 
1275     // add to connections list
1276     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1277 
1278     // assert security requirements
1279     gap_request_security_level(handle, channel->required_security_level);
1280 }
1281 
1282 void l2cap_accept_connection(uint16_t local_cid){
1283     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
1284     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1285     if (!channel) {
1286         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
1287         return;
1288     }
1289 
1290     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
1291 
1292     // process
1293     l2cap_run();
1294 }
1295 
1296 void l2cap_decline_connection(uint16_t local_cid){
1297     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
1298     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
1299     if (!channel) {
1300         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
1301         return;
1302     }
1303     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
1304     channel->reason = 0x04; // no resources available
1305     l2cap_run();
1306 }
1307 
1308 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
1309 
1310     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1311 
1312     uint16_t flags = little_endian_read_16(command, 6);
1313     if (flags & 1) {
1314         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1315     }
1316 
1317     // accept the other's configuration options
1318     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1319     uint16_t pos     = 8;
1320     while (pos < end_pos){
1321         uint8_t option_hint = command[pos] >> 7;
1322         uint8_t option_type = command[pos] & 0x7f;
1323         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
1324         pos++;
1325         uint8_t length = command[pos++];
1326         // MTU { type(8): 1, len(8):2, MTU(16) }
1327         if (option_type == 1 && length == 2){
1328             channel->remote_mtu = little_endian_read_16(command, pos);
1329             // log_info("l2cap cid 0x%02x, remote mtu %u", channel->local_cid, channel->remote_mtu);
1330             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1331         }
1332         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
1333         if (option_type == 2 && length == 2){
1334             channel->flush_timeout = little_endian_read_16(command, pos);
1335         }
1336         // check for unknown options
1337         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
1338             log_info("l2cap cid %u, unknown options", channel->local_cid);
1339             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
1340         }
1341         pos += length;
1342     }
1343 }
1344 
1345 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
1346     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
1347     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
1348     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
1349     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
1350     if (channel->state == L2CAP_STATE_OPEN) return 0;
1351     return 1;
1352 }
1353 
1354 
1355 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
1356 
1357     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1358     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1359     uint16_t result = 0;
1360 
1361     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
1362 
1363     // handle DISCONNECT REQUESTS seperately
1364     if (code == DISCONNECTION_REQUEST){
1365         switch (channel->state){
1366             case L2CAP_STATE_CONFIG:
1367             case L2CAP_STATE_OPEN:
1368             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1369             case L2CAP_STATE_WAIT_DISCONNECT:
1370                 l2cap_handle_disconnect_request(channel, identifier);
1371                 break;
1372 
1373             default:
1374                 // ignore in other states
1375                 break;
1376         }
1377         return;
1378     }
1379 
1380     // @STATEMACHINE(l2cap)
1381     switch (channel->state) {
1382 
1383         case L2CAP_STATE_WAIT_CONNECT_RSP:
1384             switch (code){
1385                 case CONNECTION_RESPONSE:
1386                     l2cap_stop_rtx(channel);
1387                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1388                     switch (result) {
1389                         case 0:
1390                             // successful connection
1391                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1392                             channel->state = L2CAP_STATE_CONFIG;
1393                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1394                             break;
1395                         case 1:
1396                             // connection pending. get some coffee, but start the ERTX
1397                             l2cap_start_ertx(channel);
1398                             break;
1399                         default:
1400                             // channel closed
1401                             channel->state = L2CAP_STATE_CLOSED;
1402                             // map l2cap connection response result to BTstack status enumeration
1403                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
1404 
1405                             // drop link key if security block
1406                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
1407                                 gap_drop_link_key_for_bd_addr(channel->address);
1408                             }
1409 
1410                             // discard channel
1411                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1412                             btstack_memory_l2cap_channel_free(channel);
1413                             break;
1414                     }
1415                     break;
1416 
1417                 default:
1418                     //@TODO: implement other signaling packets
1419                     break;
1420             }
1421             break;
1422 
1423         case L2CAP_STATE_CONFIG:
1424             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1425             switch (code) {
1426                 case CONFIGURE_REQUEST:
1427                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1428                     l2cap_signaling_handle_configure_request(channel, command);
1429                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
1430                         // only done if continuation not set
1431                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
1432                     }
1433                     break;
1434                 case CONFIGURE_RESPONSE:
1435                     l2cap_stop_rtx(channel);
1436                     switch (result){
1437                         case 0: // success
1438                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
1439                             break;
1440                         case 4: // pending
1441                             l2cap_start_ertx(channel);
1442                             break;
1443                         default:
1444                             // retry on negative result
1445                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1446                             break;
1447                     }
1448                     break;
1449                 default:
1450                     break;
1451             }
1452             if (l2cap_channel_ready_for_open(channel)){
1453                 // for open:
1454                 channel->state = L2CAP_STATE_OPEN;
1455                 l2cap_emit_channel_opened(channel, 0);
1456             }
1457             break;
1458 
1459         case L2CAP_STATE_WAIT_DISCONNECT:
1460             switch (code) {
1461                 case DISCONNECTION_RESPONSE:
1462                     l2cap_finialize_channel_close(channel);
1463                     break;
1464                 default:
1465                     //@TODO: implement other signaling packets
1466                     break;
1467             }
1468             break;
1469 
1470         case L2CAP_STATE_CLOSED:
1471             // @TODO handle incoming requests
1472             break;
1473 
1474         case L2CAP_STATE_OPEN:
1475             //@TODO: implement other signaling packets, e.g. re-configure
1476             break;
1477         default:
1478             break;
1479     }
1480     // log_info("new state %u", channel->state);
1481 }
1482 
1483 
1484 static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
1485 
1486     // get code, signalind identifier and command len
1487     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1488     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1489 
1490     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_REQUEST
1491     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_REQUEST){
1492         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, L2CAP_REJ_CMD_UNKNOWN);
1493         return;
1494     }
1495 
1496     // general commands without an assigned channel
1497     switch(code) {
1498 
1499         case CONNECTION_REQUEST: {
1500             uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1501             uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
1502             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
1503             return;
1504         }
1505 
1506         case ECHO_REQUEST:
1507             l2cap_register_signaling_response(handle, code, sig_id, 0);
1508             return;
1509 
1510         case INFORMATION_REQUEST: {
1511             uint16_t infoType = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1512             l2cap_register_signaling_response(handle, code, sig_id, infoType);
1513             return;
1514         }
1515 
1516         default:
1517             break;
1518     }
1519 
1520 
1521     // Get potential destination CID
1522     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1523 
1524     // Find channel for this sig_id and connection handle
1525     btstack_linked_list_iterator_t it;
1526     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1527     while (btstack_linked_list_iterator_has_next(&it)){
1528         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1529         if (channel->con_handle != handle) continue;
1530         if (code & 1) {
1531             // match odd commands (responses) by previous signaling identifier
1532             if (channel->local_sig_id == sig_id) {
1533                 l2cap_signaling_handler_channel(channel, command);
1534                 break;
1535             }
1536         } else {
1537             // match even commands (requests) by local channel id
1538             if (channel->local_cid == dest_cid) {
1539                 l2cap_signaling_handler_channel(channel, command);
1540                 break;
1541             }
1542         }
1543     }
1544 }
1545 #endif
1546 
1547 #ifdef ENABLE_BLE
1548 
1549 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
1550     uint8_t event[6];
1551     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
1552     event[1] = 4;
1553     little_endian_store_16(event, 2, con_handle);
1554     little_endian_store_16(event, 4, result);
1555     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1556     if (!l2cap_event_packet_handler) return;
1557     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
1558 }
1559 
1560 // @returns valid
1561 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
1562     hci_connection_t * connection;
1563     uint16_t result;
1564     uint8_t  event[10];
1565 
1566 #ifdef ENABLE_LE_DATA_CHANNELS
1567     btstack_linked_list_iterator_t it;
1568     l2cap_channel_t * channel;
1569     uint16_t local_cid;
1570     uint16_t le_psm;
1571     uint16_t new_credits;
1572     uint16_t credits_before;
1573     l2cap_service_t * service;
1574 #endif
1575 
1576     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1577     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u", code, sig_id);
1578 
1579     switch (code){
1580 
1581         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
1582             result = little_endian_read_16(command, 4);
1583             l2cap_emit_connection_parameter_update_response(handle, result);
1584             break;
1585 
1586         case CONNECTION_PARAMETER_UPDATE_REQUEST:
1587             connection = hci_connection_for_handle(handle);
1588             if (connection){
1589                 if (connection->role != HCI_ROLE_MASTER){
1590                     // reject command without notifying upper layer when not in master role
1591                     return 0;
1592                 }
1593                 int update_parameter = 1;
1594                 le_connection_parameter_range_t existing_range;
1595                 gap_get_connection_parameter_range(&existing_range);
1596                 uint16_t le_conn_interval_min = little_endian_read_16(command,8);
1597                 uint16_t le_conn_interval_max = little_endian_read_16(command,10);
1598                 uint16_t le_conn_latency = little_endian_read_16(command,12);
1599                 uint16_t le_supervision_timeout = little_endian_read_16(command,14);
1600 
1601                 if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
1602                 if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
1603 
1604                 if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
1605                 if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
1606 
1607                 if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
1608                 if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
1609 
1610                 if (update_parameter){
1611                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
1612                     connection->le_conn_interval_min = le_conn_interval_min;
1613                     connection->le_conn_interval_max = le_conn_interval_max;
1614                     connection->le_conn_latency = le_conn_latency;
1615                     connection->le_supervision_timeout = le_supervision_timeout;
1616                 } else {
1617                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
1618                 }
1619                 connection->le_con_param_update_identifier = sig_id;
1620             }
1621 
1622             if (!l2cap_event_packet_handler) break;
1623 
1624             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
1625             event[1] = 8;
1626             memcpy(&event[2], &command[4], 8);
1627             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1628             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
1629             break;
1630 
1631 #ifdef ENABLE_LE_DATA_CHANNELS
1632 
1633         case COMMAND_REJECT:
1634             // Find channel for this sig_id and connection handle
1635             channel = NULL;
1636             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1637             while (btstack_linked_list_iterator_has_next(&it)){
1638                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1639                 if (a_channel->con_handle   != handle) continue;
1640                 if (a_channel->local_sig_id != sig_id) continue;
1641                 channel = a_channel;
1642                 break;
1643             }
1644             if (!channel) break;
1645 
1646             // if received while waiting for le connection response, assume legacy device
1647             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
1648                 channel->state = L2CAP_STATE_CLOSED;
1649                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
1650                 l2cap_emit_le_channel_opened(channel, 0x0002);
1651 
1652                 // discard channel
1653                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
1654                 btstack_memory_l2cap_channel_free(channel);
1655                 break;
1656             }
1657             break;
1658 
1659         case LE_CREDIT_BASED_CONNECTION_REQUEST:
1660 
1661             // get hci connection, bail if not found (must not happen)
1662             connection = hci_connection_for_handle(handle);
1663             if (!connection) return 0;
1664 
1665             // check if service registered
1666             le_psm  = little_endian_read_16(command, 4);
1667             service = l2cap_le_get_service(le_psm);
1668 
1669             if (service){
1670 
1671                 uint16_t source_cid = little_endian_read_16(command, 6);
1672                 if (source_cid < 0x40){
1673                     // 0x0009 Connection refused - Invalid Source CID
1674                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0009);
1675                     return 1;
1676                 }
1677 
1678                 // go through list of channels for this ACL connection and check if we get a match
1679                 btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1680                 while (btstack_linked_list_iterator_has_next(&it)){
1681                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1682                     if (a_channel->con_handle != handle) continue;
1683                     if (a_channel->remote_cid != source_cid) continue;
1684                     // 0x000a Connection refused - Source CID already allocated
1685                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x000a);
1686                     return 1;
1687                 }
1688 
1689                 // security: check encryption
1690                 if (service->required_security_level >= LEVEL_2){
1691                     if (sm_encryption_key_size(handle) == 0){
1692                         // 0x0008 Connection refused - insufficient encryption
1693                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0008);
1694                         return 1;
1695                     }
1696                     // anything less than 16 byte key size is insufficient
1697                     if (sm_encryption_key_size(handle) < 16){
1698                         // 0x0007 Connection refused – insufficient encryption key size
1699                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0007);
1700                         return 1;
1701                     }
1702                 }
1703 
1704                 // security: check authencation
1705                 if (service->required_security_level >= LEVEL_3){
1706                     if (!sm_authenticated(handle)){
1707                         // 0x0005 Connection refused – insufficient authentication
1708                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0005);
1709                         return 1;
1710                     }
1711                 }
1712 
1713                 // security: check authorization
1714                 if (service->required_security_level >= LEVEL_4){
1715                     if (sm_authorization_state(handle) != AUTHORIZATION_GRANTED){
1716                         // 0x0006 Connection refused – insufficient authorization
1717                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0006);
1718                         return 1;
1719                     }
1720                 }
1721 
1722                 // allocate channel
1723                 channel = l2cap_create_channel_entry(service->packet_handler, connection->address,
1724                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
1725                 if (!channel){
1726                     // 0x0004 Connection refused – no resources available
1727                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0004);
1728                     return 1;
1729                 }
1730 
1731                 channel->con_handle = handle;
1732                 channel->remote_cid = source_cid;
1733                 channel->remote_sig_id = sig_id;
1734                 channel->remote_mtu = little_endian_read_16(command, 8);
1735                 channel->remote_mps = little_endian_read_16(command, 10);
1736                 channel->credits_outgoing = little_endian_read_16(command, 12);
1737 
1738                 // set initial state
1739                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
1740                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
1741 
1742                 // add to connections list
1743                 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
1744 
1745                 // post connection request event
1746                 l2cap_emit_le_incoming_connection(channel);
1747 
1748             } else {
1749                 // Connection refused – LE_PSM not supported
1750                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0002);
1751             }
1752             break;
1753 
1754         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
1755             // Find channel for this sig_id and connection handle
1756             channel = NULL;
1757             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1758             while (btstack_linked_list_iterator_has_next(&it)){
1759                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1760                 if (a_channel->con_handle   != handle) continue;
1761                 if (a_channel->local_sig_id != sig_id) continue;
1762                 channel = a_channel;
1763                 break;
1764             }
1765             if (!channel) break;
1766 
1767             // cid + 0
1768             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
1769             if (result){
1770                 channel->state = L2CAP_STATE_CLOSED;
1771                 // map l2cap connection response result to BTstack status enumeration
1772                 l2cap_emit_le_channel_opened(channel, result);
1773 
1774                 // discard channel
1775                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
1776                 btstack_memory_l2cap_channel_free(channel);
1777                 break;
1778             }
1779 
1780             // success
1781             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
1782             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
1783             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
1784             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
1785             channel->state = L2CAP_STATE_OPEN;
1786             l2cap_emit_le_channel_opened(channel, result);
1787             break;
1788 
1789         case LE_FLOW_CONTROL_CREDIT:
1790             // find channel
1791             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
1792             channel = l2cap_le_get_channel_for_local_cid(local_cid);
1793             if (!channel) {
1794                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
1795                 break;
1796             }
1797             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
1798             credits_before = channel->credits_outgoing;
1799             channel->credits_outgoing += new_credits;
1800             // check for credit overrun
1801             if (credits_before > channel->credits_outgoing){
1802                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
1803                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1804                 break;
1805             }
1806             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
1807             break;
1808 
1809         case DISCONNECTION_REQUEST:
1810             // find channel
1811             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
1812             channel = l2cap_le_get_channel_for_local_cid(local_cid);
1813             if (!channel) {
1814                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
1815                 break;
1816             }
1817             channel->remote_sig_id = sig_id;
1818             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
1819             break;
1820 
1821 #endif
1822 
1823         case DISCONNECTION_RESPONSE:
1824             break;
1825 
1826         default:
1827             // command unknown -> reject command
1828             return 0;
1829     }
1830     return 1;
1831 }
1832 #endif
1833 
1834 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size ){
1835 
1836     l2cap_channel_t * l2cap_channel;
1837     (void) l2cap_channel;
1838 
1839     // Get Channel ID
1840     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
1841     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
1842 
1843     switch (channel_id) {
1844 
1845 #ifdef ENABLE_CLASSIC
1846         case L2CAP_CID_SIGNALING: {
1847             uint16_t command_offset = 8;
1848             while (command_offset < size) {
1849                 // handle signaling commands
1850                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
1851 
1852                 // increment command_offset
1853                 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1854             }
1855             break;
1856         }
1857 #endif
1858 
1859 #ifdef ENABLE_BLE
1860         case L2CAP_CID_SIGNALING_LE: {
1861             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
1862             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
1863             if (!valid){
1864                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, L2CAP_REJ_CMD_UNKNOWN);
1865             }
1866             break;
1867         }
1868 #endif
1869 
1870         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
1871             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback) {
1872                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1873             }
1874             break;
1875 
1876         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
1877             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback) {
1878                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1879             }
1880             break;
1881 
1882         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
1883             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback) {
1884                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1885             }
1886             break;
1887 
1888         default:
1889 #ifdef ENABLE_CLASSIC
1890             // Find channel for this channel_id and connection handle
1891             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
1892             if (l2cap_channel) {
1893                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1894             }
1895 #endif
1896 #ifdef ENABLE_LE_DATA_CHANNELS
1897             l2cap_channel = l2cap_le_get_channel_for_local_cid(channel_id);
1898             if (l2cap_channel) {
1899                 // credit counting
1900                 if (l2cap_channel->credits_incoming == 0){
1901                     log_error("LE Data Channel packet received but no incoming credits");
1902                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1903                     break;
1904                 }
1905                 l2cap_channel->credits_incoming--;
1906 
1907                 // automatic credits
1908                 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){
1909                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
1910                 }
1911 
1912                 // first fragment
1913                 uint16_t pos = 0;
1914                 if (!l2cap_channel->receive_sdu_len){
1915                     l2cap_channel->receive_sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
1916                     l2cap_channel->receive_sdu_pos = 0;
1917                     pos  += 2;
1918                     size -= 2;
1919                 }
1920                 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], size-COMPLETE_L2CAP_HEADER);
1921                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
1922                 // done?
1923                 log_info("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
1924                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
1925                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
1926                     l2cap_channel->receive_sdu_len = 0;
1927                 }
1928             } else {
1929                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
1930             }
1931 #endif
1932             break;
1933     }
1934 
1935     l2cap_run();
1936 }
1937 
1938 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
1939 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
1940     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
1941     if (index < 0) return;
1942     fixed_channels[index].callback = the_packet_handler;
1943 }
1944 
1945 #ifdef ENABLE_CLASSIC
1946 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
1947 void l2cap_finialize_channel_close(l2cap_channel_t * channel){
1948     channel->state = L2CAP_STATE_CLOSED;
1949     l2cap_emit_channel_closed(channel);
1950     // discard channel
1951     l2cap_stop_rtx(channel);
1952     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1953     btstack_memory_l2cap_channel_free(channel);
1954 }
1955 
1956 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
1957     btstack_linked_list_iterator_t it;
1958     btstack_linked_list_iterator_init(&it, services);
1959     while (btstack_linked_list_iterator_has_next(&it)){
1960         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
1961         if ( service->psm == psm){
1962             return service;
1963         };
1964     }
1965     return NULL;
1966 }
1967 
1968 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
1969     return l2cap_get_service_internal(&l2cap_services, psm);
1970 }
1971 
1972 
1973 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
1974 
1975     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
1976 
1977     // check for alread registered psm
1978     l2cap_service_t *service = l2cap_get_service(psm);
1979     if (service) {
1980         log_error("l2cap_register_service: PSM %u already registered", psm);
1981         return L2CAP_SERVICE_ALREADY_REGISTERED;
1982     }
1983 
1984     // alloc structure
1985     service = btstack_memory_l2cap_service_get();
1986     if (!service) {
1987         log_error("l2cap_register_service: no memory for l2cap_service_t");
1988         return BTSTACK_MEMORY_ALLOC_FAILED;
1989     }
1990 
1991     // fill in
1992     service->psm = psm;
1993     service->mtu = mtu;
1994     service->packet_handler = service_packet_handler;
1995     service->required_security_level = security_level;
1996 
1997     // add to services list
1998     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
1999 
2000     // enable page scan
2001     gap_connectable_control(1);
2002 
2003     return 0;
2004 }
2005 
2006 uint8_t l2cap_unregister_service(uint16_t psm){
2007 
2008     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
2009 
2010     l2cap_service_t *service = l2cap_get_service(psm);
2011     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2012     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
2013     btstack_memory_l2cap_service_free(service);
2014 
2015     // disable page scan when no services registered
2016     if (btstack_linked_list_empty(&l2cap_services)) {
2017         gap_connectable_control(0);
2018     }
2019     return 0;
2020 }
2021 #endif
2022 
2023 
2024 #ifdef ENABLE_LE_DATA_CHANNELS
2025 
2026 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
2027     if (!channel->waiting_for_can_send_now) return;
2028     if (channel->send_sdu_buffer) return;
2029     channel->waiting_for_can_send_now = 0;
2030     log_info("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
2031     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
2032 }
2033 
2034 // 1BH2222
2035 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
2036     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",
2037              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
2038     uint8_t event[19];
2039     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
2040     event[1] = sizeof(event) - 2;
2041     event[2] = channel->address_type;
2042     reverse_bd_addr(channel->address, &event[3]);
2043     little_endian_store_16(event,  9, channel->con_handle);
2044     little_endian_store_16(event, 11, channel->psm);
2045     little_endian_store_16(event, 13, channel->local_cid);
2046     little_endian_store_16(event, 15, channel->remote_cid);
2047     little_endian_store_16(event, 17, channel->remote_mtu);
2048     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2049     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
2050 }
2051 // 11BH22222
2052 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
2053     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",
2054              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
2055              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
2056     uint8_t event[23];
2057     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
2058     event[1] = sizeof(event) - 2;
2059     event[2] = status;
2060     event[3] = channel->address_type;
2061     reverse_bd_addr(channel->address, &event[4]);
2062     little_endian_store_16(event, 10, channel->con_handle);
2063     event[12] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
2064     little_endian_store_16(event, 13, channel->psm);
2065     little_endian_store_16(event, 15, channel->local_cid);
2066     little_endian_store_16(event, 17, channel->remote_cid);
2067     little_endian_store_16(event, 19, channel->local_mtu);
2068     little_endian_store_16(event, 21, channel->remote_mtu);
2069     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2070     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
2071 }
2072 
2073 static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid){
2074     btstack_linked_list_iterator_t it;
2075     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2076     while (btstack_linked_list_iterator_has_next(&it)){
2077         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2078         if ( channel->local_cid == local_cid) {
2079             return channel;
2080         }
2081     }
2082     return NULL;
2083 }
2084 
2085 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
2086 void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
2087     channel->state = L2CAP_STATE_CLOSED;
2088     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
2089     // discard channel
2090     btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2091     btstack_memory_l2cap_channel_free(channel);
2092 }
2093 
2094 static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
2095     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
2096 }
2097 
2098 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
2099 
2100     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
2101 
2102     // check for alread registered psm
2103     l2cap_service_t *service = l2cap_le_get_service(psm);
2104     if (service) {
2105         return L2CAP_SERVICE_ALREADY_REGISTERED;
2106     }
2107 
2108     // alloc structure
2109     service = btstack_memory_l2cap_service_get();
2110     if (!service) {
2111         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
2112         return BTSTACK_MEMORY_ALLOC_FAILED;
2113     }
2114 
2115     // fill in
2116     service->psm = psm;
2117     service->mtu = 0;
2118     service->packet_handler = packet_handler;
2119     service->required_security_level = security_level;
2120 
2121     // add to services list
2122     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
2123 
2124     // done
2125     return 0;
2126 }
2127 
2128 uint8_t l2cap_le_unregister_service(uint16_t psm) {
2129     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
2130     l2cap_service_t *service = l2cap_le_get_service(psm);
2131     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2132 
2133     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
2134     btstack_memory_l2cap_service_free(service);
2135     return 0;
2136 }
2137 
2138 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
2139     // get channel
2140     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2141     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2142 
2143     // validate state
2144     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2145         return ERROR_CODE_COMMAND_DISALLOWED;
2146     }
2147 
2148     // set state accept connection
2149     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
2150     channel->receive_sdu_buffer = receive_sdu_buffer;
2151     channel->local_mtu = mtu;
2152     channel->new_credits_incoming = initial_credits;
2153     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
2154 
2155     // test
2156     // channel->new_credits_incoming = 1;
2157 
2158     // go
2159     l2cap_run();
2160     return 0;
2161 }
2162 
2163 /**
2164  * @brief Deny incoming LE Data Channel connection due to resource constraints
2165  * @param local_cid             L2CAP LE Data Channel Identifier
2166  */
2167 
2168 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
2169     // get channel
2170     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2171     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2172 
2173     // validate state
2174     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2175         return ERROR_CODE_COMMAND_DISALLOWED;
2176     }
2177 
2178     // set state decline connection
2179     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
2180     channel->reason = 0x04; // no resources available
2181     l2cap_run();
2182     return 0;
2183 }
2184 
2185 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
2186     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
2187     uint16_t * out_local_cid) {
2188 
2189     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
2190 
2191 
2192     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2193     if (!connection) {
2194         log_error("no hci_connection for handle 0x%04x", con_handle);
2195         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2196     }
2197 
2198     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, connection->address, connection->address_type, psm, mtu, security_level);
2199     if (!channel) {
2200         return BTSTACK_MEMORY_ALLOC_FAILED;
2201     }
2202     log_info("l2cap_le_create_channel %p", channel);
2203 
2204     // store local_cid
2205     if (out_local_cid){
2206        *out_local_cid = channel->local_cid;
2207     }
2208 
2209     // provide buffer
2210     channel->con_handle = con_handle;
2211     channel->receive_sdu_buffer = receive_sdu_buffer;
2212     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
2213     channel->new_credits_incoming = initial_credits;
2214     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
2215 
2216     // add to connections list
2217     btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2218 
2219     // go
2220     l2cap_run();
2221     return 0;
2222 }
2223 
2224 /**
2225  * @brief Provide credtis for LE Data Channel
2226  * @param local_cid             L2CAP LE Data Channel Identifier
2227  * @param credits               Number additional credits for peer
2228  */
2229 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
2230 
2231     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2232     if (!channel) {
2233         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
2234         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2235     }
2236 
2237     // check state
2238     if (channel->state != L2CAP_STATE_OPEN){
2239         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
2240     }
2241 
2242     // assert incoming credits + credits <= 0xffff
2243     uint32_t total_credits = channel->credits_incoming;
2244     total_credits += channel->new_credits_incoming;
2245     total_credits += credits;
2246     if (total_credits > 0xffff){
2247         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
2248             channel->new_credits_incoming, credits);
2249     }
2250 
2251     // set credits_granted
2252     channel->new_credits_incoming += credits;
2253 
2254     // go
2255     l2cap_run();
2256     return 0;
2257 }
2258 
2259 /**
2260  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
2261  * @param local_cid             L2CAP LE Data Channel Identifier
2262  */
2263 int l2cap_le_can_send_now(uint16_t local_cid){
2264     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2265     if (!channel) {
2266         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
2267         return 0;
2268     }
2269 
2270     // check state
2271     if (channel->state != L2CAP_STATE_OPEN) return 0;
2272 
2273     // check queue
2274     if (channel->send_sdu_buffer) return 0;
2275 
2276     // fine, go ahead
2277     return 1;
2278 }
2279 
2280 /**
2281  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
2282  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
2283  *       so packet handler should be ready to handle it
2284  * @param local_cid             L2CAP LE Data Channel Identifier
2285  */
2286 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
2287     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2288     if (!channel) {
2289         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
2290         return 0;
2291     }
2292     channel->waiting_for_can_send_now = 1;
2293     l2cap_le_notify_channel_can_send(channel);
2294     return 0;
2295 }
2296 
2297 /**
2298  * @brief Send data via LE Data Channel
2299  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
2300  * @param local_cid             L2CAP LE Data Channel Identifier
2301  * @param data                  data to send
2302  * @param size                  data size
2303  */
2304 uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
2305 
2306     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2307     if (!channel) {
2308         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
2309         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2310     }
2311 
2312     if (len > channel->remote_mtu){
2313         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
2314         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
2315     }
2316 
2317     if (channel->send_sdu_buffer){
2318         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
2319         return BTSTACK_ACL_BUFFERS_FULL;
2320     }
2321 
2322     channel->send_sdu_buffer = data;
2323     channel->send_sdu_len    = len;
2324     channel->send_sdu_pos    = 0;
2325 
2326     l2cap_run();
2327     return 0;
2328 }
2329 
2330 /**
2331  * @brief Disconnect from LE Data Channel
2332  * @param local_cid             L2CAP LE Data Channel Identifier
2333  */
2334 uint8_t l2cap_le_disconnect(uint16_t local_cid)
2335 {
2336     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2337     if (!channel) {
2338         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
2339         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2340     }
2341 
2342     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2343     l2cap_run();
2344     return 0;
2345 }
2346 
2347 #endif
2348