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