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