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