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