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