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