xref: /btstack/src/l2cap.c (revision cab29d481bc21e92b2bdbe997cee6c8582348bc1)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 /*
39  *  l2cap.c
40  *
41  *  Logical Link Control and Adaption Protocl (L2CAP)
42  *
43  *  Created by Matthias Ringwald on 5/16/09.
44  */
45 
46 #include "l2cap.h"
47 #include "hci.h"
48 #include "hci_dump.h"
49 #include "btstack_debug.h"
50 #include "btstack_event.h"
51 #include "btstack_memory.h"
52 
53 #ifdef ENABLE_LE_DATA_CHANNELS
54 #include "ble/sm.h"
55 #endif
56 
57 #include <stdarg.h>
58 #include <string.h>
59 
60 #include <stdio.h>
61 
62 // nr of buffered acl packets in outgoing queue to get max performance
63 #define NR_BUFFERED_ACL_PACKETS 3
64 
65 // used to cache l2cap rejects, echo, and informational requests
66 #define NR_PENDING_SIGNALING_RESPONSES 3
67 
68 // nr of credits provided to remote if credits fall below watermark
69 #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK 5
70 #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT 5
71 
72 // offsets for L2CAP SIGNALING COMMANDS
73 #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
74 #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
75 #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
76 #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
77 
78 // internal table
79 #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL 0
80 #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL  1
81 #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL 2
82 #define L2CAP_FIXED_CHANNEL_TABLE_SIZE (L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL+1)
83 
84 // 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_LE_DATA_CHANNELS
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 #ifdef ENABLE_LE_DATA_CHANNELS
733     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
734     while (btstack_linked_list_iterator_has_next(&it)){
735         uint8_t  * acl_buffer;
736         uint8_t  * l2cap_payload;
737         uint16_t pos;
738         uint16_t payload_size;
739         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
740         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
741         switch (channel->state){
742             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
743                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
744                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
745                 // le psm, source cid, mtu, mps, initial credits
746                 channel->local_sig_id = l2cap_next_sig_id();
747                 channel->credits_incoming =  channel->new_credits_incoming;
748                 channel->new_credits_incoming = 0;
749                 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);
750                 break;
751             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
752                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
753                 // TODO: support larger MPS
754                 channel->state = L2CAP_STATE_OPEN;
755                 channel->credits_incoming =  channel->new_credits_incoming;
756                 channel->new_credits_incoming = 0;
757                 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);
758                 // notify client
759                 l2cap_emit_channel_opened(channel, 0);
760                 break;
761             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
762                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
763                 channel->state = L2CAP_STATE_INVALID;
764                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
765                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
766                 l2cap_stop_rtx(channel);
767                 btstack_linked_list_iterator_remove(&it);
768                 btstack_memory_l2cap_channel_free(channel);
769                 break;
770             case L2CAP_STATE_OPEN:
771                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
772 
773                 // send credits
774                 if (channel->new_credits_incoming){
775                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
776                     channel->local_sig_id = l2cap_next_sig_id();
777                     uint16_t new_credits = channel->new_credits_incoming;
778                     channel->new_credits_incoming = 0;
779                     channel->credits_incoming += new_credits;
780                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
781                     break;
782                 }
783 
784                 // send data
785                 if (!channel->send_sdu_buffer) break;
786                 if (!channel->credits_outgoing) break;
787 
788                 // send part of SDU
789                 hci_reserve_packet_buffer();
790                 acl_buffer = hci_get_outgoing_packet_buffer();
791                 l2cap_payload = acl_buffer + 8;
792                 pos = 0;
793                 if (!channel->send_sdu_pos){
794                     // store SDU len
795                     channel->send_sdu_pos += 2;
796                     little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
797                     pos += 2;
798                 }
799                 payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
800                 log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
801                 memcpy(&l2cap_payload[pos], &channel->send_sdu_buffer[channel->send_sdu_pos-2], payload_size); // -2 for virtual SDU len
802                 pos += payload_size;
803                 channel->send_sdu_pos += payload_size;
804                 l2cap_setup_header(acl_buffer, channel->con_handle, channel->remote_cid, pos);
805                 // done
806 
807                 channel->credits_outgoing--;
808 
809                 if (channel->send_sdu_pos >= channel->send_sdu_len + 2){
810                     channel->send_sdu_buffer = NULL;
811                     // TODO: send done event
812                 }
813                 hci_send_acl_packet_buffer(8 + pos);
814                 break;
815             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
816                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
817                 channel->local_sig_id = l2cap_next_sig_id();
818                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
819                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
820                 break;
821             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
822                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
823                 channel->state = L2CAP_STATE_INVALID;
824                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
825                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
826                 break;
827             default:
828                 break;
829         }
830     }
831 
832     // send l2cap con paramter update if necessary
833     hci_connections_get_iterator(&it);
834     while(btstack_linked_list_iterator_has_next(&it)){
835         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
836         if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue;
837         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
838         switch (connection->le_con_parameter_update_state){
839             case CON_PARAMETER_UPDATE_SEND_REQUEST:
840                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
841                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier,
842                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
843                 break;
844             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
845                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
846                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
847                 break;
848             case CON_PARAMETER_UPDATE_DENY:
849                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
850                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
851                 break;
852             default:
853                 break;
854         }
855     }
856 #endif
857 #endif
858 
859     // log_info("l2cap_run: exit");
860 }
861 
862 uint16_t l2cap_max_mtu(void){
863     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
864 }
865 
866 uint16_t l2cap_max_le_mtu(void){
867     return l2cap_max_mtu();
868 }
869 
870 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
871     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
872         log_info("l2cap_handle_connection_complete expected state");
873         // success, start l2cap handshake
874         channel->con_handle = con_handle;
875         // check remote SSP feature first
876         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
877     }
878 }
879 
880 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
881     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
882 
883     // we have been waiting for remote supported features, if both support SSP,
884     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));
885     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
886         // request security level 2
887         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
888         gap_request_security_level(channel->con_handle, LEVEL_2);
889         return;
890     }
891     // fine, go ahead
892     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
893 }
894 
895 static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, bd_addr_t address, bd_addr_type_t address_type,
896     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
897 
898     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
899     if (!channel) {
900         return NULL;
901     }
902 
903      // Init memory (make valgrind happy)
904     memset(channel, 0, sizeof(l2cap_channel_t));
905 
906     // fill in
907     channel->packet_handler = packet_handler;
908     bd_addr_copy(channel->address, address);
909     channel->address_type = address_type;
910     channel->psm = psm;
911     channel->local_mtu  = local_mtu;
912     channel->remote_mtu = L2CAP_MINIMAL_MTU;
913     channel->required_security_level = security_level;
914 
915     //
916     channel->local_cid = l2cap_next_local_cid();
917     channel->con_handle = 0;
918 
919     // set initial state
920     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
921     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
922     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
923     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
924     return channel;
925 }
926 
927 /**
928  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
929  * @param packet_handler
930  * @param address
931  * @param psm
932  * @param mtu
933  * @param local_cid
934  */
935 
936 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){
937     log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x mtu %u", bd_addr_to_str(address), psm, local_mtu);
938 
939     if (local_mtu > l2cap_max_mtu()) {
940         local_mtu = l2cap_max_mtu();
941     }
942 
943     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
944     if (!channel) {
945         return BTSTACK_MEMORY_ALLOC_FAILED;
946     }
947 
948     // add to connections list
949     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
950 
951     // store local_cid
952     if (out_local_cid){
953        *out_local_cid = channel->local_cid;
954     }
955 
956     // check if hci connection is already usable
957     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
958     if (conn){
959         log_info("l2cap_create_channel, hci connection already exists");
960         l2cap_handle_connection_complete(conn->con_handle, channel);
961         // check if remote supported fearures are already received
962         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
963             l2cap_handle_remote_supported_features_received(channel);
964         }
965     }
966 
967     l2cap_run();
968 
969     return 0;
970 }
971 
972 void
973 l2cap_disconnect(uint16_t local_cid, uint8_t reason){
974     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
975     // find channel for local_cid
976     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
977     if (channel) {
978         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
979     }
980     // process
981     l2cap_run();
982 }
983 
984 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
985     btstack_linked_list_iterator_t it;
986     btstack_linked_list_iterator_init(&it, &l2cap_channels);
987     while (btstack_linked_list_iterator_has_next(&it)){
988         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
989         if ( bd_addr_cmp( channel->address, address) != 0) continue;
990         // channel for this address found
991         switch (channel->state){
992             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
993             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
994                 // failure, forward error code
995                 l2cap_emit_channel_opened(channel, status);
996                 // discard channel
997                 l2cap_stop_rtx(channel);
998                 btstack_linked_list_iterator_remove(&it);
999                 btstack_memory_l2cap_channel_free(channel);
1000                 break;
1001             default:
1002                 break;
1003         }
1004     }
1005 }
1006 
1007 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
1008     btstack_linked_list_iterator_t it;
1009     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1010     while (btstack_linked_list_iterator_has_next(&it)){
1011         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1012         if ( ! bd_addr_cmp( channel->address, address) ){
1013             l2cap_handle_connection_complete(handle, channel);
1014         }
1015     }
1016     // process
1017     l2cap_run();
1018 }
1019 
1020 static void l2cap_notify_channel_can_send(void){
1021     btstack_linked_list_iterator_t it;
1022     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1023     while (btstack_linked_list_iterator_has_next(&it)){
1024         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1025         if (!channel->waiting_for_can_send_now) continue;
1026         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
1027         channel->waiting_for_can_send_now = 0;
1028         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
1029     }
1030 
1031     int i;
1032     for (i=0;i<L2CAP_FIXED_CHANNEL_TABLE_SIZE;i++){
1033         if (!fixed_channels[i].callback) continue;
1034         if (!fixed_channels[i].waiting_for_can_send_now) continue;
1035         int can_send;
1036         if (l2cap_fixed_channel_table_index_is_le(i)){
1037             can_send = hci_can_send_acl_le_packet_now();
1038         } else {
1039             can_send = hci_can_send_acl_classic_packet_now();
1040         }
1041         if (!can_send) continue;
1042         fixed_channels[i].waiting_for_can_send_now = 0;
1043         l2cap_emit_can_send_now(fixed_channels[i].callback, l2cap_fixed_channel_table_channel_id_for_index(i));
1044     }
1045 }
1046 
1047 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
1048 
1049     bd_addr_t address;
1050     hci_con_handle_t handle;
1051     btstack_linked_list_iterator_t it;
1052     int hci_con_used;
1053 
1054     switch(hci_event_packet_get_type(packet)){
1055 
1056         // handle connection complete events
1057         case HCI_EVENT_CONNECTION_COMPLETE:
1058             reverse_bd_addr(&packet[5], address);
1059             if (packet[2] == 0){
1060                 handle = little_endian_read_16(packet, 3);
1061                 l2cap_handle_connection_success_for_addr(address, handle);
1062             } else {
1063                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
1064             }
1065             break;
1066 
1067         // handle successful create connection cancel command
1068         case HCI_EVENT_COMMAND_COMPLETE:
1069             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
1070                 if (packet[5] == 0){
1071                     reverse_bd_addr(&packet[6], address);
1072                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
1073                     l2cap_handle_connection_failed_for_addr(address, 0x16);
1074                 }
1075             }
1076             l2cap_run();    // try sending signaling packets first
1077             break;
1078 
1079         case HCI_EVENT_COMMAND_STATUS:
1080             l2cap_run();    // try sending signaling packets first
1081             break;
1082 
1083         // handle disconnection complete events
1084         case HCI_EVENT_DISCONNECTION_COMPLETE:
1085             // send l2cap disconnect events for all channels on this handle and free them
1086             handle = little_endian_read_16(packet, 3);
1087             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1088             while (btstack_linked_list_iterator_has_next(&it)){
1089                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1090                 if (channel->con_handle != handle) continue;
1091                 l2cap_emit_channel_closed(channel);
1092                 l2cap_stop_rtx(channel);
1093                 btstack_linked_list_iterator_remove(&it);
1094                 btstack_memory_l2cap_channel_free(channel);
1095             }
1096 #ifdef ENABLE_BLE
1097             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1098             while (btstack_linked_list_iterator_has_next(&it)){
1099                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1100                 if (channel->con_handle != handle) continue;
1101                 l2cap_emit_channel_closed(channel);
1102                 btstack_linked_list_iterator_remove(&it);
1103                 btstack_memory_l2cap_channel_free(channel);
1104             }
1105 #endif
1106             break;
1107 
1108         // Notify channel packet handler if they can send now
1109         case HCI_EVENT_TRANSPORT_PACKET_SENT:
1110         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
1111             l2cap_run();    // try sending signaling packets first
1112             l2cap_notify_channel_can_send();
1113             break;
1114 
1115         // HCI Connection Timeouts
1116         case L2CAP_EVENT_TIMEOUT_CHECK:
1117             handle = little_endian_read_16(packet, 2);
1118             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
1119             if (hci_authentication_active_for_handle(handle)) break;
1120             hci_con_used = 0;
1121             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1122             while (btstack_linked_list_iterator_has_next(&it)){
1123                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1124                 if (channel->con_handle != handle) continue;
1125                 hci_con_used = 1;
1126                 break;
1127             }
1128             if (hci_con_used) break;
1129             if (!hci_can_send_command_packet_now()) break;
1130             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
1131             break;
1132 
1133         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1134             handle = little_endian_read_16(packet, 3);
1135             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1136             while (btstack_linked_list_iterator_has_next(&it)){
1137                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1138                 if (channel->con_handle != handle) continue;
1139                 l2cap_handle_remote_supported_features_received(channel);
1140                 break;
1141             }
1142             break;
1143 
1144         case GAP_EVENT_SECURITY_LEVEL:
1145             handle = little_endian_read_16(packet, 2);
1146             log_info("l2cap - security level update");
1147             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1148             while (btstack_linked_list_iterator_has_next(&it)){
1149                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1150                 if (channel->con_handle != handle) continue;
1151 
1152                 log_info("l2cap - state %u", channel->state);
1153 
1154                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
1155                 gap_security_level_t required_level = channel->required_security_level;
1156 
1157                 switch (channel->state){
1158                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1159                         if (actual_level >= required_level){
1160                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
1161                             l2cap_emit_connection_request(channel);
1162                         } else {
1163                             channel->reason = 0x0003; // security block
1164                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
1165                         }
1166                         break;
1167 
1168                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
1169                         if (actual_level >= required_level){
1170                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
1171                         } else {
1172                             // disconnnect, authentication not good enough
1173                             hci_disconnect_security_block(handle);
1174                         }
1175                         break;
1176 
1177                     default:
1178                         break;
1179                 }
1180             }
1181             break;
1182 
1183         default:
1184             break;
1185     }
1186 
1187     l2cap_run();
1188 }
1189 
1190 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
1191     channel->remote_sig_id = identifier;
1192     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
1193     l2cap_run();
1194 }
1195 
1196 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t data){
1197     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused."
1198     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
1199         signaling_responses[signaling_responses_pending].handle = handle;
1200         signaling_responses[signaling_responses_pending].code = code;
1201         signaling_responses[signaling_responses_pending].sig_id = sig_id;
1202         signaling_responses[signaling_responses_pending].data = data;
1203         signaling_responses_pending++;
1204         l2cap_run();
1205     }
1206 }
1207 
1208 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
1209 
1210     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
1211     l2cap_service_t *service = l2cap_get_service(psm);
1212     if (!service) {
1213         // 0x0002 PSM not supported
1214         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0002);
1215         return;
1216     }
1217 
1218     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
1219     if (!hci_connection) {
1220         //
1221         log_error("no hci_connection for handle %u", handle);
1222         return;
1223     }
1224 
1225     // alloc structure
1226     // log_info("l2cap_handle_connection_request register channel");
1227     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, hci_connection->address, BD_ADDR_TYPE_CLASSIC,
1228     psm, service->mtu, service->required_security_level);
1229     if (!channel){
1230         // 0x0004 No resources available
1231         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0004);
1232         return;
1233     }
1234 
1235     channel->con_handle = handle;
1236     channel->remote_cid = source_cid;
1237     channel->remote_sig_id = sig_id;
1238 
1239     // limit local mtu to max acl packet length - l2cap header
1240     if (channel->local_mtu > l2cap_max_mtu()) {
1241         channel->local_mtu = l2cap_max_mtu();
1242     }
1243 
1244     // set initial state
1245     channel->state =     L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
1246     channel->state_var = L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND;
1247 
1248     // add to connections list
1249     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1250 
1251     // assert security requirements
1252     gap_request_security_level(handle, channel->required_security_level);
1253 }
1254 
1255 void l2cap_accept_connection(uint16_t local_cid){
1256     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
1257     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1258     if (!channel) {
1259         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
1260         return;
1261     }
1262 
1263     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
1264 
1265     // process
1266     l2cap_run();
1267 }
1268 
1269 void l2cap_decline_connection(uint16_t local_cid){
1270     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
1271     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
1272     if (!channel) {
1273         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
1274         return;
1275     }
1276     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
1277     channel->reason = 0x04; // no resources available
1278     l2cap_run();
1279 }
1280 
1281 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
1282 
1283     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1284 
1285     uint16_t flags = little_endian_read_16(command, 6);
1286     if (flags & 1) {
1287         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1288     }
1289 
1290     // accept the other's configuration options
1291     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1292     uint16_t pos     = 8;
1293     while (pos < end_pos){
1294         uint8_t option_hint = command[pos] >> 7;
1295         uint8_t option_type = command[pos] & 0x7f;
1296         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
1297         pos++;
1298         uint8_t length = command[pos++];
1299         // MTU { type(8): 1, len(8):2, MTU(16) }
1300         if (option_type == 1 && length == 2){
1301             channel->remote_mtu = little_endian_read_16(command, pos);
1302             // log_info("l2cap cid 0x%02x, remote mtu %u", channel->local_cid, channel->remote_mtu);
1303             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1304         }
1305         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
1306         if (option_type == 2 && length == 2){
1307             channel->flush_timeout = little_endian_read_16(command, pos);
1308         }
1309         // check for unknown options
1310         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
1311             log_info("l2cap cid %u, unknown options", channel->local_cid);
1312             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
1313         }
1314         pos += length;
1315     }
1316 }
1317 
1318 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
1319     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
1320     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
1321     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
1322     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
1323     if (channel->state == L2CAP_STATE_OPEN) return 0;
1324     return 1;
1325 }
1326 
1327 
1328 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
1329 
1330     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1331     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1332     uint16_t result = 0;
1333 
1334     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
1335 
1336     // handle DISCONNECT REQUESTS seperately
1337     if (code == DISCONNECTION_REQUEST){
1338         switch (channel->state){
1339             case L2CAP_STATE_CONFIG:
1340             case L2CAP_STATE_OPEN:
1341             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1342             case L2CAP_STATE_WAIT_DISCONNECT:
1343                 l2cap_handle_disconnect_request(channel, identifier);
1344                 break;
1345 
1346             default:
1347                 // ignore in other states
1348                 break;
1349         }
1350         return;
1351     }
1352 
1353     // @STATEMACHINE(l2cap)
1354     switch (channel->state) {
1355 
1356         case L2CAP_STATE_WAIT_CONNECT_RSP:
1357             switch (code){
1358                 case CONNECTION_RESPONSE:
1359                     l2cap_stop_rtx(channel);
1360                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1361                     switch (result) {
1362                         case 0:
1363                             // successful connection
1364                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1365                             channel->state = L2CAP_STATE_CONFIG;
1366                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1367                             break;
1368                         case 1:
1369                             // connection pending. get some coffee, but start the ERTX
1370                             l2cap_start_ertx(channel);
1371                             break;
1372                         default:
1373                             // channel closed
1374                             channel->state = L2CAP_STATE_CLOSED;
1375                             // map l2cap connection response result to BTstack status enumeration
1376                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
1377 
1378                             // drop link key if security block
1379                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
1380                                 gap_drop_link_key_for_bd_addr(channel->address);
1381                             }
1382 
1383                             // discard channel
1384                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1385                             btstack_memory_l2cap_channel_free(channel);
1386                             break;
1387                     }
1388                     break;
1389 
1390                 default:
1391                     //@TODO: implement other signaling packets
1392                     break;
1393             }
1394             break;
1395 
1396         case L2CAP_STATE_CONFIG:
1397             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1398             switch (code) {
1399                 case CONFIGURE_REQUEST:
1400                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1401                     l2cap_signaling_handle_configure_request(channel, command);
1402                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
1403                         // only done if continuation not set
1404                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
1405                     }
1406                     break;
1407                 case CONFIGURE_RESPONSE:
1408                     l2cap_stop_rtx(channel);
1409                     switch (result){
1410                         case 0: // success
1411                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
1412                             break;
1413                         case 4: // pending
1414                             l2cap_start_ertx(channel);
1415                             break;
1416                         default:
1417                             // retry on negative result
1418                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1419                             break;
1420                     }
1421                     break;
1422                 default:
1423                     break;
1424             }
1425             if (l2cap_channel_ready_for_open(channel)){
1426                 // for open:
1427                 channel->state = L2CAP_STATE_OPEN;
1428                 l2cap_emit_channel_opened(channel, 0);
1429             }
1430             break;
1431 
1432         case L2CAP_STATE_WAIT_DISCONNECT:
1433             switch (code) {
1434                 case DISCONNECTION_RESPONSE:
1435                     l2cap_finialize_channel_close(channel);
1436                     break;
1437                 default:
1438                     //@TODO: implement other signaling packets
1439                     break;
1440             }
1441             break;
1442 
1443         case L2CAP_STATE_CLOSED:
1444             // @TODO handle incoming requests
1445             break;
1446 
1447         case L2CAP_STATE_OPEN:
1448             //@TODO: implement other signaling packets, e.g. re-configure
1449             break;
1450         default:
1451             break;
1452     }
1453     // log_info("new state %u", channel->state);
1454 }
1455 
1456 
1457 static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
1458 
1459     // get code, signalind identifier and command len
1460     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1461     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1462 
1463     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_REQUEST
1464     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_REQUEST){
1465         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, L2CAP_REJ_CMD_UNKNOWN);
1466         return;
1467     }
1468 
1469     // general commands without an assigned channel
1470     switch(code) {
1471 
1472         case CONNECTION_REQUEST: {
1473             uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1474             uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
1475             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
1476             return;
1477         }
1478 
1479         case ECHO_REQUEST:
1480             l2cap_register_signaling_response(handle, code, sig_id, 0);
1481             return;
1482 
1483         case INFORMATION_REQUEST: {
1484             uint16_t infoType = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1485             l2cap_register_signaling_response(handle, code, sig_id, infoType);
1486             return;
1487         }
1488 
1489         default:
1490             break;
1491     }
1492 
1493 
1494     // Get potential destination CID
1495     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1496 
1497     // Find channel for this sig_id and connection handle
1498     btstack_linked_list_iterator_t it;
1499     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1500     while (btstack_linked_list_iterator_has_next(&it)){
1501         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1502         if (channel->con_handle != handle) continue;
1503         if (code & 1) {
1504             // match odd commands (responses) by previous signaling identifier
1505             if (channel->local_sig_id == sig_id) {
1506                 l2cap_signaling_handler_channel(channel, command);
1507                 break;
1508             }
1509         } else {
1510             // match even commands (requests) by local channel id
1511             if (channel->local_cid == dest_cid) {
1512                 l2cap_signaling_handler_channel(channel, command);
1513                 break;
1514             }
1515         }
1516     }
1517 }
1518 
1519 #ifdef ENABLE_BLE
1520 // @returns valid
1521 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
1522     hci_connection_t * connection;
1523     uint16_t result;
1524     uint8_t  event[10];
1525     uint16_t local_cid;
1526     l2cap_channel_t * channel;
1527     btstack_linked_list_iterator_t it;
1528 
1529 #ifdef ENABLE_LE_DATA_CHANNELS
1530     uint16_t le_psm;
1531     uint16_t new_credits;
1532     uint16_t credits_before;
1533     l2cap_service_t * service;
1534 #endif
1535 
1536     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1537     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u", code, sig_id);
1538 
1539     switch (code){
1540 
1541         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
1542             result = little_endian_read_16(command, 4);
1543             l2cap_emit_connection_parameter_update_response(handle, result);
1544             break;
1545 
1546         case CONNECTION_PARAMETER_UPDATE_REQUEST:
1547             connection = hci_connection_for_handle(handle);
1548             if (connection){
1549                 if (connection->role != HCI_ROLE_MASTER){
1550                     // reject command without notifying upper layer when not in master role
1551                     return 0;
1552                 }
1553                 int update_parameter = 1;
1554                 le_connection_parameter_range_t existing_range;
1555                 gap_get_connection_parameter_range(&existing_range);
1556                 uint16_t le_conn_interval_min = little_endian_read_16(command,8);
1557                 uint16_t le_conn_interval_max = little_endian_read_16(command,10);
1558                 uint16_t le_conn_latency = little_endian_read_16(command,12);
1559                 uint16_t le_supervision_timeout = little_endian_read_16(command,14);
1560 
1561                 if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
1562                 if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
1563 
1564                 if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
1565                 if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
1566 
1567                 if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
1568                 if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
1569 
1570                 if (update_parameter){
1571                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
1572                     connection->le_conn_interval_min = le_conn_interval_min;
1573                     connection->le_conn_interval_max = le_conn_interval_max;
1574                     connection->le_conn_latency = le_conn_latency;
1575                     connection->le_supervision_timeout = le_supervision_timeout;
1576                 } else {
1577                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
1578                 }
1579                 connection->le_con_param_update_identifier = sig_id;
1580             }
1581 
1582             if (!l2cap_event_packet_handler) break;
1583 
1584             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
1585             event[1] = 8;
1586             memcpy(&event[2], &command[4], 8);
1587             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1588             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
1589             break;
1590 
1591         case COMMAND_REJECT:
1592             // Find channel for this sig_id and connection handle
1593             channel = NULL;
1594             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1595             while (btstack_linked_list_iterator_has_next(&it)){
1596                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1597                 if (a_channel->con_handle   != handle) continue;
1598                 if (a_channel->local_sig_id != sig_id) continue;
1599                 channel = a_channel;
1600                 break;
1601             }
1602             if (!channel) break;
1603 
1604             // if received while waiting for le connection response, assume legacy device
1605             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
1606                 channel->state = L2CAP_STATE_CLOSED;
1607                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
1608                 l2cap_emit_channel_opened(channel, 0x0002);
1609 
1610                 // discard channel
1611                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
1612                 btstack_memory_l2cap_channel_free(channel);
1613                 break;
1614             }
1615             break;
1616 
1617 #ifdef ENABLE_LE_DATA_CHANNELS
1618         case LE_CREDIT_BASED_CONNECTION_REQUEST:
1619 
1620             // get hci connection, bail if not found (must not happen)
1621             connection = hci_connection_for_handle(handle);
1622             if (!connection) return 0;
1623 
1624             // check if service registered
1625             le_psm  = little_endian_read_16(command, 4);
1626             service = l2cap_le_get_service(le_psm);
1627 
1628             if (service){
1629 
1630                 uint16_t source_cid = little_endian_read_16(command, 6);
1631                 if (source_cid < 0x40){
1632                     // 0x0009 Connection refused - Invalid Source CID
1633                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0009);
1634                     return 1;
1635                 }
1636 
1637                 // go through list of channels for this ACL connection and check if we get a match
1638                 btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1639                 while (btstack_linked_list_iterator_has_next(&it)){
1640                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1641                     if (a_channel->con_handle != handle) continue;
1642                     if (a_channel->remote_cid != source_cid) continue;
1643                     // 0x000a Connection refused - Source CID already allocated
1644                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x000a);
1645                     return 1;
1646                 }
1647 
1648                 // security: check encryption
1649                 if (service->required_security_level >= LEVEL_2){
1650                     if (sm_encryption_key_size(handle) == 0){
1651                         // 0x0008 Connection refused - insufficient encryption
1652                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0008);
1653                         return 1;
1654                     }
1655                     // anything less than 16 byte key size is insufficient
1656                     if (sm_encryption_key_size(handle) < 16){
1657                         // 0x0007 Connection refused – insufficient encryption key size
1658                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0007);
1659                         return 1;
1660                     }
1661                 }
1662 
1663                 // security: check authencation
1664                 if (service->required_security_level >= LEVEL_3){
1665                     if (!sm_authenticated(handle)){
1666                         // 0x0005 Connection refused – insufficient authentication
1667                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0005);
1668                         return 1;
1669                     }
1670                 }
1671 
1672                 // security: check authorization
1673                 if (service->required_security_level >= LEVEL_4){
1674                     if (sm_authorization_state(handle) != AUTHORIZATION_GRANTED){
1675                         // 0x0006 Connection refused – insufficient authorization
1676                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0006);
1677                         return 1;
1678                     }
1679                 }
1680 
1681                 // allocate channel
1682                 channel = l2cap_create_channel_entry(service->packet_handler, connection->address,
1683                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
1684                 if (!channel){
1685                     // 0x0004 Connection refused – no resources available
1686                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0004);
1687                     return 1;
1688                 }
1689 
1690                 channel->con_handle = handle;
1691                 channel->remote_cid = source_cid;
1692                 channel->remote_sig_id = sig_id;
1693                 channel->remote_mtu = little_endian_read_16(command, 8);
1694                 channel->remote_mps = little_endian_read_16(command, 10);
1695                 channel->credits_outgoing = little_endian_read_16(command, 12);
1696 
1697                 // set initial state
1698                 channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
1699 
1700                 // add to connections list
1701                 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
1702 
1703                 // post connection request event
1704                 l2cap_emit_connection_request(channel);
1705 
1706             } else {
1707                 // Connection refused – LE_PSM not supported
1708                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, 0x0002);
1709             }
1710             break;
1711 
1712         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
1713             // Find channel for this sig_id and connection handle
1714             channel = NULL;
1715             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1716             while (btstack_linked_list_iterator_has_next(&it)){
1717                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1718                 if (a_channel->con_handle   != handle) continue;
1719                 if (a_channel->local_sig_id != sig_id) continue;
1720                 channel = a_channel;
1721                 break;
1722             }
1723             if (!channel) break;
1724 
1725             // cid + 0
1726             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
1727             if (result){
1728                 channel->state = L2CAP_STATE_CLOSED;
1729                 // map l2cap connection response result to BTstack status enumeration
1730                 l2cap_emit_channel_opened(channel, result);
1731 
1732                 // discard channel
1733                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
1734                 btstack_memory_l2cap_channel_free(channel);
1735                 break;
1736             }
1737 
1738             // success
1739             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
1740             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
1741             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
1742             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
1743             channel->state = L2CAP_STATE_OPEN;
1744             l2cap_emit_channel_opened(channel, result);
1745             break;
1746 
1747         case LE_FLOW_CONTROL_CREDIT:
1748             // find channel
1749             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
1750             channel = l2cap_le_get_channel_for_local_cid(local_cid);
1751             if (!channel) {
1752                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
1753                 break;
1754             }
1755             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
1756             credits_before = channel->credits_outgoing;
1757             channel->credits_outgoing += new_credits;
1758             // check for credit overrun
1759             if (credits_before > channel->credits_outgoing){
1760                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
1761                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1762                 break;
1763             }
1764             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
1765             break;
1766 #endif
1767 
1768         case DISCONNECTION_REQUEST:
1769             // find channel
1770             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
1771             channel = l2cap_le_get_channel_for_local_cid(local_cid);
1772             if (!channel) {
1773                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
1774                 break;
1775             }
1776             channel->remote_sig_id = sig_id;
1777             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
1778             break;
1779 
1780         case DISCONNECTION_RESPONSE:
1781             break;
1782 
1783         default:
1784             // command unknown -> reject command
1785             return 0;
1786     }
1787     return 1;
1788 }
1789 #endif
1790 
1791 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size ){
1792 
1793     // Get Channel ID
1794     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
1795     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
1796 
1797     switch (channel_id) {
1798 
1799         case L2CAP_CID_SIGNALING: {
1800             uint16_t command_offset = 8;
1801             while (command_offset < size) {
1802                 // handle signaling commands
1803                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
1804 
1805                 // increment command_offset
1806                 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1807             }
1808             break;
1809         }
1810 
1811 #ifdef ENABLE_BLE
1812         case L2CAP_CID_SIGNALING_LE: {
1813             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
1814             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
1815             if (!valid){
1816                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, L2CAP_REJ_CMD_UNKNOWN);
1817             }
1818             break;
1819         }
1820 #endif
1821 
1822         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
1823             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback) {
1824                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1825             }
1826             break;
1827 
1828         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
1829             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback) {
1830                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1831             }
1832             break;
1833 
1834         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
1835             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback) {
1836                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1837             }
1838             break;
1839 
1840         default: {
1841             // Find channel for this channel_id and connection handle
1842             l2cap_channel_t * l2cap_channel;
1843             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
1844             if (l2cap_channel) {
1845                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1846             }
1847 #ifdef ENABLE_BLE
1848             l2cap_channel = l2cap_le_get_channel_for_local_cid(channel_id);
1849             if (l2cap_channel) {
1850                 // credit counting
1851                 if (l2cap_channel->credits_incoming == 0){
1852                     log_error("LE Data Channel packet received but no incoming credits");
1853                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1854                     break;
1855                 }
1856                 l2cap_channel->credits_incoming--;
1857 
1858                 // automatic credits
1859                 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){
1860                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
1861                 }
1862 
1863                 // first fragment
1864                 uint16_t pos = 0;
1865                 if (!l2cap_channel->receive_sdu_len){
1866                     l2cap_channel->receive_sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
1867                     l2cap_channel->receive_sdu_pos = 0;
1868                     pos  += 2;
1869                     size -= 2;
1870                 }
1871                 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], size-COMPLETE_L2CAP_HEADER);
1872                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
1873                 // done?
1874                 log_info("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
1875                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
1876                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
1877                     l2cap_channel->receive_sdu_len = 0;
1878                 }
1879             } else {
1880                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
1881             }
1882 #endif
1883             break;
1884         }
1885     }
1886 
1887     l2cap_run();
1888 }
1889 
1890 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
1891 void l2cap_finialize_channel_close(l2cap_channel_t * channel){
1892     channel->state = L2CAP_STATE_CLOSED;
1893     l2cap_emit_channel_closed(channel);
1894     // discard channel
1895     l2cap_stop_rtx(channel);
1896     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1897     btstack_memory_l2cap_channel_free(channel);
1898 }
1899 
1900 #ifdef ENABLE_LE_DATA_CHANNELS
1901 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
1902 void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
1903     channel->state = L2CAP_STATE_CLOSED;
1904     l2cap_emit_channel_closed(channel);
1905     // discard channel
1906     l2cap_stop_rtx(channel);
1907     btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
1908     btstack_memory_l2cap_channel_free(channel);
1909 }
1910 #endif
1911 
1912 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
1913     btstack_linked_list_iterator_t it;
1914     btstack_linked_list_iterator_init(&it, services);
1915     while (btstack_linked_list_iterator_has_next(&it)){
1916         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
1917         if ( service->psm == psm){
1918             return service;
1919         };
1920     }
1921     return NULL;
1922 }
1923 
1924 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
1925     return l2cap_get_service_internal(&l2cap_services, psm);
1926 }
1927 
1928 
1929 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
1930 
1931     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
1932 
1933     // check for alread registered psm
1934     l2cap_service_t *service = l2cap_get_service(psm);
1935     if (service) {
1936         log_error("l2cap_register_service: PSM %u already registered", psm);
1937         return L2CAP_SERVICE_ALREADY_REGISTERED;
1938     }
1939 
1940     // alloc structure
1941     service = btstack_memory_l2cap_service_get();
1942     if (!service) {
1943         log_error("l2cap_register_service: no memory for l2cap_service_t");
1944         return BTSTACK_MEMORY_ALLOC_FAILED;
1945     }
1946 
1947     // fill in
1948     service->psm = psm;
1949     service->mtu = mtu;
1950     service->packet_handler = service_packet_handler;
1951     service->required_security_level = security_level;
1952 
1953     // add to services list
1954     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
1955 
1956     // enable page scan
1957     gap_connectable_control(1);
1958 
1959     return 0;
1960 }
1961 
1962 uint8_t l2cap_unregister_service(uint16_t psm){
1963 
1964     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
1965 
1966     l2cap_service_t *service = l2cap_get_service(psm);
1967     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
1968     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
1969     btstack_memory_l2cap_service_free(service);
1970 
1971     // disable page scan when no services registered
1972     if (btstack_linked_list_empty(&l2cap_services)) {
1973         gap_connectable_control(0);
1974     }
1975     return 0;
1976 }
1977 
1978 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
1979 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
1980     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
1981     if (index < 0) return;
1982     fixed_channels[index].callback = the_packet_handler;
1983 }
1984 
1985 #ifdef ENABLE_BLE
1986 
1987 #ifdef ENABLE_LE_DATA_CHANNELS
1988 
1989 static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
1990     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
1991 }
1992 
1993 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
1994 
1995     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
1996 
1997     // check for alread registered psm
1998     l2cap_service_t *service = l2cap_le_get_service(psm);
1999     if (service) {
2000         return L2CAP_SERVICE_ALREADY_REGISTERED;
2001     }
2002 
2003     // alloc structure
2004     service = btstack_memory_l2cap_service_get();
2005     if (!service) {
2006         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
2007         return BTSTACK_MEMORY_ALLOC_FAILED;
2008     }
2009 
2010     // fill in
2011     service->psm = psm;
2012     service->mtu = 0;
2013     service->packet_handler = packet_handler;
2014     service->required_security_level = security_level;
2015 
2016     // add to services list
2017     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
2018 
2019     // done
2020     return 0;
2021 }
2022 
2023 uint8_t l2cap_le_unregister_service(uint16_t psm) {
2024     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
2025     l2cap_service_t *service = l2cap_le_get_service(psm);
2026     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2027 
2028     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
2029     btstack_memory_l2cap_service_free(service);
2030     return 0;
2031 }
2032 
2033 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
2034     // get channel
2035     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2036     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2037 
2038     // validate state
2039     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2040         return ERROR_CODE_COMMAND_DISALLOWED;
2041     }
2042 
2043     // set state accept connection
2044     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
2045     channel->receive_sdu_buffer = receive_sdu_buffer;
2046     channel->local_mtu = mtu;
2047     channel->new_credits_incoming = initial_credits;
2048     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
2049 
2050     // test
2051     // channel->new_credits_incoming = 1;
2052 
2053     // go
2054     l2cap_run();
2055     return 0;
2056 }
2057 
2058 /**
2059  * @brief Deny incoming LE Data Channel connection due to resource constraints
2060  * @param local_cid             L2CAP LE Data Channel Identifier
2061  */
2062 
2063 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
2064     // get channel
2065     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2066     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2067 
2068     // validate state
2069     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2070         return ERROR_CODE_COMMAND_DISALLOWED;
2071     }
2072 
2073     // set state decline connection
2074     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
2075     channel->reason = 0x04; // no resources available
2076     l2cap_run();
2077     return 0;
2078 }
2079 
2080 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
2081     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
2082     uint16_t * out_local_cid) {
2083 
2084     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
2085 
2086 
2087     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2088     if (!connection) {
2089         log_error("no hci_connection for handle 0x%04x", con_handle);
2090         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2091     }
2092 
2093     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, connection->address, connection->address_type, psm, mtu, security_level);
2094     if (!channel) {
2095         return BTSTACK_MEMORY_ALLOC_FAILED;
2096     }
2097     log_info("l2cap_le_create_channel %p", channel);
2098 
2099     // store local_cid
2100     if (out_local_cid){
2101        *out_local_cid = channel->local_cid;
2102     }
2103 
2104     // provide buffer
2105     channel->con_handle = con_handle;
2106     channel->receive_sdu_buffer = receive_sdu_buffer;
2107     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
2108     channel->new_credits_incoming = initial_credits;
2109     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
2110 
2111     // add to connections list
2112     btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2113 
2114     // go
2115     l2cap_run();
2116     return 0;
2117 }
2118 
2119 /**
2120  * @brief Provide credtis for LE Data Channel
2121  * @param local_cid             L2CAP LE Data Channel Identifier
2122  * @param credits               Number additional credits for peer
2123  */
2124 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
2125 
2126     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2127     if (!channel) {
2128         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
2129         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2130     }
2131 
2132     // check state
2133     if (channel->state != L2CAP_STATE_OPEN){
2134         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
2135     }
2136 
2137     // assert incoming credits + credits <= 0xffff
2138     uint32_t total_credits = channel->credits_incoming;
2139     total_credits += channel->new_credits_incoming;
2140     total_credits += credits;
2141     if (total_credits > 0xffff){
2142         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
2143             channel->new_credits_incoming, credits);
2144     }
2145 
2146     // set credits_granted
2147     channel->new_credits_incoming += credits;
2148 
2149     // go
2150     l2cap_run();
2151     return 0;
2152 }
2153 
2154 /**
2155  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
2156  * @param local_cid             L2CAP LE Data Channel Identifier
2157  */
2158 int l2cap_le_can_send_now(uint16_t local_cid){
2159     // check if data can be sent via le at all
2160     return 0;
2161 }
2162 
2163 /**
2164  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
2165  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
2166  *       so packet handler should be ready to handle it
2167  * @param local_cid             L2CAP LE Data Channel Identifier
2168  */
2169 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
2170     // same as for non-le
2171     return 0;
2172 }
2173 
2174 /**
2175  * @brief Send data via LE Data Channel
2176  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
2177  * @param local_cid             L2CAP LE Data Channel Identifier
2178  * @param data                  data to send
2179  * @param size                  data size
2180  */
2181 uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
2182 
2183     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2184     if (!channel) {
2185         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
2186         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2187     }
2188 
2189     if (len > channel->remote_mtu){
2190         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
2191         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
2192     }
2193 
2194     if (channel->send_sdu_buffer){
2195         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
2196         return BTSTACK_ACL_BUFFERS_FULL;
2197     }
2198 
2199     channel->send_sdu_buffer = data;
2200     channel->send_sdu_len    = len;
2201     channel->send_sdu_pos    = 0;
2202 
2203     l2cap_run();
2204     return 0;
2205 }
2206 
2207 /**
2208  * @brief Disconnect from LE Data Channel
2209  * @param local_cid             L2CAP LE Data Channel Identifier
2210  */
2211 uint8_t l2cap_le_disconnect(uint16_t local_cid)
2212 {
2213     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2214     if (!channel) {
2215         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
2216         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2217     }
2218 
2219     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2220     l2cap_run();
2221     return 0;
2222 }
2223 
2224 #endif
2225 
2226 #endif
2227