xref: /btstack/src/l2cap.c (revision 43ec931d38cd09f2b72bdcea249f6509262d5eed)
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 // MARK: L2CAP_RUN
567 // process outstanding signaling tasks
568 static void l2cap_run(void){
569 
570     // log_info("l2cap_run: entered");
571 
572     // check pending signaling responses
573     while (signaling_responses_pending){
574 
575         hci_con_handle_t handle = signaling_responses[0].handle;
576 
577         if (!hci_can_send_acl_packet_now(handle)) break;
578 
579         uint8_t  sig_id        = signaling_responses[0].sig_id;
580         uint8_t  response_code = signaling_responses[0].code;
581         uint16_t infoType      = signaling_responses[0].data;  // INFORMATION_REQUEST
582         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
583 #ifdef ENABLE_CLASSIC
584         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
585 #endif
586         UNUSED(infoType);
587 
588         // remove first item before sending (to avoid sending response mutliple times)
589         signaling_responses_pending--;
590         int i;
591         for (i=0; i < signaling_responses_pending; i++){
592             memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t));
593         }
594 
595         switch (response_code){
596 #ifdef ENABLE_CLASSIC
597             case CONNECTION_REQUEST:
598                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
599                 // also disconnect if result is 0x0003 - security blocked
600                 if (result == 0x0003){
601                     hci_disconnect_security_block(handle);
602                 }
603                 break;
604             case ECHO_REQUEST:
605                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
606                 break;
607             case INFORMATION_REQUEST:
608                 switch (infoType){
609                     case 1: { // Connectionless MTU
610                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
611                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(connectionless_mtu), &connectionless_mtu);
612                         }
613                         break;
614                     case 2: { // Extended Features Supported
615                             // extended features request supported, features: fixed channels, unicast connectionless data reception
616                             uint32_t features = 0x280;
617 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
618                             features |= 0x0008;
619 #endif
620                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(features), &features);
621                         }
622                         break;
623                     case 3: { // Fixed Channels Supported
624                             uint8_t map[8];
625                             memset(map, 0, 8);
626                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
627                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(map), &map);
628                         }
629                         break;
630                     default:
631                         // all other types are not supported
632                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
633                         break;
634                 }
635                 break;
636             case COMMAND_REJECT:
637                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
638                 break;
639 #endif
640 #ifdef ENABLE_BLE
641             case LE_CREDIT_BASED_CONNECTION_REQUEST:
642                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
643                 break;
644             case COMMAND_REJECT_LE:
645                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
646                 break;
647 #endif
648             default:
649                 // should not happen
650                 break;
651         }
652     }
653 
654     btstack_linked_list_iterator_t it;
655     UNUSED(it);
656 
657 #ifdef ENABLE_CLASSIC
658     uint8_t  config_options[10];
659     btstack_linked_list_iterator_init(&it, &l2cap_channels);
660     while (btstack_linked_list_iterator_has_next(&it)){
661 
662         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
663         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
664         switch (channel->state){
665 
666             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
667             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
668                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
669                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
670                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
671                     l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
672                 }
673                 break;
674 
675             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
676                 if (!hci_can_send_command_packet_now()) break;
677                 // send connection request - set state first
678                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
679                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
680                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
681                 break;
682 
683             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
684                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
685                 channel->state = L2CAP_STATE_INVALID;
686                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
687                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
688                 l2cap_stop_rtx(channel);
689                 btstack_linked_list_iterator_remove(&it);
690                 btstack_memory_l2cap_channel_free(channel);
691                 break;
692 
693             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
694                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
695                 channel->state = L2CAP_STATE_CONFIG;
696                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
697                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
698                 break;
699 
700             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
701                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
702                 // success, start l2cap handshake
703                 channel->local_sig_id = l2cap_next_sig_id();
704                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
705                 l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
706                 l2cap_start_rtx(channel);
707                 break;
708 
709             case L2CAP_STATE_CONFIG:
710                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
711                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
712                     uint16_t flags = 0;
713                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
714                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
715                         flags = 1;
716                     } else {
717                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
718                     }
719                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
720                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS, 0, NULL);
721                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
722                         config_options[0] = 1; // MTU
723                         config_options[1] = 2; // len param
724                         little_endian_store_16( (uint8_t*)&config_options, 2, channel->remote_mtu);
725                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 4, &config_options);
726                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
727                     } else {
728                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 0, NULL);
729                     }
730                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
731                 }
732                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
733                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
734                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
735                     channel->local_sig_id = l2cap_next_sig_id();
736                     int send_retransmission_and_flow_control_option = 0;
737 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
738                     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
739                         send_retransmission_and_flow_control_option = 1;
740                     }
741 #endif
742                     if (send_retransmission_and_flow_control_option){
743 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
744                         config_options[0] = 0x04;   // RETRANSMISSION AND FLOW CONTROL OPTION
745                         config_options[1] = 9;      // length
746                         config_options[2] = (uint8_t) channel->mode;
747                         config_options[3] = 1;      // TxWindows size
748                         config_options[4] = 1;      // max retransmit
749                         little_endian_store_16( config_options, 5, 100); // Retransmission timeout: 100 ms
750                         little_endian_store_16( config_options, 5, 300); // Monitor timeout: 300 ms
751                         little_endian_store_16( config_options, 7, channel->local_mtu); // Max PDU size
752                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, 10, &config_options);
753 #endif
754                     } else {
755                         config_options[0] = 1; // MTU
756                         config_options[1] = 2; // len param
757                         little_endian_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
758                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, 4, &config_options);
759                     }
760                     l2cap_start_rtx(channel);
761                 }
762                 if (l2cap_channel_ready_for_open(channel)){
763                     channel->state = L2CAP_STATE_OPEN;
764                     l2cap_emit_channel_opened(channel, 0);  // success
765                 }
766                 break;
767 
768             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
769                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
770                 channel->state = L2CAP_STATE_INVALID;
771                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
772                 // 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 :)
773                 l2cap_finialize_channel_close(channel);  // -- remove from list
774                 break;
775 
776             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
777                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
778                 channel->local_sig_id = l2cap_next_sig_id();
779                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
780                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
781                 break;
782             default:
783                 break;
784         }
785     }
786 #endif
787 
788 #ifdef ENABLE_LE_DATA_CHANNELS
789     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
790     while (btstack_linked_list_iterator_has_next(&it)){
791         uint8_t  * acl_buffer;
792         uint8_t  * l2cap_payload;
793         uint16_t pos;
794         uint16_t payload_size;
795         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
796         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
797         switch (channel->state){
798             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
799                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
800                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
801                 // le psm, source cid, mtu, mps, initial credits
802                 channel->local_sig_id = l2cap_next_sig_id();
803                 channel->credits_incoming =  channel->new_credits_incoming;
804                 channel->new_credits_incoming = 0;
805                 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);
806                 break;
807             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
808                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
809                 // TODO: support larger MPS
810                 channel->state = L2CAP_STATE_OPEN;
811                 channel->credits_incoming =  channel->new_credits_incoming;
812                 channel->new_credits_incoming = 0;
813                 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);
814                 // notify client
815                 l2cap_emit_le_channel_opened(channel, 0);
816                 break;
817             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
818                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
819                 channel->state = L2CAP_STATE_INVALID;
820                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
821                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
822                 l2cap_stop_rtx(channel);
823                 btstack_linked_list_iterator_remove(&it);
824                 btstack_memory_l2cap_channel_free(channel);
825                 break;
826             case L2CAP_STATE_OPEN:
827                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
828 
829                 // send credits
830                 if (channel->new_credits_incoming){
831                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
832                     channel->local_sig_id = l2cap_next_sig_id();
833                     uint16_t new_credits = channel->new_credits_incoming;
834                     channel->new_credits_incoming = 0;
835                     channel->credits_incoming += new_credits;
836                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
837                     break;
838                 }
839 
840                 // send data
841                 if (!channel->send_sdu_buffer) break;
842                 if (!channel->credits_outgoing) break;
843 
844                 // send part of SDU
845                 hci_reserve_packet_buffer();
846                 acl_buffer = hci_get_outgoing_packet_buffer();
847                 l2cap_payload = acl_buffer + 8;
848                 pos = 0;
849                 if (!channel->send_sdu_pos){
850                     // store SDU len
851                     channel->send_sdu_pos += 2;
852                     little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
853                     pos += 2;
854                 }
855                 payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
856                 log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
857                 memcpy(&l2cap_payload[pos], &channel->send_sdu_buffer[channel->send_sdu_pos-2], payload_size); // -2 for virtual SDU len
858                 pos += payload_size;
859                 channel->send_sdu_pos += payload_size;
860                 l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
861                 // done
862 
863                 channel->credits_outgoing--;
864 
865                 if (channel->send_sdu_pos >= channel->send_sdu_len + 2){
866                     channel->send_sdu_buffer = NULL;
867                     // send done event
868                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
869                     // inform about can send now
870                     l2cap_le_notify_channel_can_send(channel);
871                 }
872                 hci_send_acl_packet_buffer(8 + pos);
873                 break;
874             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
875                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
876                 channel->local_sig_id = l2cap_next_sig_id();
877                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
878                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
879                 break;
880             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
881                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
882                 channel->state = L2CAP_STATE_INVALID;
883                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
884                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
885                 break;
886             default:
887                 break;
888         }
889     }
890 #endif
891 
892 #ifdef ENABLE_BLE
893     // send l2cap con paramter update if necessary
894     hci_connections_get_iterator(&it);
895     while(btstack_linked_list_iterator_has_next(&it)){
896         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
897         if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue;
898         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
899         switch (connection->le_con_parameter_update_state){
900             case CON_PARAMETER_UPDATE_SEND_REQUEST:
901                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
902                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier,
903                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
904                 break;
905             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
906                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
907                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
908                 break;
909             case CON_PARAMETER_UPDATE_DENY:
910                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
911                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
912                 break;
913             default:
914                 break;
915         }
916     }
917 #endif
918 
919     // log_info("l2cap_run: exit");
920 }
921 
922 #ifdef ENABLE_CLASSIC
923 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
924     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
925         log_info("l2cap_handle_connection_complete expected state");
926         // success, start l2cap handshake
927         channel->con_handle = con_handle;
928         // check remote SSP feature first
929         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
930     }
931 }
932 
933 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
934     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
935 
936     // we have been waiting for remote supported features, if both support SSP,
937     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));
938     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
939         // request security level 2
940         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
941         gap_request_security_level(channel->con_handle, LEVEL_2);
942         return;
943     }
944     // fine, go ahead
945     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
946 }
947 #endif
948 
949 #ifdef L2CAP_USES_CHANNELS
950 static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, bd_addr_t address, bd_addr_type_t address_type,
951     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
952 
953     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
954     if (!channel) {
955         return NULL;
956     }
957 
958      // Init memory (make valgrind happy)
959     memset(channel, 0, sizeof(l2cap_channel_t));
960 
961     // fill in
962     channel->packet_handler = packet_handler;
963     bd_addr_copy(channel->address, address);
964     channel->address_type = address_type;
965     channel->psm = psm;
966     channel->local_mtu  = local_mtu;
967     channel->remote_mtu = L2CAP_MINIMAL_MTU;
968     channel->required_security_level = security_level;
969 
970     //
971     channel->local_cid = l2cap_next_local_cid();
972     channel->con_handle = 0;
973 
974     // set initial state
975     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
976     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
977     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
978     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
979     return channel;
980 }
981 #endif
982 
983 #ifdef ENABLE_CLASSIC
984 
985 /**
986  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
987  * @param packet_handler
988  * @param address
989  * @param psm
990  * @param mtu
991  * @param local_cid
992  */
993 
994 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){
995     // limit MTU to the size of our outtgoing HCI buffer
996     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
997 
998     log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x mtu %u -> local mtu %u", bd_addr_to_str(address), psm, mtu, local_mtu);
999 
1000     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
1001     if (!channel) {
1002         return BTSTACK_MEMORY_ALLOC_FAILED;
1003     }
1004 
1005     // add to connections list
1006     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1007 
1008     // store local_cid
1009     if (out_local_cid){
1010        *out_local_cid = channel->local_cid;
1011     }
1012 
1013     // check if hci connection is already usable
1014     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
1015     if (conn){
1016         log_info("l2cap_create_channel, hci connection already exists");
1017         l2cap_handle_connection_complete(conn->con_handle, channel);
1018         // check if remote supported fearures are already received
1019         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
1020             l2cap_handle_remote_supported_features_received(channel);
1021         }
1022     }
1023 
1024     l2cap_run();
1025 
1026     return 0;
1027 }
1028 
1029 void
1030 l2cap_disconnect(uint16_t local_cid, uint8_t reason){
1031     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
1032     // find channel for local_cid
1033     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1034     if (channel) {
1035         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1036     }
1037     // process
1038     l2cap_run();
1039 }
1040 
1041 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
1042     btstack_linked_list_iterator_t it;
1043     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1044     while (btstack_linked_list_iterator_has_next(&it)){
1045         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1046         if ( bd_addr_cmp( channel->address, address) != 0) continue;
1047         // channel for this address found
1048         switch (channel->state){
1049             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
1050             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1051                 // failure, forward error code
1052                 l2cap_emit_channel_opened(channel, status);
1053                 // discard channel
1054                 l2cap_stop_rtx(channel);
1055                 btstack_linked_list_iterator_remove(&it);
1056                 btstack_memory_l2cap_channel_free(channel);
1057                 break;
1058             default:
1059                 break;
1060         }
1061     }
1062 }
1063 
1064 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
1065     btstack_linked_list_iterator_t it;
1066     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1067     while (btstack_linked_list_iterator_has_next(&it)){
1068         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1069         if ( ! bd_addr_cmp( channel->address, address) ){
1070             l2cap_handle_connection_complete(handle, channel);
1071         }
1072     }
1073     // process
1074     l2cap_run();
1075 }
1076 #endif
1077 
1078 static void l2cap_notify_channel_can_send(void){
1079 
1080 #ifdef ENABLE_CLASSIC
1081     btstack_linked_list_iterator_t it;
1082     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1083     while (btstack_linked_list_iterator_has_next(&it)){
1084         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1085         if (!channel->waiting_for_can_send_now) continue;
1086         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
1087         channel->waiting_for_can_send_now = 0;
1088         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
1089     }
1090 #endif
1091 
1092     int i;
1093     for (i=0;i<L2CAP_FIXED_CHANNEL_TABLE_SIZE;i++){
1094         if (!fixed_channels[i].callback) continue;
1095         if (!fixed_channels[i].waiting_for_can_send_now) continue;
1096         int can_send = 0;
1097         if (l2cap_fixed_channel_table_index_is_le(i)){
1098 #ifdef ENABLE_BLE
1099             can_send = hci_can_send_acl_le_packet_now();
1100 #endif
1101         } else {
1102 #ifdef ENABLE_CLASSIC
1103             can_send = hci_can_send_acl_classic_packet_now();
1104 #endif
1105         }
1106         if (!can_send) continue;
1107         fixed_channels[i].waiting_for_can_send_now = 0;
1108         l2cap_emit_can_send_now(fixed_channels[i].callback, l2cap_fixed_channel_table_channel_id_for_index(i));
1109     }
1110 }
1111 
1112 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
1113 
1114     UNUSED(packet_type);
1115     UNUSED(cid);
1116     UNUSED(size);
1117 
1118     bd_addr_t address;
1119     hci_con_handle_t handle;
1120     int hci_con_used;
1121     btstack_linked_list_iterator_t it;
1122 
1123     // avoid unused warnings
1124     UNUSED(address);
1125     UNUSED(hci_con_used);
1126     UNUSED(it);
1127     UNUSED(handle);
1128 
1129     switch(hci_event_packet_get_type(packet)){
1130 
1131         // Notify channel packet handler if they can send now
1132         case HCI_EVENT_TRANSPORT_PACKET_SENT:
1133         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
1134             l2cap_run();    // try sending signaling packets first
1135             l2cap_notify_channel_can_send();
1136             break;
1137 
1138         case HCI_EVENT_COMMAND_STATUS:
1139             l2cap_run();    // try sending signaling packets first
1140             break;
1141 
1142 #ifdef ENABLE_CLASSIC
1143         // handle connection complete events
1144         case HCI_EVENT_CONNECTION_COMPLETE:
1145             reverse_bd_addr(&packet[5], address);
1146             if (packet[2] == 0){
1147                 handle = little_endian_read_16(packet, 3);
1148                 l2cap_handle_connection_success_for_addr(address, handle);
1149             } else {
1150                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
1151             }
1152             break;
1153 
1154         // handle successful create connection cancel command
1155         case HCI_EVENT_COMMAND_COMPLETE:
1156             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
1157                 if (packet[5] == 0){
1158                     reverse_bd_addr(&packet[6], address);
1159                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
1160                     l2cap_handle_connection_failed_for_addr(address, 0x16);
1161                 }
1162             }
1163             l2cap_run();    // try sending signaling packets first
1164             break;
1165 #endif
1166 
1167         // handle disconnection complete events
1168         case HCI_EVENT_DISCONNECTION_COMPLETE:
1169             // send l2cap disconnect events for all channels on this handle and free them
1170 #ifdef ENABLE_CLASSIC
1171             handle = little_endian_read_16(packet, 3);
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->con_handle != handle) continue;
1176                 l2cap_emit_channel_closed(channel);
1177                 l2cap_stop_rtx(channel);
1178                 btstack_linked_list_iterator_remove(&it);
1179                 btstack_memory_l2cap_channel_free(channel);
1180             }
1181 #endif
1182 #ifdef ENABLE_LE_DATA_CHANNELS
1183             handle = little_endian_read_16(packet, 3);
1184             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1185             while (btstack_linked_list_iterator_has_next(&it)){
1186                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1187                 if (channel->con_handle != handle) continue;
1188                 l2cap_emit_channel_closed(channel);
1189                 btstack_linked_list_iterator_remove(&it);
1190                 btstack_memory_l2cap_channel_free(channel);
1191             }
1192 #endif
1193             break;
1194 
1195         // HCI Connection Timeouts
1196 #ifdef ENABLE_CLASSIC
1197         case L2CAP_EVENT_TIMEOUT_CHECK:
1198             handle = little_endian_read_16(packet, 2);
1199             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
1200             if (hci_authentication_active_for_handle(handle)) break;
1201             hci_con_used = 0;
1202             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1203             while (btstack_linked_list_iterator_has_next(&it)){
1204                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1205                 if (channel->con_handle != handle) continue;
1206                 hci_con_used = 1;
1207                 break;
1208             }
1209             if (hci_con_used) break;
1210             if (!hci_can_send_command_packet_now()) break;
1211             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
1212             break;
1213 
1214         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1215             handle = little_endian_read_16(packet, 3);
1216             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1217             while (btstack_linked_list_iterator_has_next(&it)){
1218                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1219                 if (channel->con_handle != handle) continue;
1220                 l2cap_handle_remote_supported_features_received(channel);
1221                 break;
1222             }
1223             break;
1224 
1225         case GAP_EVENT_SECURITY_LEVEL:
1226             handle = little_endian_read_16(packet, 2);
1227             log_info("l2cap - security level update");
1228             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1229             while (btstack_linked_list_iterator_has_next(&it)){
1230                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1231                 if (channel->con_handle != handle) continue;
1232 
1233                 log_info("l2cap - state %u", channel->state);
1234 
1235                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
1236                 gap_security_level_t required_level = channel->required_security_level;
1237 
1238                 switch (channel->state){
1239                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1240                         if (actual_level >= required_level){
1241                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
1242                             l2cap_emit_incoming_connection(channel);
1243                         } else {
1244                             channel->reason = 0x0003; // security block
1245                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
1246                         }
1247                         break;
1248 
1249                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
1250                         if (actual_level >= required_level){
1251                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
1252                         } else {
1253                             // disconnnect, authentication not good enough
1254                             hci_disconnect_security_block(handle);
1255                         }
1256                         break;
1257 
1258                     default:
1259                         break;
1260                 }
1261             }
1262             break;
1263 #endif
1264 
1265         default:
1266             break;
1267     }
1268 
1269     l2cap_run();
1270 }
1271 
1272 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t cid, uint16_t data){
1273     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused."
1274     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
1275         signaling_responses[signaling_responses_pending].handle = handle;
1276         signaling_responses[signaling_responses_pending].code = code;
1277         signaling_responses[signaling_responses_pending].sig_id = sig_id;
1278         signaling_responses[signaling_responses_pending].cid = cid;
1279         signaling_responses[signaling_responses_pending].data = data;
1280         signaling_responses_pending++;
1281         l2cap_run();
1282     }
1283 }
1284 
1285 #ifdef ENABLE_CLASSIC
1286 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
1287     channel->remote_sig_id = identifier;
1288     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
1289     l2cap_run();
1290 }
1291 
1292 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
1293 
1294     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
1295     l2cap_service_t *service = l2cap_get_service(psm);
1296     if (!service) {
1297         // 0x0002 PSM not supported
1298         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
1299         return;
1300     }
1301 
1302     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
1303     if (!hci_connection) {
1304         //
1305         log_error("no hci_connection for handle %u", handle);
1306         return;
1307     }
1308 
1309     // alloc structure
1310     // log_info("l2cap_handle_connection_request register channel");
1311     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, hci_connection->address, BD_ADDR_TYPE_CLASSIC,
1312     psm, service->mtu, service->required_security_level);
1313     if (!channel){
1314         // 0x0004 No resources available
1315         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
1316         return;
1317     }
1318 
1319     channel->con_handle = handle;
1320     channel->remote_cid = source_cid;
1321     channel->remote_sig_id = sig_id;
1322 
1323     // limit local mtu to max acl packet length - l2cap header
1324     if (channel->local_mtu > l2cap_max_mtu()) {
1325         channel->local_mtu = l2cap_max_mtu();
1326     }
1327 
1328     // set initial state
1329     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
1330     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
1331 
1332     // add to connections list
1333     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1334 
1335     // assert security requirements
1336     gap_request_security_level(handle, channel->required_security_level);
1337 }
1338 
1339 void l2cap_accept_connection(uint16_t local_cid){
1340     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
1341     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1342     if (!channel) {
1343         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
1344         return;
1345     }
1346 
1347 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1348     // configure L2CAP Basic mode
1349     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
1350 #endif
1351 
1352     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
1353 
1354     // process
1355     l2cap_run();
1356 }
1357 
1358 
1359 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1360 void l2cap_accept_ertm_connection(uint16_t local_cid){
1361     log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
1362     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1363     if (!channel) {
1364         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
1365         return;
1366     }
1367 
1368     // configure L2CAP ERTM
1369     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
1370 
1371     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
1372 
1373     // process
1374     l2cap_run();
1375 }
1376 #endif
1377 
1378 
1379 void l2cap_decline_connection(uint16_t local_cid){
1380     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
1381     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
1382     if (!channel) {
1383         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
1384         return;
1385     }
1386     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
1387     channel->reason = 0x04; // no resources available
1388     l2cap_run();
1389 }
1390 
1391 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
1392 
1393     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1394 
1395     uint16_t flags = little_endian_read_16(command, 6);
1396     if (flags & 1) {
1397         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1398     }
1399 
1400     // accept the other's configuration options
1401     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1402     uint16_t pos     = 8;
1403     while (pos < end_pos){
1404         uint8_t option_hint = command[pos] >> 7;
1405         uint8_t option_type = command[pos] & 0x7f;
1406         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
1407         pos++;
1408         uint8_t length = command[pos++];
1409         // MTU { type(8): 1, len(8):2, MTU(16) }
1410         if (option_type == 1 && length == 2){
1411             channel->remote_mtu = little_endian_read_16(command, pos);
1412             if (channel->remote_mtu > l2cap_max_mtu()){
1413                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
1414                 channel->remote_mtu = l2cap_max_mtu();
1415             }
1416             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1417         }
1418         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
1419         if (option_type == 2 && length == 2){
1420             channel->flush_timeout = little_endian_read_16(command, pos);
1421         }
1422         // check for unknown options
1423         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
1424             log_info("l2cap cid %u, unknown options", channel->local_cid);
1425             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
1426         }
1427         pos += length;
1428     }
1429 }
1430 
1431 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
1432     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
1433     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
1434     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
1435     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
1436     if (channel->state == L2CAP_STATE_OPEN) return 0;
1437     return 1;
1438 }
1439 
1440 
1441 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
1442 
1443     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1444     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1445     uint16_t result = 0;
1446 
1447     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
1448 
1449     // handle DISCONNECT REQUESTS seperately
1450     if (code == DISCONNECTION_REQUEST){
1451         switch (channel->state){
1452             case L2CAP_STATE_CONFIG:
1453             case L2CAP_STATE_OPEN:
1454             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1455             case L2CAP_STATE_WAIT_DISCONNECT:
1456                 l2cap_handle_disconnect_request(channel, identifier);
1457                 break;
1458 
1459             default:
1460                 // ignore in other states
1461                 break;
1462         }
1463         return;
1464     }
1465 
1466     // @STATEMACHINE(l2cap)
1467     switch (channel->state) {
1468 
1469         case L2CAP_STATE_WAIT_CONNECT_RSP:
1470             switch (code){
1471                 case CONNECTION_RESPONSE:
1472                     l2cap_stop_rtx(channel);
1473                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1474                     switch (result) {
1475                         case 0:
1476                             // successful connection
1477                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1478                             channel->state = L2CAP_STATE_CONFIG;
1479                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1480                             break;
1481                         case 1:
1482                             // connection pending. get some coffee, but start the ERTX
1483                             l2cap_start_ertx(channel);
1484                             break;
1485                         default:
1486                             // channel closed
1487                             channel->state = L2CAP_STATE_CLOSED;
1488                             // map l2cap connection response result to BTstack status enumeration
1489                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
1490 
1491                             // drop link key if security block
1492                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
1493                                 gap_drop_link_key_for_bd_addr(channel->address);
1494                             }
1495 
1496                             // discard channel
1497                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1498                             btstack_memory_l2cap_channel_free(channel);
1499                             break;
1500                     }
1501                     break;
1502 
1503                 default:
1504                     //@TODO: implement other signaling packets
1505                     break;
1506             }
1507             break;
1508 
1509         case L2CAP_STATE_CONFIG:
1510             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1511             switch (code) {
1512                 case CONFIGURE_REQUEST:
1513                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1514                     l2cap_signaling_handle_configure_request(channel, command);
1515                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
1516                         // only done if continuation not set
1517                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
1518                     }
1519                     break;
1520                 case CONFIGURE_RESPONSE:
1521                     l2cap_stop_rtx(channel);
1522                     switch (result){
1523                         case 0: // success
1524                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
1525                             break;
1526                         case 4: // pending
1527                             l2cap_start_ertx(channel);
1528                             break;
1529                         default:
1530                             // retry on negative result
1531                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1532                             break;
1533                     }
1534                     break;
1535                 default:
1536                     break;
1537             }
1538             if (l2cap_channel_ready_for_open(channel)){
1539                 // for open:
1540                 channel->state = L2CAP_STATE_OPEN;
1541                 l2cap_emit_channel_opened(channel, 0);
1542             }
1543             break;
1544 
1545         case L2CAP_STATE_WAIT_DISCONNECT:
1546             switch (code) {
1547                 case DISCONNECTION_RESPONSE:
1548                     l2cap_finialize_channel_close(channel);
1549                     break;
1550                 default:
1551                     //@TODO: implement other signaling packets
1552                     break;
1553             }
1554             break;
1555 
1556         case L2CAP_STATE_CLOSED:
1557             // @TODO handle incoming requests
1558             break;
1559 
1560         case L2CAP_STATE_OPEN:
1561             //@TODO: implement other signaling packets, e.g. re-configure
1562             break;
1563         default:
1564             break;
1565     }
1566     // log_info("new state %u", channel->state);
1567 }
1568 
1569 
1570 static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
1571 
1572     // get code, signalind identifier and command len
1573     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1574     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1575 
1576     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_REQUEST
1577     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_REQUEST){
1578         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
1579         return;
1580     }
1581 
1582     // general commands without an assigned channel
1583     switch(code) {
1584 
1585         case CONNECTION_REQUEST: {
1586             uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1587             uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
1588             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
1589             return;
1590         }
1591 
1592         case ECHO_REQUEST:
1593             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
1594             return;
1595 
1596         case INFORMATION_REQUEST: {
1597             uint16_t infoType = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1598             l2cap_register_signaling_response(handle, code, sig_id, 0, infoType);
1599             return;
1600         }
1601 
1602         default:
1603             break;
1604     }
1605 
1606 
1607     // Get potential destination CID
1608     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1609 
1610     // Find channel for this sig_id and connection handle
1611     btstack_linked_list_iterator_t it;
1612     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1613     while (btstack_linked_list_iterator_has_next(&it)){
1614         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1615         if (channel->con_handle != handle) continue;
1616         if (code & 1) {
1617             // match odd commands (responses) by previous signaling identifier
1618             if (channel->local_sig_id == sig_id) {
1619                 l2cap_signaling_handler_channel(channel, command);
1620                 break;
1621             }
1622         } else {
1623             // match even commands (requests) by local channel id
1624             if (channel->local_cid == dest_cid) {
1625                 l2cap_signaling_handler_channel(channel, command);
1626                 break;
1627             }
1628         }
1629     }
1630 }
1631 #endif
1632 
1633 #ifdef ENABLE_BLE
1634 
1635 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
1636     uint8_t event[6];
1637     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
1638     event[1] = 4;
1639     little_endian_store_16(event, 2, con_handle);
1640     little_endian_store_16(event, 4, result);
1641     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1642     if (!l2cap_event_packet_handler) return;
1643     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
1644 }
1645 
1646 // @returns valid
1647 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
1648     hci_connection_t * connection;
1649     uint16_t result;
1650     uint8_t  event[10];
1651 
1652 #ifdef ENABLE_LE_DATA_CHANNELS
1653     btstack_linked_list_iterator_t it;
1654     l2cap_channel_t * channel;
1655     uint16_t local_cid;
1656     uint16_t le_psm;
1657     uint16_t new_credits;
1658     uint16_t credits_before;
1659     l2cap_service_t * service;
1660     uint16_t source_cid;
1661 #endif
1662 
1663     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1664     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u", code, sig_id);
1665 
1666     switch (code){
1667 
1668         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
1669             result = little_endian_read_16(command, 4);
1670             l2cap_emit_connection_parameter_update_response(handle, result);
1671             break;
1672 
1673         case CONNECTION_PARAMETER_UPDATE_REQUEST:
1674             connection = hci_connection_for_handle(handle);
1675             if (connection){
1676                 if (connection->role != HCI_ROLE_MASTER){
1677                     // reject command without notifying upper layer when not in master role
1678                     return 0;
1679                 }
1680                 int update_parameter = 1;
1681                 le_connection_parameter_range_t existing_range;
1682                 gap_get_connection_parameter_range(&existing_range);
1683                 uint16_t le_conn_interval_min = little_endian_read_16(command,8);
1684                 uint16_t le_conn_interval_max = little_endian_read_16(command,10);
1685                 uint16_t le_conn_latency = little_endian_read_16(command,12);
1686                 uint16_t le_supervision_timeout = little_endian_read_16(command,14);
1687 
1688                 if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
1689                 if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
1690 
1691                 if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
1692                 if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
1693 
1694                 if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
1695                 if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
1696 
1697                 if (update_parameter){
1698                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
1699                     connection->le_conn_interval_min = le_conn_interval_min;
1700                     connection->le_conn_interval_max = le_conn_interval_max;
1701                     connection->le_conn_latency = le_conn_latency;
1702                     connection->le_supervision_timeout = le_supervision_timeout;
1703                 } else {
1704                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
1705                 }
1706                 connection->le_con_param_update_identifier = sig_id;
1707             }
1708 
1709             if (!l2cap_event_packet_handler) break;
1710 
1711             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
1712             event[1] = 8;
1713             memcpy(&event[2], &command[4], 8);
1714             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1715             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
1716             break;
1717 
1718 #ifdef ENABLE_LE_DATA_CHANNELS
1719 
1720         case COMMAND_REJECT:
1721             // Find channel for this sig_id and connection handle
1722             channel = NULL;
1723             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1724             while (btstack_linked_list_iterator_has_next(&it)){
1725                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1726                 if (a_channel->con_handle   != handle) continue;
1727                 if (a_channel->local_sig_id != sig_id) continue;
1728                 channel = a_channel;
1729                 break;
1730             }
1731             if (!channel) break;
1732 
1733             // if received while waiting for le connection response, assume legacy device
1734             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
1735                 channel->state = L2CAP_STATE_CLOSED;
1736                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
1737                 l2cap_emit_le_channel_opened(channel, 0x0002);
1738 
1739                 // discard channel
1740                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
1741                 btstack_memory_l2cap_channel_free(channel);
1742                 break;
1743             }
1744             break;
1745 
1746         case LE_CREDIT_BASED_CONNECTION_REQUEST:
1747 
1748             // get hci connection, bail if not found (must not happen)
1749             connection = hci_connection_for_handle(handle);
1750             if (!connection) return 0;
1751 
1752             // check if service registered
1753             le_psm  = little_endian_read_16(command, 4);
1754             service = l2cap_le_get_service(le_psm);
1755             source_cid = little_endian_read_16(command, 6);
1756 
1757             if (service){
1758                 if (source_cid < 0x40){
1759                     // 0x0009 Connection refused - Invalid Source CID
1760                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
1761                     return 1;
1762                 }
1763 
1764                 // go through list of channels for this ACL connection and check if we get a match
1765                 btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1766                 while (btstack_linked_list_iterator_has_next(&it)){
1767                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1768                     if (a_channel->con_handle != handle) continue;
1769                     if (a_channel->remote_cid != source_cid) continue;
1770                     // 0x000a Connection refused - Source CID already allocated
1771                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
1772                     return 1;
1773                 }
1774 
1775                 // security: check encryption
1776                 if (service->required_security_level >= LEVEL_2){
1777                     if (sm_encryption_key_size(handle) == 0){
1778                         // 0x0008 Connection refused - insufficient encryption
1779                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
1780                         return 1;
1781                     }
1782                     // anything less than 16 byte key size is insufficient
1783                     if (sm_encryption_key_size(handle) < 16){
1784                         // 0x0007 Connection refused – insufficient encryption key size
1785                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
1786                         return 1;
1787                     }
1788                 }
1789 
1790                 // security: check authencation
1791                 if (service->required_security_level >= LEVEL_3){
1792                     if (!sm_authenticated(handle)){
1793                         // 0x0005 Connection refused – insufficient authentication
1794                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
1795                         return 1;
1796                     }
1797                 }
1798 
1799                 // security: check authorization
1800                 if (service->required_security_level >= LEVEL_4){
1801                     if (sm_authorization_state(handle) != AUTHORIZATION_GRANTED){
1802                         // 0x0006 Connection refused – insufficient authorization
1803                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
1804                         return 1;
1805                     }
1806                 }
1807 
1808                 // allocate channel
1809                 channel = l2cap_create_channel_entry(service->packet_handler, connection->address,
1810                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
1811                 if (!channel){
1812                     // 0x0004 Connection refused – no resources available
1813                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
1814                     return 1;
1815                 }
1816 
1817                 channel->con_handle = handle;
1818                 channel->remote_cid = source_cid;
1819                 channel->remote_sig_id = sig_id;
1820                 channel->remote_mtu = little_endian_read_16(command, 8);
1821                 channel->remote_mps = little_endian_read_16(command, 10);
1822                 channel->credits_outgoing = little_endian_read_16(command, 12);
1823 
1824                 // set initial state
1825                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
1826                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
1827 
1828                 // add to connections list
1829                 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
1830 
1831                 // post connection request event
1832                 l2cap_emit_le_incoming_connection(channel);
1833 
1834             } else {
1835                 // Connection refused – LE_PSM not supported
1836                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
1837             }
1838             break;
1839 
1840         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
1841             // Find channel for this sig_id and connection handle
1842             channel = NULL;
1843             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1844             while (btstack_linked_list_iterator_has_next(&it)){
1845                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1846                 if (a_channel->con_handle   != handle) continue;
1847                 if (a_channel->local_sig_id != sig_id) continue;
1848                 channel = a_channel;
1849                 break;
1850             }
1851             if (!channel) break;
1852 
1853             // cid + 0
1854             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
1855             if (result){
1856                 channel->state = L2CAP_STATE_CLOSED;
1857                 // map l2cap connection response result to BTstack status enumeration
1858                 l2cap_emit_le_channel_opened(channel, result);
1859 
1860                 // discard channel
1861                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
1862                 btstack_memory_l2cap_channel_free(channel);
1863                 break;
1864             }
1865 
1866             // success
1867             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
1868             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
1869             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
1870             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
1871             channel->state = L2CAP_STATE_OPEN;
1872             l2cap_emit_le_channel_opened(channel, result);
1873             break;
1874 
1875         case LE_FLOW_CONTROL_CREDIT:
1876             // find channel
1877             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
1878             channel = l2cap_le_get_channel_for_local_cid(local_cid);
1879             if (!channel) {
1880                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
1881                 break;
1882             }
1883             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
1884             credits_before = channel->credits_outgoing;
1885             channel->credits_outgoing += new_credits;
1886             // check for credit overrun
1887             if (credits_before > channel->credits_outgoing){
1888                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
1889                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1890                 break;
1891             }
1892             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
1893             break;
1894 
1895         case DISCONNECTION_REQUEST:
1896             // find channel
1897             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
1898             channel = l2cap_le_get_channel_for_local_cid(local_cid);
1899             if (!channel) {
1900                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
1901                 break;
1902             }
1903             channel->remote_sig_id = sig_id;
1904             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
1905             break;
1906 
1907 #endif
1908 
1909         case DISCONNECTION_RESPONSE:
1910             break;
1911 
1912         default:
1913             // command unknown -> reject command
1914             return 0;
1915     }
1916     return 1;
1917 }
1918 #endif
1919 
1920 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size ){
1921     UNUSED(packet_type);
1922     UNUSED(channel);
1923 
1924     l2cap_channel_t * l2cap_channel;
1925     UNUSED(l2cap_channel);
1926 
1927     // Get Channel ID
1928     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
1929     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
1930 
1931     switch (channel_id) {
1932 
1933 #ifdef ENABLE_CLASSIC
1934         case L2CAP_CID_SIGNALING: {
1935             uint16_t command_offset = 8;
1936             while (command_offset < size) {
1937                 // handle signaling commands
1938                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
1939 
1940                 // increment command_offset
1941                 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1942             }
1943             break;
1944         }
1945 #endif
1946 
1947 #ifdef ENABLE_BLE
1948         case L2CAP_CID_SIGNALING_LE: {
1949             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
1950             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
1951             if (!valid){
1952                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
1953             }
1954             break;
1955         }
1956 #endif
1957 
1958         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
1959             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback) {
1960                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1961             }
1962             break;
1963 
1964         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
1965             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback) {
1966                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1967             }
1968             break;
1969 
1970         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
1971             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback) {
1972                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1973             }
1974             break;
1975 
1976         default:
1977 #ifdef ENABLE_CLASSIC
1978             // Find channel for this channel_id and connection handle
1979             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
1980             if (l2cap_channel) {
1981                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1982             }
1983 #endif
1984 #ifdef ENABLE_LE_DATA_CHANNELS
1985             l2cap_channel = l2cap_le_get_channel_for_local_cid(channel_id);
1986             if (l2cap_channel) {
1987                 // credit counting
1988                 if (l2cap_channel->credits_incoming == 0){
1989                     log_error("LE Data Channel packet received but no incoming credits");
1990                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1991                     break;
1992                 }
1993                 l2cap_channel->credits_incoming--;
1994 
1995                 // automatic credits
1996                 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){
1997                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
1998                 }
1999 
2000                 // first fragment
2001                 uint16_t pos = 0;
2002                 if (!l2cap_channel->receive_sdu_len){
2003                     l2cap_channel->receive_sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
2004                     l2cap_channel->receive_sdu_pos = 0;
2005                     pos  += 2;
2006                     size -= 2;
2007                 }
2008                 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], size-COMPLETE_L2CAP_HEADER);
2009                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
2010                 // done?
2011                 log_info("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
2012                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
2013                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
2014                     l2cap_channel->receive_sdu_len = 0;
2015                 }
2016             } else {
2017                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
2018             }
2019 #endif
2020             break;
2021     }
2022 
2023     l2cap_run();
2024 }
2025 
2026 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
2027 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
2028     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
2029     if (index < 0) return;
2030     fixed_channels[index].callback = the_packet_handler;
2031 }
2032 
2033 #ifdef ENABLE_CLASSIC
2034 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
2035 void l2cap_finialize_channel_close(l2cap_channel_t * channel){
2036     channel->state = L2CAP_STATE_CLOSED;
2037     l2cap_emit_channel_closed(channel);
2038     // discard channel
2039     l2cap_stop_rtx(channel);
2040     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2041     btstack_memory_l2cap_channel_free(channel);
2042 }
2043 
2044 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
2045     btstack_linked_list_iterator_t it;
2046     btstack_linked_list_iterator_init(&it, services);
2047     while (btstack_linked_list_iterator_has_next(&it)){
2048         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
2049         if ( service->psm == psm){
2050             return service;
2051         };
2052     }
2053     return NULL;
2054 }
2055 
2056 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
2057     return l2cap_get_service_internal(&l2cap_services, psm);
2058 }
2059 
2060 
2061 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
2062 
2063     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
2064 
2065     // check for alread registered psm
2066     l2cap_service_t *service = l2cap_get_service(psm);
2067     if (service) {
2068         log_error("l2cap_register_service: PSM %u already registered", psm);
2069         return L2CAP_SERVICE_ALREADY_REGISTERED;
2070     }
2071 
2072     // alloc structure
2073     service = btstack_memory_l2cap_service_get();
2074     if (!service) {
2075         log_error("l2cap_register_service: no memory for l2cap_service_t");
2076         return BTSTACK_MEMORY_ALLOC_FAILED;
2077     }
2078 
2079     // fill in
2080     service->psm = psm;
2081     service->mtu = mtu;
2082     service->packet_handler = service_packet_handler;
2083     service->required_security_level = security_level;
2084 
2085     // add to services list
2086     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
2087 
2088     // enable page scan
2089     gap_connectable_control(1);
2090 
2091     return 0;
2092 }
2093 
2094 uint8_t l2cap_unregister_service(uint16_t psm){
2095 
2096     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
2097 
2098     l2cap_service_t *service = l2cap_get_service(psm);
2099     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2100     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
2101     btstack_memory_l2cap_service_free(service);
2102 
2103     // disable page scan when no services registered
2104     if (btstack_linked_list_empty(&l2cap_services)) {
2105         gap_connectable_control(0);
2106     }
2107     return 0;
2108 }
2109 #endif
2110 
2111 
2112 #ifdef ENABLE_LE_DATA_CHANNELS
2113 
2114 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
2115     if (!channel->waiting_for_can_send_now) return;
2116     if (channel->send_sdu_buffer) return;
2117     channel->waiting_for_can_send_now = 0;
2118     log_info("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
2119     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
2120 }
2121 
2122 // 1BH2222
2123 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
2124     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",
2125              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
2126     uint8_t event[19];
2127     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
2128     event[1] = sizeof(event) - 2;
2129     event[2] = channel->address_type;
2130     reverse_bd_addr(channel->address, &event[3]);
2131     little_endian_store_16(event,  9, channel->con_handle);
2132     little_endian_store_16(event, 11, channel->psm);
2133     little_endian_store_16(event, 13, channel->local_cid);
2134     little_endian_store_16(event, 15, channel->remote_cid);
2135     little_endian_store_16(event, 17, channel->remote_mtu);
2136     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2137     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
2138 }
2139 // 11BH22222
2140 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
2141     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",
2142              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
2143              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
2144     uint8_t event[23];
2145     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
2146     event[1] = sizeof(event) - 2;
2147     event[2] = status;
2148     event[3] = channel->address_type;
2149     reverse_bd_addr(channel->address, &event[4]);
2150     little_endian_store_16(event, 10, channel->con_handle);
2151     event[12] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
2152     little_endian_store_16(event, 13, channel->psm);
2153     little_endian_store_16(event, 15, channel->local_cid);
2154     little_endian_store_16(event, 17, channel->remote_cid);
2155     little_endian_store_16(event, 19, channel->local_mtu);
2156     little_endian_store_16(event, 21, channel->remote_mtu);
2157     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2158     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
2159 }
2160 
2161 static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid){
2162     btstack_linked_list_iterator_t it;
2163     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2164     while (btstack_linked_list_iterator_has_next(&it)){
2165         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2166         if ( channel->local_cid == local_cid) {
2167             return channel;
2168         }
2169     }
2170     return NULL;
2171 }
2172 
2173 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
2174 void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
2175     channel->state = L2CAP_STATE_CLOSED;
2176     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
2177     // discard channel
2178     btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2179     btstack_memory_l2cap_channel_free(channel);
2180 }
2181 
2182 static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
2183     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
2184 }
2185 
2186 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
2187 
2188     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
2189 
2190     // check for alread registered psm
2191     l2cap_service_t *service = l2cap_le_get_service(psm);
2192     if (service) {
2193         return L2CAP_SERVICE_ALREADY_REGISTERED;
2194     }
2195 
2196     // alloc structure
2197     service = btstack_memory_l2cap_service_get();
2198     if (!service) {
2199         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
2200         return BTSTACK_MEMORY_ALLOC_FAILED;
2201     }
2202 
2203     // fill in
2204     service->psm = psm;
2205     service->mtu = 0;
2206     service->packet_handler = packet_handler;
2207     service->required_security_level = security_level;
2208 
2209     // add to services list
2210     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
2211 
2212     // done
2213     return 0;
2214 }
2215 
2216 uint8_t l2cap_le_unregister_service(uint16_t psm) {
2217     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
2218     l2cap_service_t *service = l2cap_le_get_service(psm);
2219     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2220 
2221     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
2222     btstack_memory_l2cap_service_free(service);
2223     return 0;
2224 }
2225 
2226 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
2227     // get channel
2228     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2229     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2230 
2231     // validate state
2232     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2233         return ERROR_CODE_COMMAND_DISALLOWED;
2234     }
2235 
2236     // set state accept connection
2237     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
2238     channel->receive_sdu_buffer = receive_sdu_buffer;
2239     channel->local_mtu = mtu;
2240     channel->new_credits_incoming = initial_credits;
2241     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
2242 
2243     // test
2244     // channel->new_credits_incoming = 1;
2245 
2246     // go
2247     l2cap_run();
2248     return 0;
2249 }
2250 
2251 /**
2252  * @brief Deny incoming LE Data Channel connection due to resource constraints
2253  * @param local_cid             L2CAP LE Data Channel Identifier
2254  */
2255 
2256 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
2257     // get channel
2258     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2259     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2260 
2261     // validate state
2262     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2263         return ERROR_CODE_COMMAND_DISALLOWED;
2264     }
2265 
2266     // set state decline connection
2267     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
2268     channel->reason = 0x04; // no resources available
2269     l2cap_run();
2270     return 0;
2271 }
2272 
2273 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
2274     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
2275     uint16_t * out_local_cid) {
2276 
2277     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
2278 
2279 
2280     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2281     if (!connection) {
2282         log_error("no hci_connection for handle 0x%04x", con_handle);
2283         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2284     }
2285 
2286     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, connection->address, connection->address_type, psm, mtu, security_level);
2287     if (!channel) {
2288         return BTSTACK_MEMORY_ALLOC_FAILED;
2289     }
2290     log_info("l2cap_le_create_channel %p", channel);
2291 
2292     // store local_cid
2293     if (out_local_cid){
2294        *out_local_cid = channel->local_cid;
2295     }
2296 
2297     // provide buffer
2298     channel->con_handle = con_handle;
2299     channel->receive_sdu_buffer = receive_sdu_buffer;
2300     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
2301     channel->new_credits_incoming = initial_credits;
2302     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
2303 
2304     // add to connections list
2305     btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2306 
2307     // go
2308     l2cap_run();
2309     return 0;
2310 }
2311 
2312 /**
2313  * @brief Provide credtis for LE Data Channel
2314  * @param local_cid             L2CAP LE Data Channel Identifier
2315  * @param credits               Number additional credits for peer
2316  */
2317 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
2318 
2319     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2320     if (!channel) {
2321         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
2322         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2323     }
2324 
2325     // check state
2326     if (channel->state != L2CAP_STATE_OPEN){
2327         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
2328     }
2329 
2330     // assert incoming credits + credits <= 0xffff
2331     uint32_t total_credits = channel->credits_incoming;
2332     total_credits += channel->new_credits_incoming;
2333     total_credits += credits;
2334     if (total_credits > 0xffff){
2335         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
2336             channel->new_credits_incoming, credits);
2337     }
2338 
2339     // set credits_granted
2340     channel->new_credits_incoming += credits;
2341 
2342     // go
2343     l2cap_run();
2344     return 0;
2345 }
2346 
2347 /**
2348  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
2349  * @param local_cid             L2CAP LE Data Channel Identifier
2350  */
2351 int l2cap_le_can_send_now(uint16_t local_cid){
2352     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2353     if (!channel) {
2354         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
2355         return 0;
2356     }
2357 
2358     // check state
2359     if (channel->state != L2CAP_STATE_OPEN) return 0;
2360 
2361     // check queue
2362     if (channel->send_sdu_buffer) return 0;
2363 
2364     // fine, go ahead
2365     return 1;
2366 }
2367 
2368 /**
2369  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
2370  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
2371  *       so packet handler should be ready to handle it
2372  * @param local_cid             L2CAP LE Data Channel Identifier
2373  */
2374 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
2375     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2376     if (!channel) {
2377         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
2378         return 0;
2379     }
2380     channel->waiting_for_can_send_now = 1;
2381     l2cap_le_notify_channel_can_send(channel);
2382     return 0;
2383 }
2384 
2385 /**
2386  * @brief Send data via LE Data Channel
2387  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
2388  * @param local_cid             L2CAP LE Data Channel Identifier
2389  * @param data                  data to send
2390  * @param size                  data size
2391  */
2392 uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
2393 
2394     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2395     if (!channel) {
2396         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
2397         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2398     }
2399 
2400     if (len > channel->remote_mtu){
2401         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
2402         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
2403     }
2404 
2405     if (channel->send_sdu_buffer){
2406         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
2407         return BTSTACK_ACL_BUFFERS_FULL;
2408     }
2409 
2410     channel->send_sdu_buffer = data;
2411     channel->send_sdu_len    = len;
2412     channel->send_sdu_pos    = 0;
2413 
2414     l2cap_run();
2415     return 0;
2416 }
2417 
2418 /**
2419  * @brief Disconnect from LE Data Channel
2420  * @param local_cid             L2CAP LE Data Channel Identifier
2421  */
2422 uint8_t l2cap_le_disconnect(uint16_t local_cid)
2423 {
2424     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2425     if (!channel) {
2426         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
2427         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2428     }
2429 
2430     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2431     l2cap_run();
2432     return 0;
2433 }
2434 
2435 #endif
2436