xref: /btstack/src/l2cap.c (revision 72b5080138ca1eba9e375ff9ba0b384dc8c9f3b3)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 /*
39  *  l2cap.c
40  *
41  *  Logical Link Control and Adaption Protocl (L2CAP)
42  *
43  *  Created by Matthias Ringwald on 5/16/09.
44  */
45 
46 #include "l2cap.h"
47 #include "hci.h"
48 #include "hci_dump.h"
49 #include "btstack_debug.h"
50 #include "btstack_memory.h"
51 
52 #include <stdarg.h>
53 #include <string.h>
54 
55 #include <stdio.h>
56 
57 // nr of buffered acl packets in outgoing queue to get max performance
58 #define NR_BUFFERED_ACL_PACKETS 3
59 
60 // used to cache l2cap rejects, echo, and informational requests
61 #define NR_PENDING_SIGNALING_RESPONSES 3
62 
63 // offsets for L2CAP SIGNALING COMMANDS
64 #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
65 #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
66 #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
67 #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
68 
69 static void null_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
70 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size);
71 
72 // used to cache l2cap rejects, echo, and informational requests
73 static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
74 static int signaling_responses_pending;
75 
76 static btstack_packet_callback_registration_t hci_event_callback_registration;
77 
78 static btstack_linked_list_t l2cap_channels;
79 static btstack_linked_list_t l2cap_services;
80 static btstack_linked_list_t l2cap_le_channels;
81 static btstack_linked_list_t l2cap_le_services;
82 static void (*packet_handler) (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) = null_packet_handler;
83 
84 static btstack_packet_handler_t attribute_protocol_packet_handler;
85 static btstack_packet_handler_t security_protocol_packet_handler;
86 static btstack_packet_handler_t connectionless_channel_packet_handler;
87 static uint8_t require_security_level2_for_outgoing_sdp;
88 
89 // prototypes
90 static void l2cap_finialize_channel_close(l2cap_channel_t *channel);
91 static inline l2cap_service_t * l2cap_get_service(uint16_t psm);
92 static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
93 static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
94 static void l2cap_emit_connection_request(l2cap_channel_t *channel);
95 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel);
96 
97 
98 void l2cap_init(void){
99     signaling_responses_pending = 0;
100 
101     l2cap_channels = NULL;
102     l2cap_services = NULL;
103     l2cap_le_services = NULL;
104     l2cap_le_channels = NULL;
105 
106     packet_handler = null_packet_handler;
107     attribute_protocol_packet_handler = NULL;
108     security_protocol_packet_handler = NULL;
109     connectionless_channel_packet_handler = NULL;
110 
111     require_security_level2_for_outgoing_sdp = 0;
112 
113     //
114     // register callback with HCI
115     //
116     hci_event_callback_registration.callback = &l2cap_packet_handler;
117     hci_add_event_handler(&hci_event_callback_registration);
118 
119     hci_register_acl_packet_handler(&l2cap_packet_handler);
120 
121     hci_connectable_control(0); // no services yet
122 }
123 
124 
125 /** Register L2CAP packet handlers */
126 static void null_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
127 }
128 void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
129     packet_handler = handler;
130 }
131 
132 //  notify client/protocol handler
133 static void l2cap_dispatch(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
134     if (channel->packet_handler) {
135         (* (channel->packet_handler))(type, channel->local_cid, data, size);
136     } else {
137         (*packet_handler)(type, channel->local_cid, data, size);
138     }
139 }
140 
141 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
142     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",
143              status, bd_addr_to_str(channel->address), channel->handle, channel->psm,
144              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
145     uint8_t event[23];
146     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
147     event[1] = sizeof(event) - 2;
148     event[2] = status;
149     bt_flip_addr(&event[3], channel->address);
150     little_endian_store_16(event,  9, channel->handle);
151     little_endian_store_16(event, 11, channel->psm);
152     little_endian_store_16(event, 13, channel->local_cid);
153     little_endian_store_16(event, 15, channel->remote_cid);
154     little_endian_store_16(event, 17, channel->local_mtu);
155     little_endian_store_16(event, 19, channel->remote_mtu);
156     little_endian_store_16(event, 21, channel->flush_timeout);
157     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
158     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
159 }
160 
161 void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
162     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
163     uint8_t event[4];
164     event[0] = L2CAP_EVENT_CHANNEL_CLOSED;
165     event[1] = sizeof(event) - 2;
166     little_endian_store_16(event, 2, channel->local_cid);
167     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
168     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
169 }
170 
171 void l2cap_emit_connection_request(l2cap_channel_t *channel) {
172     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
173              bd_addr_to_str(channel->address), channel->handle,  channel->psm, channel->local_cid, channel->remote_cid);
174     uint8_t event[16];
175     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
176     event[1] = sizeof(event) - 2;
177     bt_flip_addr(&event[2], channel->address);
178     little_endian_store_16(event,  8, channel->handle);
179     little_endian_store_16(event, 10, channel->psm);
180     little_endian_store_16(event, 12, channel->local_cid);
181     little_endian_store_16(event, 14, channel->remote_cid);
182     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
183     l2cap_dispatch(channel, HCI_EVENT_PACKET, event, sizeof(event));
184 }
185 
186 static void l2cap_emit_connection_parameter_update_response(uint16_t handle, uint16_t result){
187     uint8_t event[6];
188     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
189     event[1] = 4;
190     little_endian_store_16(event, 2, handle);
191     little_endian_store_16(event, 4, result);
192     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
193     (*packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
194 }
195 
196 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
197     btstack_linked_list_iterator_t it;
198     btstack_linked_list_iterator_init(&it, &l2cap_channels);
199     while (btstack_linked_list_iterator_has_next(&it)){
200         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
201         if ( channel->local_cid == local_cid) {
202             return channel;
203         }
204     }
205     return NULL;
206 }
207 
208 int  l2cap_can_send_packet_now(uint16_t local_cid){
209     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
210     if (!channel) return 0;
211     return hci_can_send_acl_packet_now(channel->handle);
212 }
213 
214 int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
215     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
216     if (!channel) return 0;
217     return hci_can_send_prepared_acl_packet_now(channel->handle);
218 }
219 
220 int  l2cap_can_send_fixed_channel_packet_now(uint16_t handle){
221     return hci_can_send_acl_packet_now(handle);
222 }
223 
224 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
225     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
226     if (channel) {
227         return channel->remote_mtu;
228     }
229     return 0;
230 }
231 
232 static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
233     btstack_linked_list_iterator_t it;
234     btstack_linked_list_iterator_init(&it, &l2cap_channels);
235     while (btstack_linked_list_iterator_has_next(&it)){
236         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
237         if ( &channel->rtx == ts) {
238             return channel;
239         }
240     }
241     return NULL;
242 }
243 
244 static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
245     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
246     if (!ts) return;
247 
248     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
249 
250     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
251     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
252     // notify client
253     l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
254 
255     // discard channel
256     // no need to stop timer here, it is removed from list during timer callback
257     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
258     btstack_memory_l2cap_channel_free(channel);
259 }
260 
261 static void l2cap_stop_rtx(l2cap_channel_t * channel){
262     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
263     btstack_run_loop_remove_timer(&channel->rtx);
264 }
265 
266 static void l2cap_start_rtx(l2cap_channel_t * channel){
267     l2cap_stop_rtx(channel);
268     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
269     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
270     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
271     btstack_run_loop_add_timer(&channel->rtx);
272 }
273 
274 static void l2cap_start_ertx(l2cap_channel_t * channel){
275     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
276     l2cap_stop_rtx(channel);
277     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
278     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
279     btstack_run_loop_add_timer(&channel->rtx);
280 }
281 
282 void l2cap_require_security_level_2_for_outgoing_sdp(void){
283     require_security_level2_for_outgoing_sdp = 1;
284 }
285 
286 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
287     return (psm == PSM_SDP) && (!require_security_level2_for_outgoing_sdp);
288 }
289 
290 static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
291 
292     if (!hci_can_send_acl_packet_now(handle)){
293         log_info("l2cap_send_signaling_packet, cannot send");
294         return BTSTACK_ACL_BUFFERS_FULL;
295     }
296 
297     // log_info("l2cap_send_signaling_packet type %u", cmd);
298     hci_reserve_packet_buffer();
299     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
300     va_list argptr;
301     va_start(argptr, identifier);
302     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
303     va_end(argptr);
304     // log_info("l2cap_send_signaling_packet con %u!", handle);
305     return hci_send_acl_packet_buffer(len);
306 }
307 
308 #ifdef ENABLE_BLE
309 static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
310 
311     if (!hci_can_send_acl_packet_now(handle)){
312         log_info("l2cap_send_signaling_packet, cannot send");
313         return BTSTACK_ACL_BUFFERS_FULL;
314     }
315 
316     // log_info("l2cap_send_signaling_packet type %u", cmd);
317     hci_reserve_packet_buffer();
318     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
319     va_list argptr;
320     va_start(argptr, identifier);
321     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
322     va_end(argptr);
323     // log_info("l2cap_send_signaling_packet con %u!", handle);
324     return hci_send_acl_packet_buffer(len);
325 }
326 #endif
327 
328 uint8_t *l2cap_get_outgoing_buffer(void){
329     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
330 }
331 
332 int l2cap_reserve_packet_buffer(void){
333     return hci_reserve_packet_buffer();
334 }
335 
336 void l2cap_release_packet_buffer(void){
337     hci_release_packet_buffer();
338 }
339 
340 
341 int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
342 
343     if (!hci_is_packet_buffer_reserved()){
344         log_error("l2cap_send_prepared called without reserving packet first");
345         return BTSTACK_ACL_BUFFERS_FULL;
346     }
347 
348     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
349     if (!channel) {
350         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
351         return -1;   // TODO: define error
352     }
353 
354     if (!hci_can_send_prepared_acl_packet_now(channel->handle)){
355         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
356         return BTSTACK_ACL_BUFFERS_FULL;
357     }
358 
359     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->handle);
360 
361     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
362 
363     int pb = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
364 
365     // 0 - Connection handle : PB=pb : BC=00
366     little_endian_store_16(acl_buffer, 0, channel->handle | (pb << 12) | (0 << 14));
367     // 2 - ACL length
368     little_endian_store_16(acl_buffer, 2,  len + 4);
369     // 4 - L2CAP packet length
370     little_endian_store_16(acl_buffer, 4,  len + 0);
371     // 6 - L2CAP channel DEST
372     little_endian_store_16(acl_buffer, 6, channel->remote_cid);
373     // send
374     int err = hci_send_acl_packet_buffer(len+8);
375 
376     return err;
377 }
378 
379 int l2cap_send_prepared_connectionless(uint16_t handle, uint16_t cid, uint16_t len){
380 
381     if (!hci_is_packet_buffer_reserved()){
382         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
383         return BTSTACK_ACL_BUFFERS_FULL;
384     }
385 
386     if (!hci_can_send_prepared_acl_packet_now(handle)){
387         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", handle, cid);
388         return BTSTACK_ACL_BUFFERS_FULL;
389     }
390 
391     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", handle, cid);
392 
393     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
394 
395     int pb = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
396 
397     // 0 - Connection handle : PB=pb : BC=00
398     little_endian_store_16(acl_buffer, 0, handle | (pb << 12) | (0 << 14));
399     // 2 - ACL length
400     little_endian_store_16(acl_buffer, 2,  len + 4);
401     // 4 - L2CAP packet length
402     little_endian_store_16(acl_buffer, 4,  len + 0);
403     // 6 - L2CAP channel DEST
404     little_endian_store_16(acl_buffer, 6, cid);
405     // send
406     int err = hci_send_acl_packet_buffer(len+8);
407 
408     return err;
409 }
410 
411 int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
412 
413     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
414     if (!channel) {
415         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
416         return -1;   // TODO: define error
417     }
418 
419     if (len > channel->remote_mtu){
420         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
421         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
422     }
423 
424     if (!hci_can_send_acl_packet_now(channel->handle)){
425         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
426         return BTSTACK_ACL_BUFFERS_FULL;
427     }
428 
429     hci_reserve_packet_buffer();
430     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
431 
432     memcpy(&acl_buffer[8], data, len);
433 
434     return l2cap_send_prepared(local_cid, len);
435 }
436 
437 int l2cap_send_connectionless(uint16_t handle, uint16_t cid, uint8_t *data, uint16_t len){
438 
439     if (!hci_can_send_acl_packet_now(handle)){
440         log_info("l2cap_send cid 0x%02x, cannot send", cid);
441         return BTSTACK_ACL_BUFFERS_FULL;
442     }
443 
444     hci_reserve_packet_buffer();
445     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
446 
447     memcpy(&acl_buffer[8], data, len);
448 
449     return l2cap_send_prepared_connectionless(handle, cid, len);
450 }
451 
452 int l2cap_send_echo_request(uint16_t handle, uint8_t *data, uint16_t len){
453     return l2cap_send_signaling_packet(handle, ECHO_REQUEST, 0x77, len, data);
454 }
455 
456 static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
457     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
458 }
459 
460 static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
461     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
462 }
463 
464 
465 
466 // MARK: L2CAP_RUN
467 // process outstanding signaling tasks
468 static void l2cap_run(void){
469 
470     // log_info("l2cap_run: entered");
471 
472     // check pending signaling responses
473     while (signaling_responses_pending){
474 
475         hci_con_handle_t handle = signaling_responses[0].handle;
476 
477         if (!hci_can_send_acl_packet_now(handle)) break;
478 
479         uint8_t  sig_id = signaling_responses[0].sig_id;
480         uint16_t infoType = signaling_responses[0].data;    // INFORMATION_REQUEST
481         uint16_t result   = signaling_responses[0].data;    // CONNECTION_REQUEST, COMMAND_REJECT
482         uint8_t  response_code = signaling_responses[0].code;
483 
484         // remove first item before sending (to avoid sending response mutliple times)
485         signaling_responses_pending--;
486         int i;
487         for (i=0; i < signaling_responses_pending; i++){
488             memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t));
489         }
490 
491         switch (response_code){
492             case CONNECTION_REQUEST:
493                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, 0, 0, result, 0);
494                 // also disconnect if result is 0x0003 - security blocked
495                 if (result == 0x0003){
496                     hci_disconnect_security_block(handle);
497                 }
498                 break;
499             case ECHO_REQUEST:
500                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
501                 break;
502             case INFORMATION_REQUEST:
503                 switch (infoType){
504                     case 1: { // Connectionless MTU
505                         uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
506                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(connectionless_mtu), &connectionless_mtu);
507                         break;
508                     }
509                     case 2: { // Extended Features Supported
510                         // extended features request supported, features: fixed channels, unicast connectionless data reception
511                         uint32_t features = 0x280;
512                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(features), &features);
513                         break;
514                     }
515                     case 3: { // Fixed Channels Supported
516                         uint8_t map[8];
517                         memset(map, 0, 8);
518                         map[0] = 0x01;  // L2CAP Signaling Channel (0x01) + Connectionless reception (0x02)
519                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(map), &map);
520                         break;
521                     }
522                     default:
523                         // all other types are not supported
524                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
525                         break;
526                 }
527                 break;
528             case COMMAND_REJECT:
529                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
530 #ifdef ENABLE_BLE
531             case COMMAND_REJECT_LE:
532                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
533                 break;
534 #endif
535             default:
536                 // should not happen
537                 break;
538         }
539     }
540 
541     uint8_t  config_options[4];
542     btstack_linked_list_iterator_t it;
543     btstack_linked_list_iterator_init(&it, &l2cap_channels);
544     while (btstack_linked_list_iterator_has_next(&it)){
545 
546         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
547         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
548         switch (channel->state){
549 
550             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
551             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
552                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
553                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
554                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
555                     l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
556                 }
557                 break;
558 
559             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
560                 if (!hci_can_send_command_packet_now()) break;
561                 // send connection request - set state first
562                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
563                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
564                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
565                 break;
566 
567             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
568                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
569                 channel->state = L2CAP_STATE_INVALID;
570                 l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
571                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
572                 l2cap_stop_rtx(channel);
573                 btstack_linked_list_iterator_remove(&it);
574                 btstack_memory_l2cap_channel_free(channel);
575                 break;
576 
577             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
578                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
579                 channel->state = L2CAP_STATE_CONFIG;
580                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
581                 l2cap_send_signaling_packet(channel->handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
582                 break;
583 
584             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
585                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
586                 // success, start l2cap handshake
587                 channel->local_sig_id = l2cap_next_sig_id();
588                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
589                 l2cap_send_signaling_packet( channel->handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
590                 l2cap_start_rtx(channel);
591                 break;
592 
593             case L2CAP_STATE_CONFIG:
594                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
595                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
596                     uint16_t flags = 0;
597                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
598                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
599                         flags = 1;
600                     } else {
601                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
602                     }
603                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
604                         l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS, 0, NULL);
605                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
606                         config_options[0] = 1; // MTU
607                         config_options[1] = 2; // len param
608                         little_endian_store_16( (uint8_t*)&config_options, 2, channel->remote_mtu);
609                         l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 4, &config_options);
610                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
611                     } else {
612                         l2cap_send_signaling_packet(channel->handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, 0, 0, NULL);
613                     }
614                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
615                 }
616                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
617                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
618                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
619                     channel->local_sig_id = l2cap_next_sig_id();
620                     config_options[0] = 1; // MTU
621                     config_options[1] = 2; // len param
622                     little_endian_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
623                     l2cap_send_signaling_packet(channel->handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, 4, &config_options);
624                     l2cap_start_rtx(channel);
625                 }
626                 if (l2cap_channel_ready_for_open(channel)){
627                     channel->state = L2CAP_STATE_OPEN;
628                     l2cap_emit_channel_opened(channel, 0);  // success
629                 }
630                 break;
631 
632             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
633                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
634                 channel->state = L2CAP_STATE_INVALID;
635                 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
636                 // 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 :)
637                 l2cap_finialize_channel_close(channel);  // -- remove from list
638                 break;
639 
640             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
641                 if (!hci_can_send_acl_packet_now(channel->handle)) break;
642                 channel->local_sig_id = l2cap_next_sig_id();
643                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
644                 l2cap_send_signaling_packet( channel->handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
645                 break;
646             default:
647                 break;
648         }
649     }
650 
651 #ifdef ENABLE_BLE
652     // send l2cap con paramter update if necessary
653     hci_connections_get_iterator(&it);
654     while(btstack_linked_list_iterator_has_next(&it)){
655         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
656         if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue;
657         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
658         switch (connection->le_con_parameter_update_state){
659             case CON_PARAMETER_UPDATE_SEND_REQUEST:
660                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
661                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier,
662                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
663                 break;
664             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
665                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
666                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
667                 break;
668             case CON_PARAMETER_UPDATE_DENY:
669                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
670                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
671                 break;
672             default:
673                 break;
674         }
675     }
676 #endif
677 
678     // log_info("l2cap_run: exit");
679 }
680 
681 uint16_t l2cap_max_mtu(void){
682     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
683 }
684 
685 uint16_t l2cap_max_le_mtu(void){
686     return l2cap_max_mtu();
687 }
688 
689 static void l2cap_handle_connection_complete(uint16_t handle, l2cap_channel_t * channel){
690     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
691         log_info("l2cap_handle_connection_complete expected state");
692         // success, start l2cap handshake
693         channel->handle = handle;
694         // check remote SSP feature first
695         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
696     }
697 }
698 
699 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
700     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
701 
702     // we have been waiting for remote supported features, if both support SSP,
703     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));
704     if (hci_ssp_supported_on_both_sides(channel->handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
705         // request security level 2
706         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
707         gap_request_security_level(channel->handle, LEVEL_2);
708         return;
709     }
710     // fine, go ahead
711     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
712 }
713 
714 /**
715  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
716  * @param packet_handler
717  * @param address
718  * @param psm
719  * @param mtu
720  * @param local_cid
721  */
722 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){
723     log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x mtu %u", bd_addr_to_str(address), psm, mtu);
724 
725     // alloc structure
726     l2cap_channel_t * chan = btstack_memory_l2cap_channel_get();
727     if (!chan) {
728         return BTSTACK_MEMORY_ALLOC_FAILED;
729     }
730 
731      // Init memory (make valgrind happy)
732     memset(chan, 0, sizeof(l2cap_channel_t));
733     // limit local mtu to max acl packet length - l2cap header
734     if (mtu > l2cap_max_mtu()) {
735         mtu = l2cap_max_mtu();
736     }
737 
738     // fill in
739     BD_ADDR_COPY(chan->address, address);
740     chan->psm = psm;
741     chan->handle = 0;
742     chan->packet_handler = channel_packet_handler;
743     chan->remote_mtu = L2CAP_MINIMAL_MTU;
744     chan->local_mtu = mtu;
745     chan->local_cid = l2cap_next_local_cid();
746 
747     // set initial state
748     chan->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
749     chan->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
750     chan->remote_sig_id = L2CAP_SIG_ID_INVALID;
751     chan->local_sig_id = L2CAP_SIG_ID_INVALID;
752     chan->required_security_level = LEVEL_0;
753 
754     // add to connections list
755     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) chan);
756 
757     // store local_cid
758     if (out_local_cid){
759        *out_local_cid = chan->local_cid;
760     }
761 
762     // check if hci connection is already usable
763     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
764     if (conn){
765         log_info("l2cap_create_channel, hci connection already exists");
766         l2cap_handle_connection_complete(conn->con_handle, chan);
767         // check if remote supported fearures are already received
768         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
769             l2cap_handle_remote_supported_features_received(chan);
770         }
771     }
772 
773     l2cap_run();
774 
775     return 0;
776 }
777 
778 void
779 l2cap_disconnect(uint16_t local_cid, uint8_t reason){
780     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
781     // find channel for local_cid
782     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
783     if (channel) {
784         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
785     }
786     // process
787     l2cap_run();
788 }
789 
790 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
791     btstack_linked_list_iterator_t it;
792     btstack_linked_list_iterator_init(&it, &l2cap_channels);
793     while (btstack_linked_list_iterator_has_next(&it)){
794         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
795         if ( BD_ADDR_CMP( channel->address, address) != 0) continue;
796         // channel for this address found
797         switch (channel->state){
798             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
799             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
800                 // failure, forward error code
801                 l2cap_emit_channel_opened(channel, status);
802                 // discard channel
803                 l2cap_stop_rtx(channel);
804                 btstack_linked_list_iterator_remove(&it);
805                 btstack_memory_l2cap_channel_free(channel);
806                 break;
807             default:
808                 break;
809         }
810     }
811 }
812 
813 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
814     btstack_linked_list_iterator_t it;
815     btstack_linked_list_iterator_init(&it, &l2cap_channels);
816     while (btstack_linked_list_iterator_has_next(&it)){
817         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
818         if ( ! BD_ADDR_CMP( channel->address, address) ){
819             l2cap_handle_connection_complete(handle, channel);
820         }
821     }
822     // process
823     l2cap_run();
824 }
825 
826 static void l2cap_event_handler(uint8_t *packet, uint16_t size){
827 
828     bd_addr_t address;
829     hci_con_handle_t handle;
830     btstack_linked_list_iterator_t it;
831     int hci_con_used;
832 
833     switch(packet[0]){
834 
835         // handle connection complete events
836         case HCI_EVENT_CONNECTION_COMPLETE:
837             bt_flip_addr(address, &packet[5]);
838             if (packet[2] == 0){
839                 handle = little_endian_read_16(packet, 3);
840                 l2cap_handle_connection_success_for_addr(address, handle);
841             } else {
842                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
843             }
844             break;
845 
846         // handle successful create connection cancel command
847         case HCI_EVENT_COMMAND_COMPLETE:
848             if ( COMMAND_COMPLETE_EVENT(packet, hci_create_connection_cancel) ) {
849                 if (packet[5] == 0){
850                     bt_flip_addr(address, &packet[6]);
851                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
852                     l2cap_handle_connection_failed_for_addr(address, 0x16);
853                 }
854             }
855             l2cap_run();    // try sending signaling packets first
856             break;
857 
858         case HCI_EVENT_COMMAND_STATUS:
859             l2cap_run();    // try sending signaling packets first
860             break;
861 
862         // handle disconnection complete events
863         case HCI_EVENT_DISCONNECTION_COMPLETE:
864             // send l2cap disconnect events for all channels on this handle and free them
865             handle = little_endian_read_16(packet, 3);
866             btstack_linked_list_iterator_init(&it, &l2cap_channels);
867             while (btstack_linked_list_iterator_has_next(&it)){
868                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
869                 if (channel->handle != handle) continue;
870                 l2cap_emit_channel_closed(channel);
871                 l2cap_stop_rtx(channel);
872                 btstack_linked_list_iterator_remove(&it);
873                 btstack_memory_l2cap_channel_free(channel);
874             }
875             break;
876 
877         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
878             l2cap_run();    // try sending signaling packets first
879             break;
880 
881         // HCI Connection Timeouts
882         case L2CAP_EVENT_TIMEOUT_CHECK:
883             handle = little_endian_read_16(packet, 2);
884             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
885             if (hci_authentication_active_for_handle(handle)) break;
886             hci_con_used = 0;
887             btstack_linked_list_iterator_init(&it, &l2cap_channels);
888             while (btstack_linked_list_iterator_has_next(&it)){
889                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
890                 if (channel->handle != handle) continue;
891                 hci_con_used = 1;
892                 break;
893             }
894             if (hci_con_used) break;
895             if (!hci_can_send_command_packet_now()) break;
896             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
897             break;
898 
899         case DAEMON_EVENT_HCI_PACKET_SENT:
900             l2cap_run();    // try sending signaling packets first
901 
902             btstack_linked_list_iterator_init(&it, &l2cap_channels);
903             while (btstack_linked_list_iterator_has_next(&it)){
904                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
905                 if (!channel->packet_handler) continue;
906                 (* (channel->packet_handler))(HCI_EVENT_PACKET, channel->local_cid, packet, size);
907             }
908             if (attribute_protocol_packet_handler) {
909                 (*attribute_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
910             }
911             if (security_protocol_packet_handler) {
912                 (*security_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
913             }
914             if (connectionless_channel_packet_handler) {
915                 (*connectionless_channel_packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
916             }
917             break;
918 
919         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
920             handle = little_endian_read_16(packet, 3);
921             btstack_linked_list_iterator_init(&it, &l2cap_channels);
922             while (btstack_linked_list_iterator_has_next(&it)){
923                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
924                 if (channel->handle != handle) continue;
925                 l2cap_handle_remote_supported_features_received(channel);
926                 break;
927             }
928             break;
929 
930         case GAP_EVENT_SECURITY_LEVEL:
931             handle = little_endian_read_16(packet, 2);
932             log_info("l2cap - security level update");
933             btstack_linked_list_iterator_init(&it, &l2cap_channels);
934             while (btstack_linked_list_iterator_has_next(&it)){
935                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
936                 if (channel->handle != handle) continue;
937 
938                 log_info("l2cap - state %u", channel->state);
939 
940                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
941                 gap_security_level_t required_level = channel->required_security_level;
942 
943                 switch (channel->state){
944                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
945                         if (actual_level >= required_level){
946                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
947                             l2cap_emit_connection_request(channel);
948                         } else {
949                             channel->reason = 0x0003; // security block
950                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
951                         }
952                         break;
953 
954                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
955                         if (actual_level >= required_level){
956                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
957                         } else {
958                             // disconnnect, authentication not good enough
959                             hci_disconnect_security_block(handle);
960                         }
961                         break;
962 
963                     default:
964                         break;
965                 }
966             }
967             break;
968 
969         default:
970             break;
971     }
972 
973     // pass on: main packet handler, att and sm packet handlers
974     (*packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
975     if (attribute_protocol_packet_handler){
976         (*attribute_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
977     }
978     if (security_protocol_packet_handler) {
979         (*security_protocol_packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
980     }
981     if (connectionless_channel_packet_handler) {
982         (*connectionless_channel_packet_handler)(HCI_EVENT_PACKET, 0, packet, size);
983     }
984 
985     l2cap_run();
986 }
987 
988 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
989     channel->remote_sig_id = identifier;
990     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
991     l2cap_run();
992 }
993 
994 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t data){
995     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused."
996     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
997         signaling_responses[signaling_responses_pending].handle = handle;
998         signaling_responses[signaling_responses_pending].code = code;
999         signaling_responses[signaling_responses_pending].sig_id = sig_id;
1000         signaling_responses[signaling_responses_pending].data = data;
1001         signaling_responses_pending++;
1002         l2cap_run();
1003     }
1004 }
1005 
1006 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
1007 
1008     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
1009     l2cap_service_t *service = l2cap_get_service(psm);
1010     if (!service) {
1011         // 0x0002 PSM not supported
1012         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0002);
1013         return;
1014     }
1015 
1016     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
1017     if (!hci_connection) {
1018         //
1019         log_error("no hci_connection for handle %u", handle);
1020         return;
1021     }
1022 
1023     // alloc structure
1024     // log_info("l2cap_handle_connection_request register channel");
1025     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1026     if (!channel){
1027         // 0x0004 No resources available
1028         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, 0x0004);
1029         return;
1030     }
1031     // Init memory (make valgrind happy)
1032     memset(channel, 0, sizeof(l2cap_channel_t));
1033     // fill in
1034     BD_ADDR_COPY(channel->address, hci_connection->address);
1035     channel->psm = psm;
1036     channel->handle = handle;
1037     channel->packet_handler = service->packet_handler;
1038     channel->local_cid  = l2cap_next_local_cid();
1039     channel->remote_cid = source_cid;
1040     channel->local_mtu  = service->mtu;
1041     channel->remote_mtu = L2CAP_DEFAULT_MTU;
1042     channel->remote_sig_id = sig_id;
1043     channel->required_security_level = service->required_security_level;
1044 
1045     // limit local mtu to max acl packet length - l2cap header
1046     if (channel->local_mtu > l2cap_max_mtu()) {
1047         channel->local_mtu = l2cap_max_mtu();
1048     }
1049 
1050     // set initial state
1051     channel->state =     L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
1052     channel->state_var = L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND;
1053 
1054     // add to connections list
1055     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1056 
1057     // assert security requirements
1058     gap_request_security_level(handle, channel->required_security_level);
1059 }
1060 
1061 void l2cap_accept_connection(uint16_t local_cid){
1062     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
1063     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1064     if (!channel) {
1065         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
1066         return;
1067     }
1068 
1069     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
1070 
1071     // process
1072     l2cap_run();
1073 }
1074 
1075 void l2cap_decline_connection(uint16_t local_cid, uint8_t reason){
1076     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x, reason %x", local_cid, reason);
1077     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
1078     if (!channel) {
1079         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
1080         return;
1081     }
1082     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
1083     channel->reason = reason;
1084     l2cap_run();
1085 }
1086 
1087 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
1088 
1089     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1090 
1091     uint16_t flags = little_endian_read_16(command, 6);
1092     if (flags & 1) {
1093         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1094     }
1095 
1096     // accept the other's configuration options
1097     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1098     uint16_t pos     = 8;
1099     while (pos < end_pos){
1100         uint8_t option_hint = command[pos] >> 7;
1101         uint8_t option_type = command[pos] & 0x7f;
1102         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
1103         pos++;
1104         uint8_t length = command[pos++];
1105         // MTU { type(8): 1, len(8):2, MTU(16) }
1106         if (option_type == 1 && length == 2){
1107             channel->remote_mtu = little_endian_read_16(command, pos);
1108             // log_info("l2cap cid 0x%02x, remote mtu %u", channel->local_cid, channel->remote_mtu);
1109             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1110         }
1111         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
1112         if (option_type == 2 && length == 2){
1113             channel->flush_timeout = little_endian_read_16(command, pos);
1114         }
1115         // check for unknown options
1116         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
1117             log_info("l2cap cid %u, unknown options", channel->local_cid);
1118             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
1119         }
1120         pos += length;
1121     }
1122 }
1123 
1124 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
1125     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
1126     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
1127     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
1128     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
1129     if (channel->state == L2CAP_STATE_OPEN) return 0;
1130     return 1;
1131 }
1132 
1133 
1134 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
1135 
1136     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1137     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1138     uint16_t result = 0;
1139 
1140     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
1141 
1142     // handle DISCONNECT REQUESTS seperately
1143     if (code == DISCONNECTION_REQUEST){
1144         switch (channel->state){
1145             case L2CAP_STATE_CONFIG:
1146             case L2CAP_STATE_OPEN:
1147             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1148             case L2CAP_STATE_WAIT_DISCONNECT:
1149                 l2cap_handle_disconnect_request(channel, identifier);
1150                 break;
1151 
1152             default:
1153                 // ignore in other states
1154                 break;
1155         }
1156         return;
1157     }
1158 
1159     // @STATEMACHINE(l2cap)
1160     switch (channel->state) {
1161 
1162         case L2CAP_STATE_WAIT_CONNECT_RSP:
1163             switch (code){
1164                 case CONNECTION_RESPONSE:
1165                     l2cap_stop_rtx(channel);
1166                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1167                     switch (result) {
1168                         case 0:
1169                             // successful connection
1170                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1171                             channel->state = L2CAP_STATE_CONFIG;
1172                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1173                             break;
1174                         case 1:
1175                             // connection pending. get some coffee, but start the ERTX
1176                             l2cap_start_ertx(channel);
1177                             break;
1178                         default:
1179                             // channel closed
1180                             channel->state = L2CAP_STATE_CLOSED;
1181                             // map l2cap connection response result to BTstack status enumeration
1182                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
1183 
1184                             // drop link key if security block
1185                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
1186                                 hci_drop_link_key_for_bd_addr(channel->address);
1187                             }
1188 
1189                             // discard channel
1190                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1191                             btstack_memory_l2cap_channel_free(channel);
1192                             break;
1193                     }
1194                     break;
1195 
1196                 default:
1197                     //@TODO: implement other signaling packets
1198                     break;
1199             }
1200             break;
1201 
1202         case L2CAP_STATE_CONFIG:
1203             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1204             switch (code) {
1205                 case CONFIGURE_REQUEST:
1206                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1207                     l2cap_signaling_handle_configure_request(channel, command);
1208                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
1209                         // only done if continuation not set
1210                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
1211                     }
1212                     break;
1213                 case CONFIGURE_RESPONSE:
1214                     l2cap_stop_rtx(channel);
1215                     switch (result){
1216                         case 0: // success
1217                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
1218                             break;
1219                         case 4: // pending
1220                             l2cap_start_ertx(channel);
1221                             break;
1222                         default:
1223                             // retry on negative result
1224                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1225                             break;
1226                     }
1227                     break;
1228                 default:
1229                     break;
1230             }
1231             if (l2cap_channel_ready_for_open(channel)){
1232                 // for open:
1233                 channel->state = L2CAP_STATE_OPEN;
1234                 l2cap_emit_channel_opened(channel, 0);
1235             }
1236             break;
1237 
1238         case L2CAP_STATE_WAIT_DISCONNECT:
1239             switch (code) {
1240                 case DISCONNECTION_RESPONSE:
1241                     l2cap_finialize_channel_close(channel);
1242                     break;
1243                 default:
1244                     //@TODO: implement other signaling packets
1245                     break;
1246             }
1247             break;
1248 
1249         case L2CAP_STATE_CLOSED:
1250             // @TODO handle incoming requests
1251             break;
1252 
1253         case L2CAP_STATE_OPEN:
1254             //@TODO: implement other signaling packets, e.g. re-configure
1255             break;
1256         default:
1257             break;
1258     }
1259     // log_info("new state %u", channel->state);
1260 }
1261 
1262 
1263 static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
1264 
1265     // get code, signalind identifier and command len
1266     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
1267     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1268 
1269     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_REQUEST
1270     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_REQUEST){
1271         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, L2CAP_REJ_CMD_UNKNOWN);
1272         return;
1273     }
1274 
1275     // general commands without an assigned channel
1276     switch(code) {
1277 
1278         case CONNECTION_REQUEST: {
1279             uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1280             uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
1281             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
1282             return;
1283         }
1284 
1285         case ECHO_REQUEST:
1286             l2cap_register_signaling_response(handle, code, sig_id, 0);
1287             return;
1288 
1289         case INFORMATION_REQUEST: {
1290             uint16_t infoType = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1291             l2cap_register_signaling_response(handle, code, sig_id, infoType);
1292             return;
1293         }
1294 
1295         default:
1296             break;
1297     }
1298 
1299 
1300     // Get potential destination CID
1301     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1302 
1303     // Find channel for this sig_id and connection handle
1304     btstack_linked_list_iterator_t it;
1305     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1306     while (btstack_linked_list_iterator_has_next(&it)){
1307         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1308         if (channel->handle != handle) continue;
1309         if (code & 1) {
1310             // match odd commands (responses) by previous signaling identifier
1311             if (channel->local_sig_id == sig_id) {
1312                 l2cap_signaling_handler_channel(channel, command);
1313                 break;
1314             }
1315         } else {
1316             // match even commands (requests) by local channel id
1317             if (channel->local_cid == dest_cid) {
1318                 l2cap_signaling_handler_channel(channel, command);
1319                 break;
1320             }
1321         }
1322     }
1323 }
1324 
1325 static void l2cap_acl_handler( uint8_t *packet, uint16_t size ){
1326 
1327     // Get Channel ID
1328     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
1329     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
1330 
1331     switch (channel_id) {
1332 
1333         case L2CAP_CID_SIGNALING: {
1334 
1335             uint16_t command_offset = 8;
1336             while (command_offset < size) {
1337 
1338                 // handle signaling commands
1339                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
1340 
1341                 // increment command_offset
1342                 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1343             }
1344             break;
1345         }
1346 
1347         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
1348             if (attribute_protocol_packet_handler) {
1349                 (*attribute_protocol_packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1350             }
1351             break;
1352 
1353         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
1354             if (security_protocol_packet_handler) {
1355                 (*security_protocol_packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1356             }
1357             break;
1358 
1359         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
1360             if (connectionless_channel_packet_handler) {
1361                 (*connectionless_channel_packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1362             }
1363             break;
1364 
1365         case L2CAP_CID_SIGNALING_LE: {
1366             switch (packet[8]){
1367                 case CONNECTION_PARAMETER_UPDATE_RESPONSE: {
1368                     uint16_t result = little_endian_read_16(packet, 12);
1369                     l2cap_emit_connection_parameter_update_response(handle, result);
1370                     break;
1371                 }
1372                 case CONNECTION_PARAMETER_UPDATE_REQUEST: {
1373                     uint8_t event[10];
1374                     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
1375                     event[1] = 8;
1376                     memcpy(&event[2], &packet[12], 8);
1377 
1378                     hci_connection_t * connection = hci_connection_for_handle(handle);
1379                     if (connection){
1380                         if (connection->role != HCI_ROLE_MASTER){
1381                             // reject command without notifying upper layer when not in master role
1382                             uint8_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
1383                             l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, L2CAP_REJ_CMD_UNKNOWN);
1384                             break;
1385                         }
1386                         int update_parameter = 1;
1387                         le_connection_parameter_range_t existing_range;
1388                         gap_le_get_connection_parameter_range(existing_range);
1389                         uint16_t le_conn_interval_min = little_endian_read_16(packet,12);
1390                         uint16_t le_conn_interval_max = little_endian_read_16(packet,14);
1391                         uint16_t le_conn_latency = little_endian_read_16(packet,16);
1392                         uint16_t le_supervision_timeout = little_endian_read_16(packet,18);
1393 
1394                         if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
1395                         if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
1396 
1397                         if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
1398                         if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
1399 
1400                         if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
1401                         if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
1402 
1403                         if (update_parameter){
1404                             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
1405                             connection->le_conn_interval_min = le_conn_interval_min;
1406                             connection->le_conn_interval_max = le_conn_interval_max;
1407                             connection->le_conn_latency = le_conn_latency;
1408                             connection->le_supervision_timeout = le_supervision_timeout;
1409                         } else {
1410                             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
1411                         }
1412                         connection->le_con_param_update_identifier = packet[COMPLETE_L2CAP_HEADER + 1];
1413                     }
1414 
1415                     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1416                     (*packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
1417 
1418                     break;
1419                 }
1420                 default: {
1421                     uint8_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
1422                     l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, L2CAP_REJ_CMD_UNKNOWN);
1423                     break;
1424                 }
1425             }
1426             break;
1427         }
1428 
1429         default: {
1430             // Find channel for this channel_id and connection handle
1431             l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(channel_id);
1432             if (channel) {
1433                 l2cap_dispatch(channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
1434             }
1435             break;
1436         }
1437     }
1438 }
1439 
1440 static void l2cap_packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1441     switch (packet_type) {
1442         case HCI_EVENT_PACKET:
1443             l2cap_event_handler(packet, size);
1444             break;
1445         case HCI_ACL_DATA_PACKET:
1446             l2cap_acl_handler(packet, size);
1447             break;
1448         default:
1449             break;
1450     }
1451     l2cap_run();
1452 }
1453 
1454 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
1455 void l2cap_finialize_channel_close(l2cap_channel_t *channel){
1456     channel->state = L2CAP_STATE_CLOSED;
1457     l2cap_emit_channel_closed(channel);
1458     // discard channel
1459     l2cap_stop_rtx(channel);
1460     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1461     btstack_memory_l2cap_channel_free(channel);
1462 }
1463 
1464 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
1465     btstack_linked_list_iterator_t it;
1466     btstack_linked_list_iterator_init(&it, services);
1467     while (btstack_linked_list_iterator_has_next(&it)){
1468         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
1469         if ( service->psm == psm){
1470             return service;
1471         };
1472     }
1473     return NULL;
1474 }
1475 
1476 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
1477     return l2cap_get_service_internal(&l2cap_services, psm);
1478 }
1479 
1480 
1481 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
1482 
1483     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
1484 
1485     // check for alread registered psm
1486     // TODO: emit error event
1487     l2cap_service_t *service = l2cap_get_service(psm);
1488     if (service) {
1489         log_error("l2cap_register_service: PSM %u already registered", psm);
1490         return L2CAP_SERVICE_ALREADY_REGISTERED;
1491     }
1492 
1493     // alloc structure
1494     // TODO: emit error event
1495     service = btstack_memory_l2cap_service_get();
1496     if (!service) {
1497         log_error("l2cap_register_service: no memory for l2cap_service_t");
1498         return BTSTACK_MEMORY_ALLOC_FAILED;
1499     }
1500 
1501     // fill in
1502     service->psm = psm;
1503     service->mtu = mtu;
1504     service->packet_handler = service_packet_handler;
1505     service->required_security_level = security_level;
1506 
1507     // add to services list
1508     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
1509 
1510     // enable page scan
1511     hci_connectable_control(1);
1512 
1513     return 0;
1514 }
1515 
1516 void l2cap_unregister_service(uint16_t psm){
1517 
1518     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
1519 
1520     l2cap_service_t *service = l2cap_get_service(psm);
1521     if (!service) return;
1522     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
1523     btstack_memory_l2cap_service_free(service);
1524 
1525     // disable page scan when no services registered
1526     if (!btstack_linked_list_empty(&l2cap_services)) return;
1527     hci_connectable_control(0);
1528 }
1529 
1530 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
1531 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
1532     switch(channel_id){
1533         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
1534             attribute_protocol_packet_handler = the_packet_handler;
1535             break;
1536         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
1537             security_protocol_packet_handler = the_packet_handler;
1538             break;
1539         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
1540             connectionless_channel_packet_handler = the_packet_handler;
1541             break;
1542     }
1543 }
1544 
1545 #ifdef ENABLE_BLE
1546 
1547 
1548 #if 0
1549 static inline l2cap_service_t * l2cap_le_get_service(uint16_t psm){
1550     return l2cap_get_service_internal(&l2cap_le_services, psm);
1551 }
1552 /**
1553  * @brief Regster L2CAP LE Credit Based Flow Control Mode service
1554  * @param
1555  */
1556 void l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm,
1557     uint16_t mtu, uint16_t mps, uint16_t initial_credits, gap_security_level_t security_level){
1558 
1559     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x mtu %u connection %p", psm, mtu, connection);
1560 
1561     // check for alread registered psm
1562     // TODO: emit error event
1563     l2cap_service_t *service = l2cap_le_get_service(psm);
1564     if (service) {
1565         log_error("l2cap_le_register_service_internal: PSM %u already registered", psm);
1566         l2cap_emit_service_registered(connection, L2CAP_SERVICE_ALREADY_REGISTERED, psm);
1567         return;
1568     }
1569 
1570     // alloc structure
1571     // TODO: emit error event
1572     service = btstack_memory_l2cap_service_get();
1573     if (!service) {
1574         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
1575         l2cap_emit_service_registered(connection, BTSTACK_MEMORY_ALLOC_FAILED, psm);
1576         return;
1577     }
1578 
1579     // fill in
1580     service->psm = psm;
1581     service->mtu = mtu;
1582     service->mps = mps;
1583     service->packet_handler = packet_handler;
1584     service->required_security_level = security_level;
1585 
1586     // add to services list
1587     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
1588 
1589     // done
1590     l2cap_emit_service_registered(connection, 0, psm);
1591 }
1592 
1593 void l2cap_le_unregister_service(uint16_t psm) {
1594 
1595     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
1596 
1597     l2cap_service_t *service = l2cap_le_get_service(psm);
1598     if (!service) return;
1599     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
1600     btstack_memory_l2cap_service_free(service);
1601 }
1602 #endif
1603 #endif
1604