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