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