xref: /btstack/src/l2cap.c (revision bbc0a9e771e6fb2777fa97601fe30e015c17b2dd)
143625864Smatthias.ringwald /*
2a0c35809S[email protected]  * Copyright (C) 2014 BlueKitchen GmbH
31713bceaSmatthias.ringwald  *
41713bceaSmatthias.ringwald  * Redistribution and use in source and binary forms, with or without
51713bceaSmatthias.ringwald  * modification, are permitted provided that the following conditions
61713bceaSmatthias.ringwald  * are met:
71713bceaSmatthias.ringwald  *
81713bceaSmatthias.ringwald  * 1. Redistributions of source code must retain the above copyright
91713bceaSmatthias.ringwald  *    notice, this list of conditions and the following disclaimer.
101713bceaSmatthias.ringwald  * 2. Redistributions in binary form must reproduce the above copyright
111713bceaSmatthias.ringwald  *    notice, this list of conditions and the following disclaimer in the
121713bceaSmatthias.ringwald  *    documentation and/or other materials provided with the distribution.
131713bceaSmatthias.ringwald  * 3. Neither the name of the copyright holders nor the names of
141713bceaSmatthias.ringwald  *    contributors may be used to endorse or promote products derived
151713bceaSmatthias.ringwald  *    from this software without specific prior written permission.
166b64433eSmatthias.ringwald  * 4. Any redistribution, use, or modification is done solely for
176b64433eSmatthias.ringwald  *    personal benefit and not for any commercial purpose or for
186b64433eSmatthias.ringwald  *    monetary gain.
191713bceaSmatthias.ringwald  *
20a0c35809S[email protected]  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
211713bceaSmatthias.ringwald  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
221713bceaSmatthias.ringwald  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
231713bceaSmatthias.ringwald  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
241713bceaSmatthias.ringwald  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
251713bceaSmatthias.ringwald  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
261713bceaSmatthias.ringwald  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
271713bceaSmatthias.ringwald  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
281713bceaSmatthias.ringwald  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
291713bceaSmatthias.ringwald  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
301713bceaSmatthias.ringwald  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
311713bceaSmatthias.ringwald  * SUCH DAMAGE.
321713bceaSmatthias.ringwald  *
33a0c35809S[email protected]  * Please inquire about commercial licensing options at
34a0c35809S[email protected]  * [email protected]
356b64433eSmatthias.ringwald  *
361713bceaSmatthias.ringwald  */
371713bceaSmatthias.ringwald 
38ab2c6ae4SMatthias Ringwald #define __BTSTACK_FILE__ "l2cap.c"
39ab2c6ae4SMatthias Ringwald 
401713bceaSmatthias.ringwald /*
4143625864Smatthias.ringwald  *  l2cap.c
4243625864Smatthias.ringwald  *
4343625864Smatthias.ringwald  *  Logical Link Control and Adaption Protocl (L2CAP)
4443625864Smatthias.ringwald  *
4543625864Smatthias.ringwald  *  Created by Matthias Ringwald on 5/16/09.
4643625864Smatthias.ringwald  */
4743625864Smatthias.ringwald 
4843625864Smatthias.ringwald #include "l2cap.h"
49645658c9Smatthias.ringwald #include "hci.h"
502b3c6c9bSmatthias.ringwald #include "hci_dump.h"
51235946f1SMatthias Ringwald #include "bluetooth_sdp.h"
5216ece135SMatthias Ringwald #include "btstack_debug.h"
530e2df43fSMatthias Ringwald #include "btstack_event.h"
54d3a9df87Smatthias.ringwald #include "btstack_memory.h"
5543625864Smatthias.ringwald 
56cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
5783fd9c76SMatthias Ringwald #include "ble/sm.h"
5883fd9c76SMatthias Ringwald #endif
5983fd9c76SMatthias Ringwald 
6043625864Smatthias.ringwald #include <stdarg.h>
6143625864Smatthias.ringwald #include <string.h>
6243625864Smatthias.ringwald 
6343625864Smatthias.ringwald #include <stdio.h>
6443625864Smatthias.ringwald 
654c744e21Smatthias.ringwald // nr of buffered acl packets in outgoing queue to get max performance
664c744e21Smatthias.ringwald #define NR_BUFFERED_ACL_PACKETS 3
674c744e21Smatthias.ringwald 
6839bda6d5Smatthias.ringwald // used to cache l2cap rejects, echo, and informational requests
69e16a9cacSmatthias.ringwald #define NR_PENDING_SIGNALING_RESPONSES 3
7039bda6d5Smatthias.ringwald 
7185aeef60SMatthias Ringwald // nr of credits provided to remote if credits fall below watermark
7285aeef60SMatthias Ringwald #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK 5
7385aeef60SMatthias Ringwald #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT 5
7485aeef60SMatthias Ringwald 
7500d93d79Smatthias.ringwald // offsets for L2CAP SIGNALING COMMANDS
7600d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
7700d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
7800d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
7900d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
8000d93d79Smatthias.ringwald 
815628cf69SMatthias Ringwald // internal table
825628cf69SMatthias Ringwald #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL 0
835628cf69SMatthias Ringwald #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL  1
845628cf69SMatthias Ringwald #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL 2
855628cf69SMatthias Ringwald #define L2CAP_FIXED_CHANNEL_TABLE_SIZE (L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL+1)
865628cf69SMatthias Ringwald 
8709e9d05bSMatthias Ringwald #if defined(ENABLE_LE_DATA_CHANNELS) || defined(ENABLE_CLASSIC)
8809e9d05bSMatthias Ringwald #define L2CAP_USES_CHANNELS
8909e9d05bSMatthias Ringwald #endif
9009e9d05bSMatthias Ringwald 
9133c40538SMatthias Ringwald // prototypes
9233c40538SMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
933d50b4baSMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size );
9430725612SMatthias Ringwald static void l2cap_notify_channel_can_send(void);
9509e9d05bSMatthias Ringwald static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel);
9609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
9709e9d05bSMatthias Ringwald static void l2cap_finialize_channel_close(l2cap_channel_t *channel);
9809e9d05bSMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm);
9909e9d05bSMatthias Ringwald static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
10009e9d05bSMatthias Ringwald static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
10109e9d05bSMatthias Ringwald static void l2cap_emit_incoming_connection(l2cap_channel_t *channel);
10209e9d05bSMatthias Ringwald static int  l2cap_channel_ready_for_open(l2cap_channel_t *channel);
10309e9d05bSMatthias Ringwald #endif
104cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
10557be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status);
10657be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel);
10757be49d6SMatthias Ringwald static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid);
10844276248SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel);
109828a7f7aSMatthias Ringwald static void l2cap_le_finialize_channel_close(l2cap_channel_t *channel);
110e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t psm);
111e7d0c9aaSMatthias Ringwald #endif
11233c40538SMatthias Ringwald 
1135628cf69SMatthias Ringwald typedef struct l2cap_fixed_channel {
1145628cf69SMatthias Ringwald     btstack_packet_handler_t callback;
1152125de09SMatthias Ringwald     uint8_t waiting_for_can_send_now;
1165628cf69SMatthias Ringwald } l2cap_fixed_channel_t;
1175628cf69SMatthias Ringwald 
11809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1195628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_channels;
1205628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_services;
12109e9d05bSMatthias Ringwald static uint8_t require_security_level2_for_outgoing_sdp;
12209e9d05bSMatthias Ringwald #endif
12357be49d6SMatthias Ringwald 
12457be49d6SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1255628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_le_channels;
1265628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_le_services;
12757be49d6SMatthias Ringwald #endif
12839bda6d5Smatthias.ringwald 
12939bda6d5Smatthias.ringwald // used to cache l2cap rejects, echo, and informational requests
1302b83fb7dSmatthias.ringwald static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
1312b83fb7dSmatthias.ringwald static int signaling_responses_pending;
1322b83fb7dSmatthias.ringwald 
133fb37a842SMatthias Ringwald static btstack_packet_callback_registration_t hci_event_callback_registration;
1345628cf69SMatthias Ringwald static l2cap_fixed_channel_t fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_SIZE];
13539bda6d5Smatthias.ringwald 
136d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
137d6ed9f9cSMatthias Ringwald // only used for connection parameter update events
138d6ed9f9cSMatthias Ringwald static btstack_packet_handler_t l2cap_event_packet_handler;
139d6ed9f9cSMatthias Ringwald #endif
140d6ed9f9cSMatthias Ringwald 
14185ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
14285ddcd84SMatthias Ringwald 
14385ddcd84SMatthias Ringwald /*
14485ddcd84SMatthias Ringwald  * CRC lookup table for generator polynom D^16 + D^15 + D^2 + 1
14585ddcd84SMatthias Ringwald  */
14685ddcd84SMatthias Ringwald static const uint16_t crc16_table[256] = {
14785ddcd84SMatthias Ringwald     0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
14885ddcd84SMatthias Ringwald     0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841,
14985ddcd84SMatthias Ringwald     0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41,
15085ddcd84SMatthias Ringwald     0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040,
15185ddcd84SMatthias Ringwald     0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441,
15285ddcd84SMatthias Ringwald     0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840,
15385ddcd84SMatthias Ringwald     0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40,
15485ddcd84SMatthias Ringwald     0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041,
15585ddcd84SMatthias Ringwald     0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
15685ddcd84SMatthias Ringwald     0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840,
15785ddcd84SMatthias Ringwald     0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
15885ddcd84SMatthias Ringwald     0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041,
15985ddcd84SMatthias Ringwald     0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440,
16085ddcd84SMatthias Ringwald     0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841,
16185ddcd84SMatthias Ringwald     0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41,
16285ddcd84SMatthias Ringwald     0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040,
16385ddcd84SMatthias Ringwald };
16485ddcd84SMatthias Ringwald 
16585ddcd84SMatthias Ringwald static uint16_t crc16_calc(uint8_t * data, uint16_t len){
16685ddcd84SMatthias Ringwald     uint16_t crc = 0;   // initial value = 0
16785ddcd84SMatthias Ringwald     while (len--){
16885ddcd84SMatthias Ringwald         crc = (crc >> 8) ^ crc16_table[ (crc ^ ((uint16_t) *data++)) & 0x00FF ];
16985ddcd84SMatthias Ringwald     }
17085ddcd84SMatthias Ringwald     return crc;
17185ddcd84SMatthias Ringwald }
17285ddcd84SMatthias Ringwald 
17385ddcd84SMatthias Ringwald #endif
17485ddcd84SMatthias Ringwald 
17585ddcd84SMatthias Ringwald 
17634e7e577SMatthias Ringwald static uint16_t l2cap_fixed_channel_table_channel_id_for_index(int index){
17734e7e577SMatthias Ringwald     switch (index){
17834e7e577SMatthias Ringwald         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL:
17934e7e577SMatthias Ringwald             return L2CAP_CID_ATTRIBUTE_PROTOCOL;
18034e7e577SMatthias Ringwald         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL:
18134e7e577SMatthias Ringwald             return L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
18234e7e577SMatthias Ringwald         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL:
18334e7e577SMatthias Ringwald             return L2CAP_CID_CONNECTIONLESS_CHANNEL;
18434e7e577SMatthias Ringwald         default:
18534e7e577SMatthias Ringwald             return 0;
18634e7e577SMatthias Ringwald     }
18734e7e577SMatthias Ringwald }
1885628cf69SMatthias Ringwald static int l2cap_fixed_channel_table_index_for_channel_id(uint16_t channel_id){
1895628cf69SMatthias Ringwald     switch (channel_id){
1905628cf69SMatthias Ringwald         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
1915628cf69SMatthias Ringwald             return L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL;
1925628cf69SMatthias Ringwald         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
1935628cf69SMatthias Ringwald             return  L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL;
1945628cf69SMatthias Ringwald         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
1955628cf69SMatthias Ringwald             return  L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL;
1965628cf69SMatthias Ringwald         default:
1975628cf69SMatthias Ringwald             return -1;
1985628cf69SMatthias Ringwald         }
1995628cf69SMatthias Ringwald }
20039bda6d5Smatthias.ringwald 
20134e7e577SMatthias Ringwald static int l2cap_fixed_channel_table_index_is_le(int index){
20234e7e577SMatthias Ringwald     if (index == L2CAP_CID_CONNECTIONLESS_CHANNEL) return 0;
20334e7e577SMatthias Ringwald     return 1;
20434e7e577SMatthias Ringwald }
20534e7e577SMatthias Ringwald 
20671de195eSMatthias Ringwald void l2cap_init(void){
2072b83fb7dSmatthias.ringwald     signaling_responses_pending = 0;
208808a48abSmatthias.ringwald 
20985ddcd84SMatthias Ringwald     uint8_t test[] = {0x0E, 0x00, 0x40, 0x00, 0x02, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 };
21085ddcd84SMatthias Ringwald     printf("crc16: %04x\n", crc16_calc(test, sizeof(test)));
21185ddcd84SMatthias Ringwald 
21209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
213f5454fc6Smatthias.ringwald     l2cap_channels = NULL;
214f5454fc6Smatthias.ringwald     l2cap_services = NULL;
21509e9d05bSMatthias Ringwald     require_security_level2_for_outgoing_sdp = 0;
21609e9d05bSMatthias Ringwald #endif
217a3dc965aSMatthias Ringwald 
218a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2197192e786SMatthias Ringwald     l2cap_le_services = NULL;
2207192e786SMatthias Ringwald     l2cap_le_channels = NULL;
221a3dc965aSMatthias Ringwald #endif
222f5454fc6Smatthias.ringwald 
223d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
22433c40538SMatthias Ringwald     l2cap_event_packet_handler = NULL;
225d6ed9f9cSMatthias Ringwald #endif
2265628cf69SMatthias Ringwald     memset(fixed_channels, 0, sizeof(fixed_channels));
227f5454fc6Smatthias.ringwald 
228fcadd0caSmatthias.ringwald     //
2292718e2e7Smatthias.ringwald     // register callback with HCI
230fcadd0caSmatthias.ringwald     //
231d9a7306aSMatthias Ringwald     hci_event_callback_registration.callback = &l2cap_hci_event_handler;
232fb37a842SMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
233fb37a842SMatthias Ringwald 
234d9a7306aSMatthias Ringwald     hci_register_acl_packet_handler(&l2cap_acl_handler);
235fb37a842SMatthias Ringwald 
236be005ed6SMatthias Ringwald #ifdef ENABLE_CLASSIC
23715a95bd5SMatthias Ringwald     gap_connectable_control(0); // no services yet
238be005ed6SMatthias Ringwald #endif
239fcadd0caSmatthias.ringwald }
240fcadd0caSmatthias.ringwald 
241ffbf8201SMatthias Ringwald void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
242d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
24333c40538SMatthias Ringwald     l2cap_event_packet_handler = handler;
244d6ed9f9cSMatthias Ringwald #else
245d6ed9f9cSMatthias Ringwald     UNUSED(handler);
246d6ed9f9cSMatthias Ringwald #endif
2471e6aba47Smatthias.ringwald }
2481e6aba47Smatthias.ringwald 
24909e9d05bSMatthias Ringwald void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
2509ec2630cSMatthias Ringwald     UNUSED(con_handle);
2519ec2630cSMatthias Ringwald 
25209e9d05bSMatthias Ringwald     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
25309e9d05bSMatthias Ringwald     if (index < 0) return;
25409e9d05bSMatthias Ringwald     fixed_channels[index].waiting_for_can_send_now = 1;
25509e9d05bSMatthias Ringwald     l2cap_notify_channel_can_send();
25609e9d05bSMatthias Ringwald }
25709e9d05bSMatthias Ringwald 
25809e9d05bSMatthias Ringwald int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
2599ec2630cSMatthias Ringwald     UNUSED(channel_id);
2609ec2630cSMatthias Ringwald 
26109e9d05bSMatthias Ringwald     return hci_can_send_acl_packet_now(con_handle);
26209e9d05bSMatthias Ringwald }
26309e9d05bSMatthias Ringwald 
26409e9d05bSMatthias Ringwald uint8_t *l2cap_get_outgoing_buffer(void){
26509e9d05bSMatthias Ringwald     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
26609e9d05bSMatthias Ringwald }
26709e9d05bSMatthias Ringwald 
26809e9d05bSMatthias Ringwald int l2cap_reserve_packet_buffer(void){
26909e9d05bSMatthias Ringwald     return hci_reserve_packet_buffer();
27009e9d05bSMatthias Ringwald }
27109e9d05bSMatthias Ringwald 
27209e9d05bSMatthias Ringwald void l2cap_release_packet_buffer(void){
27309e9d05bSMatthias Ringwald     hci_release_packet_buffer();
27409e9d05bSMatthias Ringwald }
27509e9d05bSMatthias Ringwald 
276f511cefaSMatthias Ringwald static void l2cap_setup_header(uint8_t * acl_buffer, hci_con_handle_t con_handle, uint8_t packet_boundary, uint16_t remote_cid, uint16_t len){
27709e9d05bSMatthias Ringwald     // 0 - Connection handle : PB=pb : BC=00
278f511cefaSMatthias Ringwald     little_endian_store_16(acl_buffer, 0, con_handle | (packet_boundary << 12) | (0 << 14));
27909e9d05bSMatthias Ringwald     // 2 - ACL length
28009e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 2,  len + 4);
28109e9d05bSMatthias Ringwald     // 4 - L2CAP packet length
28209e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 4,  len + 0);
28309e9d05bSMatthias Ringwald     // 6 - L2CAP channel DEST
28409e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 6,  remote_cid);
28509e9d05bSMatthias Ringwald }
28609e9d05bSMatthias Ringwald 
287f511cefaSMatthias Ringwald // assumption - only on LE connections
28809e9d05bSMatthias Ringwald int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
28909e9d05bSMatthias Ringwald 
29009e9d05bSMatthias Ringwald     if (!hci_is_packet_buffer_reserved()){
29109e9d05bSMatthias Ringwald         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
29209e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
29309e9d05bSMatthias Ringwald     }
29409e9d05bSMatthias Ringwald 
29509e9d05bSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
29609e9d05bSMatthias Ringwald         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
29709e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
29809e9d05bSMatthias Ringwald     }
29909e9d05bSMatthias Ringwald 
30009e9d05bSMatthias Ringwald     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
30109e9d05bSMatthias Ringwald 
30209e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
303f511cefaSMatthias Ringwald     l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
30409e9d05bSMatthias Ringwald     // send
30509e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len+8);
30609e9d05bSMatthias Ringwald }
30709e9d05bSMatthias Ringwald 
308f511cefaSMatthias Ringwald // assumption - only on LE connections
30909e9d05bSMatthias Ringwald int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
31009e9d05bSMatthias Ringwald 
31109e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(con_handle)){
31209e9d05bSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", cid);
31309e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
31409e9d05bSMatthias Ringwald     }
31509e9d05bSMatthias Ringwald 
31609e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
31709e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
31809e9d05bSMatthias Ringwald 
31909e9d05bSMatthias Ringwald     memcpy(&acl_buffer[8], data, len);
32009e9d05bSMatthias Ringwald 
32109e9d05bSMatthias Ringwald     return l2cap_send_prepared_connectionless(con_handle, cid, len);
32209e9d05bSMatthias Ringwald }
32309e9d05bSMatthias Ringwald 
32409e9d05bSMatthias Ringwald static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
325d9d23054SMatthias Ringwald     log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
32609e9d05bSMatthias Ringwald     uint8_t event[4];
32709e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
32809e9d05bSMatthias Ringwald     event[1] = sizeof(event) - 2;
32909e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, channel);
33009e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
33109e9d05bSMatthias Ringwald     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
33209e9d05bSMatthias Ringwald }
33309e9d05bSMatthias Ringwald 
33409e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
33517a9b554SMatthias Ringwald static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
33658de5610Smatthias.ringwald     (* (channel->packet_handler))(type, channel->local_cid, data, size);
33758de5610Smatthias.ringwald }
33858de5610Smatthias.ringwald 
33944276248SMatthias Ringwald static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
34044276248SMatthias Ringwald     uint8_t event[4];
34144276248SMatthias Ringwald     event[0] = event_code;
34244276248SMatthias Ringwald     event[1] = sizeof(event) - 2;
34344276248SMatthias Ringwald     little_endian_store_16(event, 2, channel->local_cid);
34444276248SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
34544276248SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
34644276248SMatthias Ringwald }
34709e9d05bSMatthias Ringwald #endif
34844276248SMatthias Ringwald 
34909e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
35058de5610Smatthias.ringwald void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
351c9dc710bS[email protected]     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",
352fc64f94aSMatthias Ringwald              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
353c9dc710bS[email protected]              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
354bab5f4f0SMatthias Ringwald     uint8_t event[24];
35558de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
35658de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
35758de5610Smatthias.ringwald     event[2] = status;
358724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
359fc64f94aSMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
360f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
361f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
362f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
363f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 17, channel->local_mtu);
364f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 19, channel->remote_mtu);
365f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 21, channel->flush_timeout);
366bab5f4f0SMatthias Ringwald     event[23] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
36758de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
36817a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
36958de5610Smatthias.ringwald }
37058de5610Smatthias.ringwald 
37144276248SMatthias Ringwald static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
372e0abb8e7S[email protected]     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
37344276248SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
37458de5610Smatthias.ringwald }
37558de5610Smatthias.ringwald 
37644276248SMatthias Ringwald static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
377e0abb8e7S[email protected]     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
378fc64f94aSMatthias Ringwald              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
37958de5610Smatthias.ringwald     uint8_t event[16];
38058de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
38158de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
382724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[2]);
383fc64f94aSMatthias Ringwald     little_endian_store_16(event,  8, channel->con_handle);
384f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 10, channel->psm);
385f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 12, channel->local_cid);
386f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 14, channel->remote_cid);
38758de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
38817a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3890af41d30Smatthias.ringwald }
390808a48abSmatthias.ringwald 
3917f02f414SMatthias Ringwald static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
392665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
393665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
394665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
395665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
396b35f641cSmatthias.ringwald         if ( channel->local_cid == local_cid) {
397f62db1e3Smatthias.ringwald             return channel;
398f62db1e3Smatthias.ringwald         }
399f62db1e3Smatthias.ringwald     }
400f62db1e3Smatthias.ringwald     return NULL;
401f62db1e3Smatthias.ringwald }
402f62db1e3Smatthias.ringwald 
4030b9d7e78SMatthias Ringwald ///
4040b9d7e78SMatthias Ringwald 
40530725612SMatthias Ringwald void l2cap_request_can_send_now_event(uint16_t local_cid){
40630725612SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
40730725612SMatthias Ringwald     if (!channel) return;
40830725612SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
40930725612SMatthias Ringwald     l2cap_notify_channel_can_send();
41030725612SMatthias Ringwald }
41130725612SMatthias Ringwald 
4126b1fde37Smatthias.ringwald int  l2cap_can_send_packet_now(uint16_t local_cid){
4136b1fde37Smatthias.ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
4146b1fde37Smatthias.ringwald     if (!channel) return 0;
4150b9d7e78SMatthias Ringwald     return hci_can_send_acl_packet_now(channel->con_handle);
4167856fb31S[email protected] }
4177856fb31S[email protected] 
41883e7cdd9SMatthias Ringwald int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
41983e7cdd9SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
42083e7cdd9SMatthias Ringwald     if (!channel) return 0;
4210b9d7e78SMatthias Ringwald     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
42283e7cdd9SMatthias Ringwald }
42396cbd662Smatthias.ringwald uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
42496cbd662Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
42596cbd662Smatthias.ringwald     if (channel) {
42696cbd662Smatthias.ringwald         return channel->remote_mtu;
42796cbd662Smatthias.ringwald     }
42896cbd662Smatthias.ringwald     return 0;
42996cbd662Smatthias.ringwald }
43096cbd662Smatthias.ringwald 
431ec820d77SMatthias Ringwald static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
432665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
433665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
434665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
435665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4365932bd7cS[email protected]         if ( &channel->rtx == ts) {
4375932bd7cS[email protected]             return channel;
4385932bd7cS[email protected]         }
4395932bd7cS[email protected]     }
4405932bd7cS[email protected]     return NULL;
4415932bd7cS[email protected] }
4425932bd7cS[email protected] 
443ec820d77SMatthias Ringwald static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
4445932bd7cS[email protected]     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
44595d2c8f4SMatthias Ringwald     if (!channel) return;
4465932bd7cS[email protected] 
4475932bd7cS[email protected]     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
4485932bd7cS[email protected] 
4495932bd7cS[email protected]     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
4505932bd7cS[email protected]     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
4515932bd7cS[email protected]     // notify client
4525932bd7cS[email protected]     l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
4535932bd7cS[email protected] 
4545932bd7cS[email protected]     // discard channel
4559dcb2fb2S[email protected]     // no need to stop timer here, it is removed from list during timer callback
456665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4575932bd7cS[email protected]     btstack_memory_l2cap_channel_free(channel);
4585932bd7cS[email protected] }
4595932bd7cS[email protected] 
4605932bd7cS[email protected] static void l2cap_stop_rtx(l2cap_channel_t * channel){
4615932bd7cS[email protected]     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
462528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->rtx);
4635932bd7cS[email protected] }
4645932bd7cS[email protected] 
4655932bd7cS[email protected] static void l2cap_start_rtx(l2cap_channel_t * channel){
4665932bd7cS[email protected]     l2cap_stop_rtx(channel);
467cb0ff06bS[email protected]     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
468528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
469528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
470528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
4715932bd7cS[email protected] }
4725932bd7cS[email protected] 
4735932bd7cS[email protected] static void l2cap_start_ertx(l2cap_channel_t * channel){
4745932bd7cS[email protected]     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
4755932bd7cS[email protected]     l2cap_stop_rtx(channel);
476528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
477528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
478528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
4795932bd7cS[email protected] }
4805932bd7cS[email protected] 
48171de195eSMatthias Ringwald void l2cap_require_security_level_2_for_outgoing_sdp(void){
482ac301f95S[email protected]     require_security_level2_for_outgoing_sdp = 1;
483ac301f95S[email protected] }
484ac301f95S[email protected] 
485df3354fcS[email protected] static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
486235946f1SMatthias Ringwald     return (psm == BLUETOOTH_PROTOCOL_SDP) && (!require_security_level2_for_outgoing_sdp);
487df3354fcS[email protected] }
4885932bd7cS[email protected] 
4897f02f414SMatthias Ringwald static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
490a35252c8S[email protected]     if (!hci_can_send_acl_packet_now(handle)){
4919da54300S[email protected]         log_info("l2cap_send_signaling_packet, cannot send");
492b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
493b1d43497Smatthias.ringwald     }
494b1d43497Smatthias.ringwald 
4959da54300S[email protected]     // log_info("l2cap_send_signaling_packet type %u", cmd);
4962a373862S[email protected]     hci_reserve_packet_buffer();
497facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
49858de5610Smatthias.ringwald     va_list argptr;
49958de5610Smatthias.ringwald     va_start(argptr, identifier);
50070efece1S[email protected]     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
50158de5610Smatthias.ringwald     va_end(argptr);
5029da54300S[email protected]     // log_info("l2cap_send_signaling_packet con %u!", handle);
503826f7347S[email protected]     return hci_send_acl_packet_buffer(len);
50458de5610Smatthias.ringwald }
50558de5610Smatthias.ringwald 
506f511cefaSMatthias Ringwald // assumption - only on Classic connections
507b1d43497Smatthias.ringwald int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
508b1d43497Smatthias.ringwald 
509c8b9416aS[email protected]     if (!hci_is_packet_buffer_reserved()){
510c8b9416aS[email protected]         log_error("l2cap_send_prepared called without reserving packet first");
511c8b9416aS[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
512c8b9416aS[email protected]     }
513c8b9416aS[email protected] 
51458de5610Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
515b1d43497Smatthias.ringwald     if (!channel) {
5169da54300S[email protected]         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
517b1d43497Smatthias.ringwald         return -1;   // TODO: define error
5186218e6f1Smatthias.ringwald     }
5196218e6f1Smatthias.ringwald 
520fc64f94aSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
5219da54300S[email protected]         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
522a35252c8S[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
523a35252c8S[email protected]     }
524a35252c8S[email protected] 
525fc64f94aSMatthias Ringwald     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
526b1d43497Smatthias.ringwald 
52785ddcd84SMatthias Ringwald     int fcs_size = 0;
52885ddcd84SMatthias Ringwald 
52985ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
53085ddcd84SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
53185ddcd84SMatthias Ringwald         fcs_size = 2;
53285ddcd84SMatthias Ringwald     }
53385ddcd84SMatthias Ringwald #endif
53485ddcd84SMatthias Ringwald 
535f511cefaSMatthias Ringwald     // set non-flushable packet boundary flag if supported on Controller
536facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
537f511cefaSMatthias Ringwald     uint8_t packet_boundary_flag = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
53885ddcd84SMatthias Ringwald     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
53985ddcd84SMatthias Ringwald 
54085ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
54185ddcd84SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
54285ddcd84SMatthias Ringwald         // calculate FCS over l2cap data
54385ddcd84SMatthias Ringwald         uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
54485ddcd84SMatthias Ringwald         log_info("I-Frame: fcs 0x%04x", fcs);
54585ddcd84SMatthias Ringwald         little_endian_store_16(acl_buffer, 8 + len, fcs);
54658de5610Smatthias.ringwald     }
54785ddcd84SMatthias Ringwald #endif
54885ddcd84SMatthias Ringwald 
54985ddcd84SMatthias Ringwald     // send
55085ddcd84SMatthias Ringwald     return hci_send_acl_packet_buffer(len+8+fcs_size);
55185ddcd84SMatthias Ringwald }
55285ddcd84SMatthias Ringwald 
55385ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
55485ddcd84SMatthias Ringwald static inline uint16_t l2cap_encanced_control_field_for_information_frame(uint8_t tx_seq, int final, uint8_t req_seq, l2cap_segmentation_and_reassembly_t sar){
55585ddcd84SMatthias Ringwald     return (((uint16_t) sar) << 14) | (req_seq << 8) | (final << 7) | (tx_seq << 1) | 0;
55685ddcd84SMatthias Ringwald }
55785ddcd84SMatthias Ringwald #if 0
55885ddcd84SMatthias Ringwald static inline uint16_t l2cap_encanced_control_field_for_supevisor_frame(l2cap_supervisory_function_t supervisory_function, int poll, int final, uint8_t req_seq){
55985ddcd84SMatthias Ringwald     return (((uint16_t) sar) << 14) | (req_seq << 8) | (final << 7) | 1;
56085ddcd84SMatthias Ringwald }
56185ddcd84SMatthias Ringwald #endif
56285ddcd84SMatthias Ringwald static int l2cap_next_ertm_seq_nr(int seq_nr){
56385ddcd84SMatthias Ringwald     return (seq_nr + 1) & 0x3f;
56485ddcd84SMatthias Ringwald }
56585ddcd84SMatthias Ringwald #endif
56658de5610Smatthias.ringwald 
567f511cefaSMatthias Ringwald // assumption - only on Classic connections
568ce8f182eSMatthias Ringwald int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
569b1d43497Smatthias.ringwald 
570a35252c8S[email protected]     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
571a35252c8S[email protected]     if (!channel) {
572ce8f182eSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
573a35252c8S[email protected]         return -1;   // TODO: define error
574a35252c8S[email protected]     }
575a35252c8S[email protected] 
576f0efaa57S[email protected]     if (len > channel->remote_mtu){
577ce8f182eSMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
578f0efaa57S[email protected]         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
579f0efaa57S[email protected]     }
580f0efaa57S[email protected] 
581fc64f94aSMatthias Ringwald     if (!hci_can_send_acl_packet_now(channel->con_handle)){
582ce8f182eSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
583b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
584b1d43497Smatthias.ringwald     }
585b1d43497Smatthias.ringwald 
5862a373862S[email protected]     hci_reserve_packet_buffer();
587facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
588b1d43497Smatthias.ringwald 
58985ddcd84SMatthias Ringwald     int control_size = 0;
59085ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
59185ddcd84SMatthias Ringwald     // hack to send i-frames
59285ddcd84SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
59385ddcd84SMatthias Ringwald         uint16_t control = l2cap_encanced_control_field_for_information_frame(channel->next_tx_seq, 0, 0, L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU);
59485ddcd84SMatthias Ringwald         log_info("I-Frame: control 0x%04x", control);
59585ddcd84SMatthias Ringwald         little_endian_store_16(acl_buffer, 8, control);
59685ddcd84SMatthias Ringwald         channel->next_tx_seq = l2cap_next_ertm_seq_nr(channel->next_tx_seq);
59785ddcd84SMatthias Ringwald         control_size = 2;
59885ddcd84SMatthias Ringwald     }
59985ddcd84SMatthias Ringwald #endif
600b1d43497Smatthias.ringwald 
60185ddcd84SMatthias Ringwald     memcpy(&acl_buffer[8+control_size], data, len);
60285ddcd84SMatthias Ringwald 
60385ddcd84SMatthias Ringwald     return l2cap_send_prepared(local_cid, len+control_size);
604b1d43497Smatthias.ringwald }
605b1d43497Smatthias.ringwald 
606fc64f94aSMatthias Ringwald int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
607fc64f94aSMatthias Ringwald     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
6080e37e417S[email protected] }
6090e37e417S[email protected] 
61028ca2b46S[email protected] static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
61128ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
61228ca2b46S[email protected] }
61328ca2b46S[email protected] 
61428ca2b46S[email protected] static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
61528ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
61628ca2b46S[email protected] }
61709e9d05bSMatthias Ringwald #endif
61828ca2b46S[email protected] 
61928ca2b46S[email protected] 
62009e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
62109e9d05bSMatthias Ringwald static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
62209e9d05bSMatthias Ringwald 
62309e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(handle)){
62409e9d05bSMatthias Ringwald         log_info("l2cap_send_le_signaling_packet, cannot send");
62509e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
62609e9d05bSMatthias Ringwald     }
62709e9d05bSMatthias Ringwald 
62809e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
62909e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
63009e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
63109e9d05bSMatthias Ringwald     va_list argptr;
63209e9d05bSMatthias Ringwald     va_start(argptr, identifier);
63309e9d05bSMatthias Ringwald     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
63409e9d05bSMatthias Ringwald     va_end(argptr);
63509e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
63609e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len);
63709e9d05bSMatthias Ringwald }
63809e9d05bSMatthias Ringwald #endif
63909e9d05bSMatthias Ringwald 
64009e9d05bSMatthias Ringwald uint16_t l2cap_max_mtu(void){
64109e9d05bSMatthias Ringwald     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
64209e9d05bSMatthias Ringwald }
64309e9d05bSMatthias Ringwald 
64409e9d05bSMatthias Ringwald uint16_t l2cap_max_le_mtu(void){
64509e9d05bSMatthias Ringwald     return l2cap_max_mtu();
64609e9d05bSMatthias Ringwald }
647b1d43497Smatthias.ringwald 
648450ad7ecSMatthias Ringwald static uint16_t l2cap_setup_options_mtu(l2cap_channel_t * channel, uint8_t * config_options){
649450ad7ecSMatthias Ringwald     config_options[0] = 1; // MTU
650450ad7ecSMatthias Ringwald     config_options[1] = 2; // len param
651450ad7ecSMatthias Ringwald     little_endian_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
652450ad7ecSMatthias Ringwald     return 4;
653450ad7ecSMatthias Ringwald }
654450ad7ecSMatthias Ringwald 
6556dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
656450ad7ecSMatthias Ringwald static uint16_t l2cap_setup_options_ertm(l2cap_channel_t * channel, uint8_t * config_options){
6576dca2a0cSMatthias Ringwald     config_options[0] = 0x04;   // RETRANSMISSION AND FLOW CONTROL OPTION
6586dca2a0cSMatthias Ringwald     config_options[1] = 9;      // length
6596dca2a0cSMatthias Ringwald     config_options[2] = (uint8_t) channel->mode;
6607b181629SMatthias Ringwald     config_options[3] = channel->num_rx_buffers;    // == TxWindows size
661*bbc0a9e7SMatthias Ringwald     config_options[4] = channel->local_max_transmit;
662*bbc0a9e7SMatthias Ringwald     little_endian_store_16( config_options, 5, channel->local_retransmission_timeout_ms);
663*bbc0a9e7SMatthias Ringwald     little_endian_store_16( config_options, 7, channel->local_monitor_timeout_ms);
6647b181629SMatthias Ringwald     little_endian_store_16( config_options, 9, channel->local_mtu);
665450ad7ecSMatthias Ringwald     return 11;
6666dca2a0cSMatthias Ringwald }
667450ad7ecSMatthias Ringwald #endif
668450ad7ecSMatthias Ringwald 
669450ad7ecSMatthias Ringwald static uint16_t l2cap_setup_options(l2cap_channel_t * channel, uint8_t * config_options){
670450ad7ecSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
671450ad7ecSMatthias Ringwald     // use ERTM options if supported
672450ad7ecSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
673450ad7ecSMatthias Ringwald     if ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE) && (connection->l2cap_state.extended_feature_mask & 0x08)){
674450ad7ecSMatthias Ringwald         return l2cap_setup_options_ertm(channel, config_options);
675450ad7ecSMatthias Ringwald 
676450ad7ecSMatthias Ringwald     }
677450ad7ecSMatthias Ringwald #endif
678450ad7ecSMatthias Ringwald     return l2cap_setup_options_mtu(channel, config_options);
6796dca2a0cSMatthias Ringwald }
6806dca2a0cSMatthias Ringwald 
6811b9cb13dSMatthias Ringwald static uint32_t l2cap_extended_features_mask(void){
6821b9cb13dSMatthias Ringwald     // extended features request supported, features: fixed channels, unicast connectionless data reception
6831b9cb13dSMatthias Ringwald     uint32_t features = 0x280;
6841b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
6851b9cb13dSMatthias Ringwald     features |= 0x0008;
6861b9cb13dSMatthias Ringwald #endif
6871b9cb13dSMatthias Ringwald     return features;
6881b9cb13dSMatthias Ringwald }
6891b9cb13dSMatthias Ringwald 
6908158c421Smatthias.ringwald // MARK: L2CAP_RUN
6912cd0be45Smatthias.ringwald // process outstanding signaling tasks
6927f02f414SMatthias Ringwald static void l2cap_run(void){
6932b83fb7dSmatthias.ringwald 
69422c29ab4SMatthias Ringwald     // log_info("l2cap_run: entered");
69522c29ab4SMatthias Ringwald 
6962b83fb7dSmatthias.ringwald     // check pending signaling responses
6972b83fb7dSmatthias.ringwald     while (signaling_responses_pending){
6982b83fb7dSmatthias.ringwald 
6992b83fb7dSmatthias.ringwald         hci_con_handle_t handle = signaling_responses[0].handle;
700a35252c8S[email protected] 
701a35252c8S[email protected]         if (!hci_can_send_acl_packet_now(handle)) break;
702a35252c8S[email protected] 
7032b83fb7dSmatthias.ringwald         uint8_t  sig_id        = signaling_responses[0].sig_id;
704e74c5f58SMatthias Ringwald         uint8_t  response_code = signaling_responses[0].code;
7052b360848Smatthias.ringwald         uint16_t infoType      = signaling_responses[0].data;  // INFORMATION_REQUEST
70663a7246aSmatthias.ringwald         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
707b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
708b3264428SMatthias Ringwald         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
709b3264428SMatthias Ringwald #endif
710f3963406SMatthias Ringwald         UNUSED(infoType);
71109e9d05bSMatthias Ringwald 
712f53da564S[email protected]         // remove first item before sending (to avoid sending response mutliple times)
713f53da564S[email protected]         signaling_responses_pending--;
714f53da564S[email protected]         int i;
715f53da564S[email protected]         for (i=0; i < signaling_responses_pending; i++){
716f53da564S[email protected]             memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t));
717f53da564S[email protected]         }
718f53da564S[email protected] 
719f53da564S[email protected]         switch (response_code){
72009e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
7212b360848Smatthias.ringwald             case CONNECTION_REQUEST:
722e74c5f58SMatthias Ringwald                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
7232bd8b7e7S[email protected]                 // also disconnect if result is 0x0003 - security blocked
7244d816277S[email protected]                 if (result == 0x0003){
7252bd8b7e7S[email protected]                     hci_disconnect_security_block(handle);
7264d816277S[email protected]                 }
7272b360848Smatthias.ringwald                 break;
7282b83fb7dSmatthias.ringwald             case ECHO_REQUEST:
7292b83fb7dSmatthias.ringwald                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
7302b83fb7dSmatthias.ringwald                 break;
7312b83fb7dSmatthias.ringwald             case INFORMATION_REQUEST:
7323b0484b3S[email protected]                 switch (infoType){
7333b0484b3S[email protected]                     case 1: { // Connectionless MTU
7343b0484b3S[email protected]                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
7353b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(connectionless_mtu), &connectionless_mtu);
7363b0484b3S[email protected]                         }
737202c8a4cSMatthias Ringwald                         break;
7383b0484b3S[email protected]                     case 2: {  // Extended Features Supported
7391b9cb13dSMatthias Ringwald                             uint32_t features = l2cap_extended_features_mask();
7403b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(features), &features);
7413b0484b3S[email protected]                         }
742202c8a4cSMatthias Ringwald                         break;
7433b0484b3S[email protected]                     case 3: { // Fixed Channels Supported
7443b0484b3S[email protected]                             uint8_t map[8];
7453b0484b3S[email protected]                             memset(map, 0, 8);
746288636a2SMatthias Ringwald                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
7473b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(map), &map);
7483b0484b3S[email protected]                         }
749202c8a4cSMatthias Ringwald                         break;
7503b0484b3S[email protected]                     default:
7512b83fb7dSmatthias.ringwald                         // all other types are not supported
7522b83fb7dSmatthias.ringwald                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
7533b0484b3S[email protected]                         break;
7542b83fb7dSmatthias.ringwald                 }
7552b83fb7dSmatthias.ringwald                 break;
75663a7246aSmatthias.ringwald             case COMMAND_REJECT:
7575ca8d57bS[email protected]                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
75863f0ac45SMatthias Ringwald                 break;
75909e9d05bSMatthias Ringwald #endif
760a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
76163f0ac45SMatthias Ringwald             case LE_CREDIT_BASED_CONNECTION_REQUEST:
76263f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
76363f0ac45SMatthias Ringwald                 break;
76470efece1S[email protected]             case COMMAND_REJECT_LE:
76570efece1S[email protected]                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
76663a7246aSmatthias.ringwald                 break;
76770efece1S[email protected] #endif
7682b83fb7dSmatthias.ringwald             default:
7692b83fb7dSmatthias.ringwald                 // should not happen
7702b83fb7dSmatthias.ringwald                 break;
7712b83fb7dSmatthias.ringwald         }
7722b83fb7dSmatthias.ringwald     }
7732b83fb7dSmatthias.ringwald 
774665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
775f3963406SMatthias Ringwald     UNUSED(it);
77609e9d05bSMatthias Ringwald 
7771b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
7781b9cb13dSMatthias Ringwald     // send l2cap information request if neccessary
7791b9cb13dSMatthias Ringwald     hci_connections_get_iterator(&it);
7801b9cb13dSMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
7811b9cb13dSMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
7821b9cb13dSMatthias Ringwald         if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST){
7831b9cb13dSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
7841b9cb13dSMatthias Ringwald             // send information request for extended features
7851b9cb13dSMatthias Ringwald             uint8_t sig_id = l2cap_next_sig_id();
7861b9cb13dSMatthias Ringwald             uint8_t info_type = 2;
7871b9cb13dSMatthias Ringwald             l2cap_send_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
7881b9cb13dSMatthias Ringwald             return;
7891b9cb13dSMatthias Ringwald         }
7901b9cb13dSMatthias Ringwald     }
7911b9cb13dSMatthias Ringwald #endif
7921b9cb13dSMatthias Ringwald 
79309e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
79443ec931dSMatthias Ringwald     uint8_t  config_options[10];
795665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
796665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
797baf94f06S[email protected] 
798665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
79922c29ab4SMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
8002cd0be45Smatthias.ringwald         switch (channel->state){
8012cd0be45Smatthias.ringwald 
802df3354fcS[email protected]             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
803ad671560S[email protected]             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
804fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
805a00031e2S[email protected]                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
806ad671560S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
807fc64f94aSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
808ad671560S[email protected]                 }
809ad671560S[email protected]                 break;
810ad671560S[email protected] 
81102b22dc4Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
812baf94f06S[email protected]                 if (!hci_can_send_command_packet_now()) break;
81364472d52Smatthias.ringwald                 // send connection request - set state first
81464472d52Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
81502b22dc4Smatthias.ringwald                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
8168f8108aaSmatthias.ringwald                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
81702b22dc4Smatthias.ringwald                 break;
81802b22dc4Smatthias.ringwald 
819e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
820fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
82122c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
822fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
823e7ff783cSmatthias.ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
8249dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
825665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
826d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
827e7ff783cSmatthias.ringwald                 break;
828e7ff783cSmatthias.ringwald 
829552d92a1Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
830fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
831fa8473a4Smatthias.ringwald                 channel->state = L2CAP_STATE_CONFIG;
83228ca2b46S[email protected]                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
833fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
834552d92a1Smatthias.ringwald                 break;
835552d92a1Smatthias.ringwald 
8366fdcc387Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
837fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
8386fdcc387Smatthias.ringwald                 // success, start l2cap handshake
839b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
8406fdcc387Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
841fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
8425932bd7cS[email protected]                 l2cap_start_rtx(channel);
8436fdcc387Smatthias.ringwald                 break;
8446fdcc387Smatthias.ringwald 
845fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
846fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
84773cf2b3dSmatthias.ringwald                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
84863a7246aSmatthias.ringwald                     uint16_t flags = 0;
84928ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
85063a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
85163a7246aSmatthias.ringwald                         flags = 1;
85263a7246aSmatthias.ringwald                     } else {
85328ca2b46S[email protected]                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
85463a7246aSmatthias.ringwald                     }
85563a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
856ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
857fc64f94aSMatthias Ringwald                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS, 0, NULL);
858ac8f1300SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
859ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
860ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
861ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
8626dca2a0cSMatthias Ringwald                         uint16_t options_size = l2cap_setup_options(channel, config_options);
863ac8f1300SMatthias Ringwald                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS, options_size, &config_options);
864ac8f1300SMatthias Ringwald #endif
865ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
86663a7246aSmatthias.ringwald                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
867ac8f1300SMatthias Ringwald                         uint16_t options_size = l2cap_setup_options(channel, config_options);
868ac8f1300SMatthias Ringwald                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, options_size, &config_options);
86963a7246aSmatthias.ringwald                     } else {
870ac8f1300SMatthias Ringwald                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
87163a7246aSmatthias.ringwald                     }
87263a7246aSmatthias.ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
873fa8473a4Smatthias.ringwald                 }
87473cf2b3dSmatthias.ringwald                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
87528ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
87628ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
877b1988dceSmatthias.ringwald                     channel->local_sig_id = l2cap_next_sig_id();
8786dca2a0cSMatthias Ringwald                     uint16_t options_size = l2cap_setup_options(channel, config_options);
8796dca2a0cSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options);
8805932bd7cS[email protected]                     l2cap_start_rtx(channel);
881fa8473a4Smatthias.ringwald                 }
882fa8473a4Smatthias.ringwald                 if (l2cap_channel_ready_for_open(channel)){
883552d92a1Smatthias.ringwald                     channel->state = L2CAP_STATE_OPEN;
884552d92a1Smatthias.ringwald                     l2cap_emit_channel_opened(channel, 0);  // success
885fa8473a4Smatthias.ringwald                 }
886552d92a1Smatthias.ringwald                 break;
887552d92a1Smatthias.ringwald 
888e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
889fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
89022c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
891fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
8925932bd7cS[email protected]                 // 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 :)
893756102d3Smatthias.ringwald                 l2cap_finialize_channel_close(channel);  // -- remove from list
894e7ff783cSmatthias.ringwald                 break;
895e7ff783cSmatthias.ringwald 
896e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
897fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
898b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
8992cd0be45Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
900fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
9012cd0be45Smatthias.ringwald                 break;
9022cd0be45Smatthias.ringwald             default:
9032cd0be45Smatthias.ringwald                 break;
9042cd0be45Smatthias.ringwald         }
9052cd0be45Smatthias.ringwald     }
90609e9d05bSMatthias Ringwald #endif
907da886c03S[email protected] 
908cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
909efedfb4cSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
910efedfb4cSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
9117f107edaSMatthias Ringwald         uint8_t  * acl_buffer;
9127f107edaSMatthias Ringwald         uint8_t  * l2cap_payload;
9137f107edaSMatthias Ringwald         uint16_t pos;
9147f107edaSMatthias Ringwald         uint16_t payload_size;
915efedfb4cSMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
916efedfb4cSMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
917efedfb4cSMatthias Ringwald         switch (channel->state){
9185cb87675SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
9195cb87675SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
9205cb87675SMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
9215cb87675SMatthias Ringwald                 // le psm, source cid, mtu, mps, initial credits
9221b8b8d05SMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
92363f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
92463f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
92563f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, LE_CREDIT_BASED_CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid, channel->local_mtu, 23, channel->credits_incoming);
9265cb87675SMatthias Ringwald                 break;
92723017473SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
92823017473SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
92923017473SMatthias Ringwald                 // TODO: support larger MPS
93023017473SMatthias Ringwald                 channel->state = L2CAP_STATE_OPEN;
93163f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
93263f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
93363f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->local_mtu, 23, channel->credits_incoming, 0);
93464e11ca9SMatthias Ringwald                 // notify client
93544276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0);
93623017473SMatthias Ringwald                 break;
937e7d0c9aaSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
938e7d0c9aaSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
939e7d0c9aaSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
94063f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
941e7d0c9aaSMatthias Ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
942e7d0c9aaSMatthias Ringwald                 l2cap_stop_rtx(channel);
943e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
944e7d0c9aaSMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
945e7d0c9aaSMatthias Ringwald                 break;
9467f107edaSMatthias Ringwald             case L2CAP_STATE_OPEN:
94785aeef60SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
94885aeef60SMatthias Ringwald 
94985aeef60SMatthias Ringwald                 // send credits
95085aeef60SMatthias Ringwald                 if (channel->new_credits_incoming){
95185aeef60SMatthias Ringwald                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
95285aeef60SMatthias Ringwald                     channel->local_sig_id = l2cap_next_sig_id();
95385aeef60SMatthias Ringwald                     uint16_t new_credits = channel->new_credits_incoming;
95485aeef60SMatthias Ringwald                     channel->new_credits_incoming = 0;
95585aeef60SMatthias Ringwald                     channel->credits_incoming += new_credits;
95685aeef60SMatthias Ringwald                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
95785aeef60SMatthias Ringwald                     break;
95885aeef60SMatthias Ringwald                 }
95985aeef60SMatthias Ringwald 
96085aeef60SMatthias Ringwald                 // send data
9617f107edaSMatthias Ringwald                 if (!channel->send_sdu_buffer) break;
9627f107edaSMatthias Ringwald                 if (!channel->credits_outgoing) break;
96385aeef60SMatthias Ringwald 
9647f107edaSMatthias Ringwald                 // send part of SDU
9657f107edaSMatthias Ringwald                 hci_reserve_packet_buffer();
9667f107edaSMatthias Ringwald                 acl_buffer = hci_get_outgoing_packet_buffer();
9677f107edaSMatthias Ringwald                 l2cap_payload = acl_buffer + 8;
9687f107edaSMatthias Ringwald                 pos = 0;
9697f107edaSMatthias Ringwald                 if (!channel->send_sdu_pos){
9707f107edaSMatthias Ringwald                     // store SDU len
9717f107edaSMatthias Ringwald                     channel->send_sdu_pos += 2;
9727f107edaSMatthias Ringwald                     little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
9737f107edaSMatthias Ringwald                     pos += 2;
9747f107edaSMatthias Ringwald                 }
9757f107edaSMatthias Ringwald                 payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
97685aeef60SMatthias Ringwald                 log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
9777f107edaSMatthias Ringwald                 memcpy(&l2cap_payload[pos], &channel->send_sdu_buffer[channel->send_sdu_pos-2], payload_size); // -2 for virtual SDU len
9787f107edaSMatthias Ringwald                 pos += payload_size;
9797f107edaSMatthias Ringwald                 channel->send_sdu_pos += payload_size;
980f511cefaSMatthias Ringwald                 l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
9817f107edaSMatthias Ringwald                 // done
9827f107edaSMatthias Ringwald 
98385aeef60SMatthias Ringwald                 channel->credits_outgoing--;
9847f107edaSMatthias Ringwald 
9857f107edaSMatthias Ringwald                 if (channel->send_sdu_pos >= channel->send_sdu_len + 2){
9867f107edaSMatthias Ringwald                     channel->send_sdu_buffer = NULL;
98744276248SMatthias Ringwald                     // send done event
98844276248SMatthias Ringwald                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
98944276248SMatthias Ringwald                     // inform about can send now
99044276248SMatthias Ringwald                     l2cap_le_notify_channel_can_send(channel);
9917f107edaSMatthias Ringwald                 }
9927f107edaSMatthias Ringwald                 hci_send_acl_packet_buffer(8 + pos);
9937f107edaSMatthias Ringwald                 break;
994828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
995828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
996828a7f7aSMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
997828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
998828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
999828a7f7aSMatthias Ringwald                 break;
1000828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1001828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1002828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1003828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1004828a7f7aSMatthias Ringwald                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
1005828a7f7aSMatthias Ringwald                 break;
1006efedfb4cSMatthias Ringwald             default:
1007efedfb4cSMatthias Ringwald                 break;
1008efedfb4cSMatthias Ringwald         }
1009efedfb4cSMatthias Ringwald     }
101009e9d05bSMatthias Ringwald #endif
1011efedfb4cSMatthias Ringwald 
101209e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
1013da886c03S[email protected]     // send l2cap con paramter update if necessary
1014da886c03S[email protected]     hci_connections_get_iterator(&it);
1015665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
1016665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
10175d14fa8fSMatthias Ringwald         if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue;
1018b68d7bc3SMatthias Ringwald         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
1019da886c03S[email protected]         switch (connection->le_con_parameter_update_state){
1020b68d7bc3SMatthias Ringwald             case CON_PARAMETER_UPDATE_SEND_REQUEST:
1021b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1022b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier,
1023b68d7bc3SMatthias Ringwald                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
1024b68d7bc3SMatthias Ringwald                 break;
1025da886c03S[email protected]             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
1026b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
1027b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
1028da886c03S[email protected]                 break;
1029da886c03S[email protected]             case CON_PARAMETER_UPDATE_DENY:
1030b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1031b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
1032da886c03S[email protected]                 break;
1033da886c03S[email protected]             default:
1034da886c03S[email protected]                 break;
1035da886c03S[email protected]         }
1036da886c03S[email protected]     }
10374d7157c3S[email protected] #endif
1038da886c03S[email protected] 
103922c29ab4SMatthias Ringwald     // log_info("l2cap_run: exit");
10402cd0be45Smatthias.ringwald }
10412cd0be45Smatthias.ringwald 
104209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1043fc64f94aSMatthias Ringwald static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
10442df5dadcS[email protected]     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
10455533f01eS[email protected]         log_info("l2cap_handle_connection_complete expected state");
10462df5dadcS[email protected]         // success, start l2cap handshake
1047fc64f94aSMatthias Ringwald         channel->con_handle = con_handle;
10482df5dadcS[email protected]         // check remote SSP feature first
10492df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
10502df5dadcS[email protected]     }
10512df5dadcS[email protected] }
10522df5dadcS[email protected] 
10531b9cb13dSMatthias Ringwald static void l2cap_ready_to_connect(l2cap_channel_t * channel){
10541b9cb13dSMatthias Ringwald 
10551b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
105627e0774aSMatthias Ringwald     // assumption: outgoing connection
10571b9cb13dSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
10581b9cb13dSMatthias Ringwald     if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
10591b9cb13dSMatthias Ringwald         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
10601b9cb13dSMatthias Ringwald         channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
10611b9cb13dSMatthias Ringwald         return;
10621b9cb13dSMatthias Ringwald     }
10631b9cb13dSMatthias Ringwald #endif
10641b9cb13dSMatthias Ringwald 
10651b9cb13dSMatthias Ringwald     // fine, go ahead
10661b9cb13dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
10671b9cb13dSMatthias Ringwald }
10681b9cb13dSMatthias Ringwald 
10692df5dadcS[email protected] static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
10702df5dadcS[email protected]     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
10712df5dadcS[email protected] 
10722df5dadcS[email protected]     // we have been waiting for remote supported features, if both support SSP,
1073ac301f95S[email protected]     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));
1074fc64f94aSMatthias Ringwald     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
10752df5dadcS[email protected]         // request security level 2
10762df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
1077fc64f94aSMatthias Ringwald         gap_request_security_level(channel->con_handle, LEVEL_2);
10782df5dadcS[email protected]         return;
10792df5dadcS[email protected]     }
10801b9cb13dSMatthias Ringwald 
10811b9cb13dSMatthias Ringwald     l2cap_ready_to_connect(channel);
10822df5dadcS[email protected] }
108309e9d05bSMatthias Ringwald #endif
10842df5dadcS[email protected] 
108509e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
1086da144af5SMatthias Ringwald static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, bd_addr_t address, bd_addr_type_t address_type,
1087da144af5SMatthias Ringwald     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
1088da144af5SMatthias Ringwald 
1089da144af5SMatthias Ringwald     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1090da144af5SMatthias Ringwald     if (!channel) {
1091da144af5SMatthias Ringwald         return NULL;
1092da144af5SMatthias Ringwald     }
1093da144af5SMatthias Ringwald 
1094da144af5SMatthias Ringwald      // Init memory (make valgrind happy)
1095da144af5SMatthias Ringwald     memset(channel, 0, sizeof(l2cap_channel_t));
1096da144af5SMatthias Ringwald 
1097da144af5SMatthias Ringwald     // fill in
1098da144af5SMatthias Ringwald     channel->packet_handler = packet_handler;
1099da144af5SMatthias Ringwald     bd_addr_copy(channel->address, address);
1100da144af5SMatthias Ringwald     channel->address_type = address_type;
1101da144af5SMatthias Ringwald     channel->psm = psm;
1102da144af5SMatthias Ringwald     channel->local_mtu  = local_mtu;
1103da144af5SMatthias Ringwald     channel->remote_mtu = L2CAP_MINIMAL_MTU;
1104da144af5SMatthias Ringwald     channel->required_security_level = security_level;
1105da144af5SMatthias Ringwald 
1106da144af5SMatthias Ringwald     //
1107da144af5SMatthias Ringwald     channel->local_cid = l2cap_next_local_cid();
1108da144af5SMatthias Ringwald     channel->con_handle = 0;
1109da144af5SMatthias Ringwald 
1110da144af5SMatthias Ringwald     // set initial state
1111da144af5SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
1112da144af5SMatthias Ringwald     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
1113da144af5SMatthias Ringwald     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
1114da144af5SMatthias Ringwald     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
1115da144af5SMatthias Ringwald     return channel;
1116da144af5SMatthias Ringwald }
111709e9d05bSMatthias Ringwald #endif
111809e9d05bSMatthias Ringwald 
111909e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1120da144af5SMatthias Ringwald 
11219077cb15SMatthias Ringwald /**
11229077cb15SMatthias Ringwald  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
11239077cb15SMatthias Ringwald  * @param packet_handler
11249077cb15SMatthias Ringwald  * @param address
11259077cb15SMatthias Ringwald  * @param psm
11269077cb15SMatthias Ringwald  * @param mtu
11279077cb15SMatthias Ringwald  * @param local_cid
11289077cb15SMatthias Ringwald  */
11299077cb15SMatthias Ringwald 
11309d139fbaSMatthias Ringwald 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){
11319d139fbaSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
11329d139fbaSMatthias Ringwald     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1133da144af5SMatthias Ringwald 
11349d139fbaSMatthias Ringwald     log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x mtu %u -> local mtu %u", bd_addr_to_str(address), psm, mtu, local_mtu);
1135da144af5SMatthias Ringwald 
1136da144af5SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
1137fc64f94aSMatthias Ringwald     if (!channel) {
11389077cb15SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
11399077cb15SMatthias Ringwald     }
11409077cb15SMatthias Ringwald 
11411b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
11421b9cb13dSMatthias Ringwald     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
11431b9cb13dSMatthias Ringwald #endif
11441b9cb13dSMatthias Ringwald 
11459077cb15SMatthias Ringwald     // add to connections list
1146fc64f94aSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
11479077cb15SMatthias Ringwald 
11489077cb15SMatthias Ringwald     // store local_cid
11499077cb15SMatthias Ringwald     if (out_local_cid){
1150fc64f94aSMatthias Ringwald        *out_local_cid = channel->local_cid;
11519077cb15SMatthias Ringwald     }
11529077cb15SMatthias Ringwald 
11539077cb15SMatthias Ringwald     // check if hci connection is already usable
11549077cb15SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
11559077cb15SMatthias Ringwald     if (conn){
1156add0254bSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
1157fc64f94aSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
11589077cb15SMatthias Ringwald         // check if remote supported fearures are already received
11599077cb15SMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
1160fc64f94aSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
11619077cb15SMatthias Ringwald         }
11629077cb15SMatthias Ringwald     }
11639077cb15SMatthias Ringwald 
11649077cb15SMatthias Ringwald     l2cap_run();
11659077cb15SMatthias Ringwald 
11669077cb15SMatthias Ringwald     return 0;
11679077cb15SMatthias Ringwald }
11689077cb15SMatthias Ringwald 
11691b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
11707b181629SMatthias Ringwald 
11712b70d705SMatthias Ringwald static uint8_t l2cap_ertm_validate_local_config(uint8_t max_transmit, uint16_t retransmission_timeout_ms,
11722b70d705SMatthias Ringwald     uint16_t monitor_timeout_ms, uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size){
11732b70d705SMatthias Ringwald     UNUSED(buffer);
11742b70d705SMatthias Ringwald     UNUSED(size);
11752b70d705SMatthias Ringwald 
11762b70d705SMatthias Ringwald     uint8_t result = ERROR_CODE_SUCCESS;
11772b70d705SMatthias Ringwald     if (max_transmit < 1){
11782b70d705SMatthias Ringwald         log_error("max_transmit must be >= 1");
11792b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
11802b70d705SMatthias Ringwald     }
11812b70d705SMatthias Ringwald     if (retransmission_timeout_ms < 2000){
11822b70d705SMatthias Ringwald         log_error("retransmission_timeout_ms must be >= 2000 ms");
11832b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
11842b70d705SMatthias Ringwald     }
11852b70d705SMatthias Ringwald     if (monitor_timeout_ms < 12000){
11862b70d705SMatthias Ringwald         log_error("monitor_timeout_ms must be >= 12000 ms");
11872b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
11882b70d705SMatthias Ringwald     }
11892b70d705SMatthias Ringwald     if (num_rx_buffers < 1){
11902b70d705SMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
11912b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
11922b70d705SMatthias Ringwald     }
11932b70d705SMatthias Ringwald     if (num_tx_buffers < 1){
11942b70d705SMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
11952b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
11962b70d705SMatthias Ringwald     }
11972b70d705SMatthias Ringwald     return result;
11982b70d705SMatthias Ringwald }
11992b70d705SMatthias Ringwald 
12007b181629SMatthias Ringwald static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, int ertm_mandatory, uint8_t max_transmit,
12017b181629SMatthias Ringwald     uint16_t retransmission_timeout_ms, uint16_t monitor_timeout_ms, uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size){
12027b181629SMatthias Ringwald 
12037b181629SMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
12047b181629SMatthias Ringwald     channel->ertm_mandatory = ertm_mandatory;
1205*bbc0a9e7SMatthias Ringwald     channel->local_max_transmit = max_transmit;
1206*bbc0a9e7SMatthias Ringwald     channel->local_retransmission_timeout_ms = retransmission_timeout_ms;
1207*bbc0a9e7SMatthias Ringwald     channel->local_monitor_timeout_ms = monitor_timeout_ms;
12087b181629SMatthias Ringwald     channel->num_rx_buffers = num_rx_buffers;
12097b181629SMatthias Ringwald     channel->num_tx_buffers = num_tx_buffers;
12107b181629SMatthias Ringwald 
12117b181629SMatthias Ringwald     // TODO: align buffer pointer
12127b181629SMatthias Ringwald     uint32_t pos = 0;
12137b181629SMatthias Ringwald     channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) &buffer[pos];
12147b181629SMatthias Ringwald     pos += num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
12157b181629SMatthias Ringwald     channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) &buffer[pos];
12167b181629SMatthias Ringwald     pos += num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
12177b181629SMatthias Ringwald     // calculate MTU
12187b181629SMatthias Ringwald     channel->local_mtu = (size - pos) / (num_rx_buffers + num_tx_buffers);
12197b181629SMatthias Ringwald     log_info("Local ERTM MTU: %u", channel->local_mtu);
12207b181629SMatthias Ringwald     channel->rx_packets_data = &buffer[pos];
12217b181629SMatthias Ringwald     pos += num_rx_buffers * channel->local_mtu;
12227b181629SMatthias Ringwald     channel->tx_packets_data = &buffer[pos];
12237b181629SMatthias Ringwald     log_info("RX packets %p, TX packets %p", channel->rx_packets_data, channel->tx_packets_data);
12247b181629SMatthias Ringwald }
12257b181629SMatthias Ringwald 
1226501329faSMatthias Ringwald uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
1227501329faSMatthias Ringwald     int ertm_mandatory, uint8_t max_transmit, uint16_t retransmission_timeout_ms, uint16_t monitor_timeout_ms,
1228501329faSMatthias Ringwald     uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
1229501329faSMatthias Ringwald 
12301b9cb13dSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
1231501329faSMatthias Ringwald     uint16_t local_mtu = l2cap_max_mtu();
12321b9cb13dSMatthias Ringwald 
1233501329faSMatthias Ringwald     log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x -> local mtu %u", bd_addr_to_str(address), psm, local_mtu);
12341b9cb13dSMatthias Ringwald 
12352b70d705SMatthias Ringwald     // validate local config
12362b70d705SMatthias Ringwald     uint8_t result = l2cap_ertm_validate_local_config(max_transmit, retransmission_timeout_ms, monitor_timeout_ms, num_tx_buffers, num_rx_buffers, buffer, size);
12372b70d705SMatthias Ringwald     if (result) return result;
12382b70d705SMatthias Ringwald 
1239501329faSMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
12401b9cb13dSMatthias Ringwald     if (!channel) {
12411b9cb13dSMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
12421b9cb13dSMatthias Ringwald     }
12431b9cb13dSMatthias Ringwald 
12447b181629SMatthias Ringwald     // configure ERTM
12457b181629SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_mandatory, max_transmit, retransmission_timeout_ms,
12467b181629SMatthias Ringwald         monitor_timeout_ms, num_tx_buffers, num_rx_buffers, buffer, size);
12471b9cb13dSMatthias Ringwald 
12481b9cb13dSMatthias Ringwald     // add to connections list
12491b9cb13dSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
12501b9cb13dSMatthias Ringwald 
12511b9cb13dSMatthias Ringwald     // store local_cid
12521b9cb13dSMatthias Ringwald     if (out_local_cid){
12531b9cb13dSMatthias Ringwald        *out_local_cid = channel->local_cid;
12541b9cb13dSMatthias Ringwald     }
12551b9cb13dSMatthias Ringwald 
12561b9cb13dSMatthias Ringwald     // check if hci connection is already usable
12571b9cb13dSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
12581b9cb13dSMatthias Ringwald     if (conn){
12591b9cb13dSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
12601b9cb13dSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
12611b9cb13dSMatthias Ringwald         // check if remote supported fearures are already received
12621b9cb13dSMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
12631b9cb13dSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
12641b9cb13dSMatthias Ringwald         }
12651b9cb13dSMatthias Ringwald     }
12661b9cb13dSMatthias Ringwald 
12671b9cb13dSMatthias Ringwald     l2cap_run();
12681b9cb13dSMatthias Ringwald 
12691b9cb13dSMatthias Ringwald     return 0;
12701b9cb13dSMatthias Ringwald }
12711b9cb13dSMatthias Ringwald #endif
12721b9cb13dSMatthias Ringwald 
1273ce8f182eSMatthias Ringwald void
1274ce8f182eSMatthias Ringwald l2cap_disconnect(uint16_t local_cid, uint8_t reason){
1275e0abb8e7S[email protected]     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
1276b35f641cSmatthias.ringwald     // find channel for local_cid
1277b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1278f62db1e3Smatthias.ringwald     if (channel) {
1279e7ff783cSmatthias.ringwald         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1280f62db1e3Smatthias.ringwald     }
12812cd0be45Smatthias.ringwald     // process
12822cd0be45Smatthias.ringwald     l2cap_run();
128343625864Smatthias.ringwald }
12841e6aba47Smatthias.ringwald 
1285afde0c52Smatthias.ringwald static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
1286665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1287665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1288665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1289665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1290058e3d6bSMatthias Ringwald         if ( bd_addr_cmp( channel->address, address) != 0) continue;
1291c22aecc9S[email protected]         // channel for this address found
1292c22aecc9S[email protected]         switch (channel->state){
1293c22aecc9S[email protected]             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
1294c22aecc9S[email protected]             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1295afde0c52Smatthias.ringwald                 // failure, forward error code
1296afde0c52Smatthias.ringwald                 l2cap_emit_channel_opened(channel, status);
1297afde0c52Smatthias.ringwald                 // discard channel
12989dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
1299665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1300d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
1301c22aecc9S[email protected]                 break;
1302c22aecc9S[email protected]             default:
1303c22aecc9S[email protected]                 break;
1304afde0c52Smatthias.ringwald         }
1305afde0c52Smatthias.ringwald     }
1306afde0c52Smatthias.ringwald }
1307afde0c52Smatthias.ringwald 
1308afde0c52Smatthias.ringwald static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
1309665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1310665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1311665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1312665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1313058e3d6bSMatthias Ringwald         if ( ! bd_addr_cmp( channel->address, address) ){
13142df5dadcS[email protected]             l2cap_handle_connection_complete(handle, channel);
1315afde0c52Smatthias.ringwald         }
1316afde0c52Smatthias.ringwald     }
13176fdcc387Smatthias.ringwald     // process
13186fdcc387Smatthias.ringwald     l2cap_run();
1319afde0c52Smatthias.ringwald }
132009e9d05bSMatthias Ringwald #endif
1321b448a0e7Smatthias.ringwald 
132233c40538SMatthias Ringwald static void l2cap_notify_channel_can_send(void){
132309e9d05bSMatthias Ringwald 
132409e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
132533c40538SMatthias Ringwald     btstack_linked_list_iterator_t it;
132633c40538SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
132733c40538SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
132833c40538SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
132933c40538SMatthias Ringwald         if (!channel->waiting_for_can_send_now) continue;
1330fc64f94aSMatthias Ringwald         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
133133c40538SMatthias Ringwald         channel->waiting_for_can_send_now = 0;
133234e7e577SMatthias Ringwald         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
133333c40538SMatthias Ringwald     }
133409e9d05bSMatthias Ringwald #endif
133544276248SMatthias Ringwald 
13362125de09SMatthias Ringwald     int i;
13372125de09SMatthias Ringwald     for (i=0;i<L2CAP_FIXED_CHANNEL_TABLE_SIZE;i++){
1338773c4106SMatthias Ringwald         if (!fixed_channels[i].callback) continue;
13392125de09SMatthias Ringwald         if (!fixed_channels[i].waiting_for_can_send_now) continue;
134035454696SMatthias Ringwald         int can_send = 0;
134134e7e577SMatthias Ringwald         if (l2cap_fixed_channel_table_index_is_le(i)){
134235454696SMatthias Ringwald #ifdef ENABLE_BLE
134334e7e577SMatthias Ringwald             can_send = hci_can_send_acl_le_packet_now();
134435454696SMatthias Ringwald #endif
134534e7e577SMatthias Ringwald         } else {
134635454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
134734e7e577SMatthias Ringwald             can_send = hci_can_send_acl_classic_packet_now();
134835454696SMatthias Ringwald #endif
134934e7e577SMatthias Ringwald         }
135034e7e577SMatthias Ringwald         if (!can_send) continue;
135134e7e577SMatthias Ringwald         fixed_channels[i].waiting_for_can_send_now = 0;
135234e7e577SMatthias Ringwald         l2cap_emit_can_send_now(fixed_channels[i].callback, l2cap_fixed_channel_table_channel_id_for_index(i));
13532125de09SMatthias Ringwald     }
135433c40538SMatthias Ringwald }
135533c40538SMatthias Ringwald 
1356d9a7306aSMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
1357afde0c52Smatthias.ringwald 
13589ec2630cSMatthias Ringwald     UNUSED(packet_type);
13599ec2630cSMatthias Ringwald     UNUSED(cid);
13609ec2630cSMatthias Ringwald     UNUSED(size);
13619ec2630cSMatthias Ringwald 
1362afde0c52Smatthias.ringwald     bd_addr_t address;
1363afde0c52Smatthias.ringwald     hci_con_handle_t handle;
13642d00edd4Smatthias.ringwald     int hci_con_used;
136509e9d05bSMatthias Ringwald     btstack_linked_list_iterator_t it;
136609e9d05bSMatthias Ringwald 
136709e9d05bSMatthias Ringwald     // avoid unused warnings
1368f3963406SMatthias Ringwald     UNUSED(address);
1369f3963406SMatthias Ringwald     UNUSED(hci_con_used);
1370f3963406SMatthias Ringwald     UNUSED(it);
1371f22209dfSMatthias Ringwald     UNUSED(handle);
1372afde0c52Smatthias.ringwald 
13730e2df43fSMatthias Ringwald     switch(hci_event_packet_get_type(packet)){
1374afde0c52Smatthias.ringwald 
137509e9d05bSMatthias Ringwald         // Notify channel packet handler if they can send now
137609e9d05bSMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
137709e9d05bSMatthias Ringwald         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
137809e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
137909e9d05bSMatthias Ringwald             l2cap_notify_channel_can_send();
138009e9d05bSMatthias Ringwald             break;
138109e9d05bSMatthias Ringwald 
138209e9d05bSMatthias Ringwald         case HCI_EVENT_COMMAND_STATUS:
138309e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
138409e9d05bSMatthias Ringwald             break;
138509e9d05bSMatthias Ringwald 
138609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1387afde0c52Smatthias.ringwald         // handle connection complete events
1388afde0c52Smatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
1389724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], address);
1390afde0c52Smatthias.ringwald             if (packet[2] == 0){
1391f8fbdce0SMatthias Ringwald                 handle = little_endian_read_16(packet, 3);
1392afde0c52Smatthias.ringwald                 l2cap_handle_connection_success_for_addr(address, handle);
1393afde0c52Smatthias.ringwald             } else {
1394afde0c52Smatthias.ringwald                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
1395afde0c52Smatthias.ringwald             }
1396afde0c52Smatthias.ringwald             break;
1397afde0c52Smatthias.ringwald 
1398afde0c52Smatthias.ringwald         // handle successful create connection cancel command
1399afde0c52Smatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
1400073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
1401afde0c52Smatthias.ringwald                 if (packet[5] == 0){
1402724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[6], address);
1403afde0c52Smatthias.ringwald                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
1404afde0c52Smatthias.ringwald                     l2cap_handle_connection_failed_for_addr(address, 0x16);
140503cfbabcSmatthias.ringwald                 }
14061e6aba47Smatthias.ringwald             }
140739d59809Smatthias.ringwald             l2cap_run();    // try sending signaling packets first
140839d59809Smatthias.ringwald             break;
140909e9d05bSMatthias Ringwald #endif
141027a923d0Smatthias.ringwald 
14111e6aba47Smatthias.ringwald         // handle disconnection complete events
1412afde0c52Smatthias.ringwald         case HCI_EVENT_DISCONNECTION_COMPLETE:
1413c22aecc9S[email protected]             // send l2cap disconnect events for all channels on this handle and free them
141409e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1415d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1416665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1417665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1418665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1419fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
142015ec09bbSmatthias.ringwald                 l2cap_emit_channel_closed(channel);
14219dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
1422665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1423d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
142427a923d0Smatthias.ringwald             }
142509e9d05bSMatthias Ringwald #endif
1426a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1427d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1428991fea48SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1429991fea48SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1430991fea48SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1431991fea48SMatthias Ringwald                 if (channel->con_handle != handle) continue;
1432991fea48SMatthias Ringwald                 l2cap_emit_channel_closed(channel);
1433991fea48SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1434991fea48SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
1435991fea48SMatthias Ringwald             }
1436991fea48SMatthias Ringwald #endif
1437afde0c52Smatthias.ringwald             break;
1438fcadd0caSmatthias.ringwald 
1439ee091cf1Smatthias.ringwald         // HCI Connection Timeouts
144009e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1441afde0c52Smatthias.ringwald         case L2CAP_EVENT_TIMEOUT_CHECK:
1442f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
1443bd04d84aSMatthias Ringwald             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
144480ca58a0Smatthias.ringwald             if (hci_authentication_active_for_handle(handle)) break;
14452d00edd4Smatthias.ringwald             hci_con_used = 0;
1446665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1447665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1448665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1449fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
14502d00edd4Smatthias.ringwald                 hci_con_used = 1;
1451c22aecc9S[email protected]                 break;
1452ee091cf1Smatthias.ringwald             }
14532d00edd4Smatthias.ringwald             if (hci_con_used) break;
1454d94d3cafS[email protected]             if (!hci_can_send_command_packet_now()) break;
14559edc8742Smatthias.ringwald             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
1456afde0c52Smatthias.ringwald             break;
1457ee091cf1Smatthias.ringwald 
1458df3354fcS[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1459f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1460665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1461665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1462665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1463fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
14642df5dadcS[email protected]                 l2cap_handle_remote_supported_features_received(channel);
1465df3354fcS[email protected]                 break;
1466df3354fcS[email protected]             }
1467c22aecc9S[email protected]             break;
1468df3354fcS[email protected] 
14695611a760SMatthias Ringwald         case GAP_EVENT_SECURITY_LEVEL:
1470f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
1471bd63148eS[email protected]             log_info("l2cap - security level update");
1472665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1473665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1474665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1475fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
14765533f01eS[email protected] 
1477bd63148eS[email protected]                 log_info("l2cap - state %u", channel->state);
1478bd63148eS[email protected] 
1479e569dfd9SMatthias Ringwald                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
14805533f01eS[email protected]                 gap_security_level_t required_level = channel->required_security_level;
14815533f01eS[email protected] 
1482df3354fcS[email protected]                 switch (channel->state){
1483df3354fcS[email protected]                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
14845533f01eS[email protected]                         if (actual_level >= required_level){
148552606043SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
148652606043SMatthias Ringwald                             // we need to know if ERTM is supported before sending a config response
148752606043SMatthias Ringwald                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
148852606043SMatthias Ringwald                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
148952606043SMatthias Ringwald                             channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
149052606043SMatthias Ringwald #else
1491f85a9399S[email protected]                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
149244276248SMatthias Ringwald                             l2cap_emit_incoming_connection(channel);
149352606043SMatthias Ringwald #endif
14941eb2563eS[email protected]                         } else {
1495775ecc36SMatthias Ringwald                             channel->reason = 0x0003; // security block
14961eb2563eS[email protected]                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
14971eb2563eS[email protected]                         }
1498df3354fcS[email protected]                         break;
1499df3354fcS[email protected] 
1500df3354fcS[email protected]                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
15015533f01eS[email protected]                         if (actual_level >= required_level){
15021b9cb13dSMatthias Ringwald                             l2cap_ready_to_connect(channel);
1503df3354fcS[email protected]                         } else {
1504df3354fcS[email protected]                             // disconnnect, authentication not good enough
1505df3354fcS[email protected]                             hci_disconnect_security_block(handle);
1506df3354fcS[email protected]                         }
1507df3354fcS[email protected]                         break;
1508df3354fcS[email protected] 
1509df3354fcS[email protected]                     default:
1510df3354fcS[email protected]                         break;
1511df3354fcS[email protected]                 }
1512f85a9399S[email protected]             }
1513f85a9399S[email protected]             break;
151409e9d05bSMatthias Ringwald #endif
1515f85a9399S[email protected] 
1516afde0c52Smatthias.ringwald         default:
1517afde0c52Smatthias.ringwald             break;
1518afde0c52Smatthias.ringwald     }
1519afde0c52Smatthias.ringwald 
1520bd63148eS[email protected]     l2cap_run();
15211e6aba47Smatthias.ringwald }
15221e6aba47Smatthias.ringwald 
1523e74c5f58SMatthias Ringwald static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t cid, uint16_t data){
15244cf56b4aSmatthias.ringwald     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused."
15252b360848Smatthias.ringwald     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
15262b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].handle = handle;
15272b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].code = code;
15282b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].sig_id = sig_id;
1529e74c5f58SMatthias Ringwald         signaling_responses[signaling_responses_pending].cid = cid;
15302b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].data = data;
15312b360848Smatthias.ringwald         signaling_responses_pending++;
15322b360848Smatthias.ringwald         l2cap_run();
15332b360848Smatthias.ringwald     }
15342b360848Smatthias.ringwald }
15352b360848Smatthias.ringwald 
153609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
153709e9d05bSMatthias Ringwald static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
153809e9d05bSMatthias Ringwald     channel->remote_sig_id = identifier;
153909e9d05bSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
154009e9d05bSMatthias Ringwald     l2cap_run();
154109e9d05bSMatthias Ringwald }
154209e9d05bSMatthias Ringwald 
1543b35f641cSmatthias.ringwald static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
1544645658c9Smatthias.ringwald 
15459da54300S[email protected]     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
1546645658c9Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
1547645658c9Smatthias.ringwald     if (!service) {
1548645658c9Smatthias.ringwald         // 0x0002 PSM not supported
1549e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
1550645658c9Smatthias.ringwald         return;
1551645658c9Smatthias.ringwald     }
1552645658c9Smatthias.ringwald 
15535061f3afS[email protected]     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
1554645658c9Smatthias.ringwald     if (!hci_connection) {
15552b360848Smatthias.ringwald         //
15569da54300S[email protected]         log_error("no hci_connection for handle %u", handle);
1557645658c9Smatthias.ringwald         return;
1558645658c9Smatthias.ringwald     }
15592bd8b7e7S[email protected] 
1560645658c9Smatthias.ringwald     // alloc structure
15619da54300S[email protected]     // log_info("l2cap_handle_connection_request register channel");
1562da144af5SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, hci_connection->address, BD_ADDR_TYPE_CLASSIC,
1563da144af5SMatthias Ringwald     psm, service->mtu, service->required_security_level);
15642b360848Smatthias.ringwald     if (!channel){
15652b360848Smatthias.ringwald         // 0x0004 No resources available
1566e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
15672b360848Smatthias.ringwald         return;
15682b360848Smatthias.ringwald     }
1569da144af5SMatthias Ringwald 
1570fc64f94aSMatthias Ringwald     channel->con_handle = handle;
1571b35f641cSmatthias.ringwald     channel->remote_cid = source_cid;
1572b1988dceSmatthias.ringwald     channel->remote_sig_id = sig_id;
1573645658c9Smatthias.ringwald 
1574f53da564S[email protected]     // limit local mtu to max acl packet length - l2cap header
15752985cb84Smatthias.ringwald     if (channel->local_mtu > l2cap_max_mtu()) {
15762985cb84Smatthias.ringwald         channel->local_mtu = l2cap_max_mtu();
15779775e25bSmatthias.ringwald     }
15789775e25bSmatthias.ringwald 
1579645658c9Smatthias.ringwald     // set initial state
1580df3354fcS[email protected]     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
1581a24785d0SMatthias Ringwald     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
1582e405ae81Smatthias.ringwald 
1583645658c9Smatthias.ringwald     // add to connections list
1584665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1585645658c9Smatthias.ringwald 
1586f85a9399S[email protected]     // assert security requirements
15871eb2563eS[email protected]     gap_request_security_level(handle, channel->required_security_level);
1588e405ae81Smatthias.ringwald }
1589645658c9Smatthias.ringwald 
1590ce8f182eSMatthias Ringwald void l2cap_accept_connection(uint16_t local_cid){
1591e0abb8e7S[email protected]     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
1592b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1593e405ae81Smatthias.ringwald     if (!channel) {
1594ce8f182eSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
1595e405ae81Smatthias.ringwald         return;
1596e405ae81Smatthias.ringwald     }
1597e405ae81Smatthias.ringwald 
159843ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
159943ec931dSMatthias Ringwald     // configure L2CAP Basic mode
160043ec931dSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
160143ec931dSMatthias Ringwald #endif
160243ec931dSMatthias Ringwald 
1603552d92a1Smatthias.ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
1604e405ae81Smatthias.ringwald 
1605552d92a1Smatthias.ringwald     // process
1606552d92a1Smatthias.ringwald     l2cap_run();
1607e405ae81Smatthias.ringwald }
1608645658c9Smatthias.ringwald 
160943ec931dSMatthias Ringwald 
161043ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
16112b70d705SMatthias Ringwald uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, int ertm_mandatory, uint8_t max_transmit,
1612501329faSMatthias Ringwald     uint16_t retransmission_timeout_ms, uint16_t monitor_timeout_ms, uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size){
1613501329faSMatthias Ringwald 
161443ec931dSMatthias Ringwald     log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
161543ec931dSMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
161643ec931dSMatthias Ringwald     if (!channel) {
161743ec931dSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
16182b70d705SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
161943ec931dSMatthias Ringwald     }
162043ec931dSMatthias Ringwald 
16212b70d705SMatthias Ringwald     // validate local config
16222b70d705SMatthias Ringwald     uint8_t result = l2cap_ertm_validate_local_config(max_transmit, retransmission_timeout_ms, monitor_timeout_ms, num_tx_buffers, num_rx_buffers, buffer, size);
16232b70d705SMatthias Ringwald     if (result) return result;
16242b70d705SMatthias Ringwald 
162543ec931dSMatthias Ringwald     // configure L2CAP ERTM
16267b181629SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_mandatory, max_transmit, retransmission_timeout_ms, monitor_timeout_ms, num_tx_buffers, num_rx_buffers, buffer, size);
162743ec931dSMatthias Ringwald 
16287b181629SMatthias Ringwald     // continue
162943ec931dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
163043ec931dSMatthias Ringwald 
163143ec931dSMatthias Ringwald     // process
163243ec931dSMatthias Ringwald     l2cap_run();
16332b70d705SMatthias Ringwald 
16342b70d705SMatthias Ringwald     return ERROR_CODE_SUCCESS;
163543ec931dSMatthias Ringwald }
163643ec931dSMatthias Ringwald #endif
163743ec931dSMatthias Ringwald 
163843ec931dSMatthias Ringwald 
16397ef6a7bbSMatthias Ringwald void l2cap_decline_connection(uint16_t local_cid){
16407ef6a7bbSMatthias Ringwald     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
1641b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
1642e405ae81Smatthias.ringwald     if (!channel) {
1643ce8f182eSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
1644e405ae81Smatthias.ringwald         return;
1645e405ae81Smatthias.ringwald     }
1646e7ff783cSmatthias.ringwald     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
16477ef6a7bbSMatthias Ringwald     channel->reason = 0x04; // no resources available
1648e7ff783cSmatthias.ringwald     l2cap_run();
1649645658c9Smatthias.ringwald }
1650645658c9Smatthias.ringwald 
16517f02f414SMatthias Ringwald static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
1652b1988dceSmatthias.ringwald 
1653b1988dceSmatthias.ringwald     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1654b1988dceSmatthias.ringwald 
1655f8fbdce0SMatthias Ringwald     uint16_t flags = little_endian_read_16(command, 6);
165663a7246aSmatthias.ringwald     if (flags & 1) {
165763a7246aSmatthias.ringwald         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
165863a7246aSmatthias.ringwald     }
165963a7246aSmatthias.ringwald 
16602784b77dSmatthias.ringwald     // accept the other's configuration options
1661f8fbdce0SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
16623de7c0caSmatthias.ringwald     uint16_t pos     = 8;
16633de7c0caSmatthias.ringwald     while (pos < end_pos){
166463a7246aSmatthias.ringwald         uint8_t option_hint = command[pos] >> 7;
166563a7246aSmatthias.ringwald         uint8_t option_type = command[pos] & 0x7f;
166663a7246aSmatthias.ringwald         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
166763a7246aSmatthias.ringwald         pos++;
16681dc511deSmatthias.ringwald         uint8_t length = command[pos++];
16691dc511deSmatthias.ringwald         // MTU { type(8): 1, len(8):2, MTU(16) }
167063a7246aSmatthias.ringwald         if (option_type == 1 && length == 2){
1671f8fbdce0SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, pos);
16729d139fbaSMatthias Ringwald             if (channel->remote_mtu > l2cap_max_mtu()){
16739d139fbaSMatthias Ringwald                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
16749d139fbaSMatthias Ringwald                 channel->remote_mtu = l2cap_max_mtu();
16759d139fbaSMatthias Ringwald             }
167663a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
167763a7246aSmatthias.ringwald         }
16780fe7a9d0S[email protected]         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
16790fe7a9d0S[email protected]         if (option_type == 2 && length == 2){
1680f8fbdce0SMatthias Ringwald             channel->flush_timeout = little_endian_read_16(command, pos);
16810fe7a9d0S[email protected]         }
1682f2fa388dSMatthias Ringwald 
16836dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
16846dca2a0cSMatthias Ringwald         // Retransmission and Flow Control Option
16856dca2a0cSMatthias Ringwald         if (option_type == 4 && length == 9){
16863232a1c6SMatthias Ringwald             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
1687ac8f1300SMatthias Ringwald             switch(channel->mode){
1688ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
1689ac8f1300SMatthias Ringwald                     if (channel->ertm_mandatory){
1690ac8f1300SMatthias Ringwald                         // ERTM mandatory, but remote doens't offer ERTM -> disconnect
16913232a1c6SMatthias Ringwald                         if (mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
16923232a1c6SMatthias Ringwald                             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
16933232a1c6SMatthias Ringwald                         } else {
1694ac8f1300SMatthias Ringwald                             // Both sides selected ERTM
1695*bbc0a9e7SMatthias Ringwald                             channel->remote_tx_window_size = command[pos+1];
1696*bbc0a9e7SMatthias Ringwald                             channel->remote_max_transmit   = command[pos+2];
1697*bbc0a9e7SMatthias Ringwald                             channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
1698*bbc0a9e7SMatthias Ringwald                             channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
1699*bbc0a9e7SMatthias Ringwald                             log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u",
1700*bbc0a9e7SMatthias Ringwald                                 channel->remote_tx_window_size,
1701*bbc0a9e7SMatthias Ringwald                                 channel->remote_max_transmit,
1702*bbc0a9e7SMatthias Ringwald                                 channel->remote_retransmission_timeout_ms,
1703*bbc0a9e7SMatthias Ringwald                                 channel->remote_monitor_timeout_ms);
1704*bbc0a9e7SMatthias Ringwald                             // we store remote MPS in remote_mtu, might need to get re-evaluated
1705*bbc0a9e7SMatthias Ringwald                             channel->remote_mtu = little_endian_read_16(command, pos + 7);
17066dca2a0cSMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
17076dca2a0cSMatthias Ringwald                         }
1708ac8f1300SMatthias Ringwald                     } else {
1709ac8f1300SMatthias Ringwald                         // ERTM is optional
1710ac8f1300SMatthias Ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1711ac8f1300SMatthias Ringwald                     }
1712ac8f1300SMatthias Ringwald                     break;
1713ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
1714ac8f1300SMatthias Ringwald                     switch (mode){
1715ac8f1300SMatthias Ringwald                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
1716ac8f1300SMatthias Ringwald                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
1717ac8f1300SMatthias Ringwald                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
1718ac8f1300SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1719ac8f1300SMatthias Ringwald                             }
1720ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
1721ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1722ac8f1300SMatthias Ringwald                             break;
1723ac8f1300SMatthias Ringwald                         default: // case L2CAP_CHANNEL_MODE_BASIC:
1724ac8f1300SMatthias Ringwald                             // TODO store and evaluate configuration
1725ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1726ac8f1300SMatthias Ringwald                             break;
1727ac8f1300SMatthias Ringwald                     }
1728ac8f1300SMatthias Ringwald                     break;
1729ac8f1300SMatthias Ringwald                 default:
1730ac8f1300SMatthias Ringwald                     break;
1731ac8f1300SMatthias Ringwald             }
17323232a1c6SMatthias Ringwald         }
17336dca2a0cSMatthias Ringwald #endif
173463a7246aSmatthias.ringwald         // check for unknown options
173563a7246aSmatthias.ringwald         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
1736c177a91cS[email protected]             log_info("l2cap cid %u, unknown options", channel->local_cid);
173763a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
17381dc511deSmatthias.ringwald         }
17391dc511deSmatthias.ringwald         pos += length;
17401dc511deSmatthias.ringwald     }
17412784b77dSmatthias.ringwald }
17422784b77dSmatthias.ringwald 
1743f2fa388dSMatthias Ringwald static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
1744f2fa388dSMatthias Ringwald     log_info("l2cap_signaling_handle_configure_response");
17453232a1c6SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
17463232a1c6SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1747f2fa388dSMatthias Ringwald     uint16_t pos     = 10;
17483232a1c6SMatthias Ringwald     while (pos < end_pos){
17493232a1c6SMatthias Ringwald         uint8_t option_hint = command[pos] >> 7;
17503232a1c6SMatthias Ringwald         uint8_t option_type = command[pos] & 0x7f;
17513232a1c6SMatthias Ringwald         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
17523232a1c6SMatthias Ringwald         pos++;
17533232a1c6SMatthias Ringwald         uint8_t length = command[pos++];
17543232a1c6SMatthias Ringwald 
17553232a1c6SMatthias Ringwald         // Retransmission and Flow Control Option
17563232a1c6SMatthias Ringwald         if (option_type == 4 && length == 9){
1757ac8f1300SMatthias Ringwald             switch (channel->mode){
1758ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
1759f2fa388dSMatthias Ringwald                     if (channel->ertm_mandatory){
1760ac8f1300SMatthias Ringwald                         // ??
1761f2fa388dSMatthias Ringwald                     } else {
1762ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
1763ac8f1300SMatthias Ringwald                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
1764f2fa388dSMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
17653232a1c6SMatthias Ringwald                         }
17663232a1c6SMatthias Ringwald                     }
1767ac8f1300SMatthias Ringwald                     break;
1768ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
1769ac8f1300SMatthias Ringwald                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
1770ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
1771ac8f1300SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1772ac8f1300SMatthias Ringwald                     }
1773ac8f1300SMatthias Ringwald                     break;
1774ac8f1300SMatthias Ringwald                 default:
1775ac8f1300SMatthias Ringwald                     break;
17763232a1c6SMatthias Ringwald             }
1777f2fa388dSMatthias Ringwald         }
17783232a1c6SMatthias Ringwald 
17793232a1c6SMatthias Ringwald         // check for unknown options
17803232a1c6SMatthias Ringwald         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
17813232a1c6SMatthias Ringwald             log_info("l2cap cid %u, unknown options", channel->local_cid);
17823232a1c6SMatthias Ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
17833232a1c6SMatthias Ringwald         }
17843232a1c6SMatthias Ringwald 
17853232a1c6SMatthias Ringwald         pos += length;
17863232a1c6SMatthias Ringwald     }
17873232a1c6SMatthias Ringwald #endif
17883232a1c6SMatthias Ringwald }
17893232a1c6SMatthias Ringwald 
1790fa8473a4Smatthias.ringwald static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
17919da54300S[email protected]     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
179273cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
179373cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
1794019f9b43SMatthias Ringwald     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
1795019f9b43SMatthias Ringwald     if (channel->state == L2CAP_STATE_OPEN) return 0;
1796fa8473a4Smatthias.ringwald     return 1;
1797fa8473a4Smatthias.ringwald }
1798fa8473a4Smatthias.ringwald 
1799fa8473a4Smatthias.ringwald 
18007f02f414SMatthias Ringwald static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
18011e6aba47Smatthias.ringwald 
180200d93d79Smatthias.ringwald     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
180300d93d79Smatthias.ringwald     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
180438e5900eSmatthias.ringwald     uint16_t result = 0;
18051e6aba47Smatthias.ringwald 
18069da54300S[email protected]     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
1807b35f641cSmatthias.ringwald 
18089a011532Smatthias.ringwald     // handle DISCONNECT REQUESTS seperately
18099a011532Smatthias.ringwald     if (code == DISCONNECTION_REQUEST){
18109a011532Smatthias.ringwald         switch (channel->state){
1811fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
18129a011532Smatthias.ringwald             case L2CAP_STATE_OPEN:
18132b83fb7dSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
18149a011532Smatthias.ringwald             case L2CAP_STATE_WAIT_DISCONNECT:
18159a011532Smatthias.ringwald                 l2cap_handle_disconnect_request(channel, identifier);
18169a011532Smatthias.ringwald                 break;
18179a011532Smatthias.ringwald 
18189a011532Smatthias.ringwald             default:
18199a011532Smatthias.ringwald                 // ignore in other states
18209a011532Smatthias.ringwald                 break;
18219a011532Smatthias.ringwald         }
18229a011532Smatthias.ringwald         return;
18239a011532Smatthias.ringwald     }
18249a011532Smatthias.ringwald 
182556081214Smatthias.ringwald     // @STATEMACHINE(l2cap)
18261e6aba47Smatthias.ringwald     switch (channel->state) {
18271e6aba47Smatthias.ringwald 
18281e6aba47Smatthias.ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
18291e6aba47Smatthias.ringwald             switch (code){
18301e6aba47Smatthias.ringwald                 case CONNECTION_RESPONSE:
18315932bd7cS[email protected]                     l2cap_stop_rtx(channel);
1832f8fbdce0SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
183338e5900eSmatthias.ringwald                     switch (result) {
183438e5900eSmatthias.ringwald                         case 0:
1835169f8b28Smatthias.ringwald                             // successful connection
1836f8fbdce0SMatthias Ringwald                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1837fa8473a4Smatthias.ringwald                             channel->state = L2CAP_STATE_CONFIG;
183828ca2b46S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
183938e5900eSmatthias.ringwald                             break;
184038e5900eSmatthias.ringwald                         case 1:
18415932bd7cS[email protected]                             // connection pending. get some coffee, but start the ERTX
18425932bd7cS[email protected]                             l2cap_start_ertx(channel);
184338e5900eSmatthias.ringwald                             break;
184438e5900eSmatthias.ringwald                         default:
1845eb920dbeSmatthias.ringwald                             // channel closed
1846eb920dbeSmatthias.ringwald                             channel->state = L2CAP_STATE_CLOSED;
1847f32b992eSmatthias.ringwald                             // map l2cap connection response result to BTstack status enumeration
184838e5900eSmatthias.ringwald                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
1849eb920dbeSmatthias.ringwald 
1850eb920dbeSmatthias.ringwald                             // drop link key if security block
1851eb920dbeSmatthias.ringwald                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
185215a95bd5SMatthias Ringwald                                 gap_drop_link_key_for_bd_addr(channel->address);
1853eb920dbeSmatthias.ringwald                             }
1854eb920dbeSmatthias.ringwald 
1855eb920dbeSmatthias.ringwald                             // discard channel
1856665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1857d3a9df87Smatthias.ringwald                             btstack_memory_l2cap_channel_free(channel);
185838e5900eSmatthias.ringwald                             break;
18591e6aba47Smatthias.ringwald                     }
18601e6aba47Smatthias.ringwald                     break;
186138e5900eSmatthias.ringwald 
186238e5900eSmatthias.ringwald                 default:
18631e6aba47Smatthias.ringwald                     //@TODO: implement other signaling packets
186438e5900eSmatthias.ringwald                     break;
18651e6aba47Smatthias.ringwald             }
18661e6aba47Smatthias.ringwald             break;
18671e6aba47Smatthias.ringwald 
1868fa8473a4Smatthias.ringwald         case L2CAP_STATE_CONFIG:
1869f8fbdce0SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1870ae280e73Smatthias.ringwald             switch (code) {
1871ae280e73Smatthias.ringwald                 case CONFIGURE_REQUEST:
187228ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1873ae280e73Smatthias.ringwald                     l2cap_signaling_handle_configure_request(channel, command);
187463a7246aSmatthias.ringwald                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
187563a7246aSmatthias.ringwald                         // only done if continuation not set
187663a7246aSmatthias.ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
187763a7246aSmatthias.ringwald                     }
1878ae280e73Smatthias.ringwald                     break;
18791e6aba47Smatthias.ringwald                 case CONFIGURE_RESPONSE:
18805932bd7cS[email protected]                     l2cap_stop_rtx(channel);
1881f2fa388dSMatthias Ringwald                     l2cap_signaling_handle_configure_response(channel, result, command);
18825932bd7cS[email protected]                     switch (result){
18835932bd7cS[email protected]                         case 0: // success
18845932bd7cS[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
18855932bd7cS[email protected]                             break;
18865932bd7cS[email protected]                         case 4: // pending
18875932bd7cS[email protected]                             l2cap_start_ertx(channel);
18885932bd7cS[email protected]                             break;
18895932bd7cS[email protected]                         default:
1890a32d6a03SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1891a32d6a03SMatthias Ringwald                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
1892a32d6a03SMatthias Ringwald                                 // remote does not offer ertm but it's required
1893a32d6a03SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1894a32d6a03SMatthias Ringwald                                 break;
1895a32d6a03SMatthias Ringwald                             }
1896a32d6a03SMatthias Ringwald #endif
1897fe9d8984S[email protected]                             // retry on negative result
1898fe9d8984S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1899fe9d8984S[email protected]                             break;
1900fe9d8984S[email protected]                     }
19015a67bd4aSmatthias.ringwald                     break;
19025a67bd4aSmatthias.ringwald                 default:
19035a67bd4aSmatthias.ringwald                     break;
19041e6aba47Smatthias.ringwald             }
1905fa8473a4Smatthias.ringwald             if (l2cap_channel_ready_for_open(channel)){
1906fa8473a4Smatthias.ringwald                 // for open:
19075a67bd4aSmatthias.ringwald                 channel->state = L2CAP_STATE_OPEN;
1908fa8473a4Smatthias.ringwald                 l2cap_emit_channel_opened(channel, 0);
1909c8e4258aSmatthias.ringwald             }
1910c8e4258aSmatthias.ringwald             break;
1911f62db1e3Smatthias.ringwald 
1912f62db1e3Smatthias.ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
1913f62db1e3Smatthias.ringwald             switch (code) {
1914f62db1e3Smatthias.ringwald                 case DISCONNECTION_RESPONSE:
191527a923d0Smatthias.ringwald                     l2cap_finialize_channel_close(channel);
191627a923d0Smatthias.ringwald                     break;
19175a67bd4aSmatthias.ringwald                 default:
19185a67bd4aSmatthias.ringwald                     //@TODO: implement other signaling packets
19195a67bd4aSmatthias.ringwald                     break;
192027a923d0Smatthias.ringwald             }
192127a923d0Smatthias.ringwald             break;
192284836b65Smatthias.ringwald 
192384836b65Smatthias.ringwald         case L2CAP_STATE_CLOSED:
192484836b65Smatthias.ringwald             // @TODO handle incoming requests
192584836b65Smatthias.ringwald             break;
192684836b65Smatthias.ringwald 
192784836b65Smatthias.ringwald         case L2CAP_STATE_OPEN:
192884836b65Smatthias.ringwald             //@TODO: implement other signaling packets, e.g. re-configure
192984836b65Smatthias.ringwald             break;
193010642e45Smatthias.ringwald         default:
193110642e45Smatthias.ringwald             break;
193227a923d0Smatthias.ringwald     }
19339da54300S[email protected]     // log_info("new state %u", channel->state);
193427a923d0Smatthias.ringwald }
193527a923d0Smatthias.ringwald 
193600d93d79Smatthias.ringwald 
19377f02f414SMatthias Ringwald static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
193800d93d79Smatthias.ringwald 
19391b9cb13dSMatthias Ringwald     btstack_linked_list_iterator_t it;
19401b9cb13dSMatthias Ringwald 
194100d93d79Smatthias.ringwald     // get code, signalind identifier and command len
194200d93d79Smatthias.ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
194300d93d79Smatthias.ringwald     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
194400d93d79Smatthias.ringwald 
19451b9cb13dSMatthias Ringwald     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
19461b9cb13dSMatthias Ringwald     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_RESPONSE){
1947e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
194800d93d79Smatthias.ringwald         return;
194900d93d79Smatthias.ringwald     }
195000d93d79Smatthias.ringwald 
195100d93d79Smatthias.ringwald     // general commands without an assigned channel
195200d93d79Smatthias.ringwald     switch(code) {
195300d93d79Smatthias.ringwald 
195400d93d79Smatthias.ringwald         case CONNECTION_REQUEST: {
1955f8fbdce0SMatthias Ringwald             uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1956f8fbdce0SMatthias Ringwald             uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
195700d93d79Smatthias.ringwald             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
19582b83fb7dSmatthias.ringwald             return;
195900d93d79Smatthias.ringwald         }
196000d93d79Smatthias.ringwald 
19612b360848Smatthias.ringwald         case ECHO_REQUEST:
1962e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
19632b83fb7dSmatthias.ringwald             return;
196400d93d79Smatthias.ringwald 
196500d93d79Smatthias.ringwald         case INFORMATION_REQUEST: {
1966f8fbdce0SMatthias Ringwald             uint16_t infoType = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1967e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, infoType);
19682b83fb7dSmatthias.ringwald             return;
196900d93d79Smatthias.ringwald         }
197000d93d79Smatthias.ringwald 
19711b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
19721b9cb13dSMatthias Ringwald         case INFORMATION_RESPONSE: {
19731b9cb13dSMatthias Ringwald             hci_connection_t * connection = hci_connection_for_handle(handle);
19741b9cb13dSMatthias Ringwald             if (!connection) return;
19751b9cb13dSMatthias Ringwald             uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
19761b9cb13dSMatthias Ringwald             uint16_t result =  little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
19771b9cb13dSMatthias Ringwald             if (result != 0) return;
1978543b84e4SMatthias Ringwald             if (info_type != 0x02) return;
19791b9cb13dSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
19801b9cb13dSMatthias Ringwald             connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1981543b84e4SMatthias Ringwald             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
19821b9cb13dSMatthias Ringwald             // trigger connection request
19831b9cb13dSMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
19841b9cb13dSMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
19851b9cb13dSMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1986543b84e4SMatthias Ringwald                 if (channel->con_handle != handle) continue;
1987543b84e4SMatthias Ringwald                 // bail if ERTM was requested but is not supported
1988543b84e4SMatthias Ringwald                 if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
1989f073f086SMatthias Ringwald                     if (channel->ertm_mandatory){
1990543b84e4SMatthias Ringwald                         // channel closed
1991543b84e4SMatthias Ringwald                         channel->state = L2CAP_STATE_CLOSED;
1992543b84e4SMatthias Ringwald                         // map l2cap connection response result to BTstack status enumeration
1993543b84e4SMatthias Ringwald                         l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTD);
1994543b84e4SMatthias Ringwald                         // discard channel
1995543b84e4SMatthias Ringwald                         btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1996543b84e4SMatthias Ringwald                         btstack_memory_l2cap_channel_free(channel);
1997543b84e4SMatthias Ringwald                         continue;
1998f073f086SMatthias Ringwald                     } else {
1999f073f086SMatthias Ringwald                         // fallback to Basic mode
2000f073f086SMatthias Ringwald                         channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2001f073f086SMatthias Ringwald                     }
2002543b84e4SMatthias Ringwald                 }
2003543b84e4SMatthias Ringwald                 // start connecting
20041b9cb13dSMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
20051b9cb13dSMatthias Ringwald                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
20061b9cb13dSMatthias Ringwald                 }
200752606043SMatthias Ringwald                 // respond to connection request
200852606043SMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
200952606043SMatthias Ringwald                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
201052606043SMatthias Ringwald                     l2cap_emit_incoming_connection(channel);
201152606043SMatthias Ringwald                 }
20121b9cb13dSMatthias Ringwald             }
20131b9cb13dSMatthias Ringwald             return;
20141b9cb13dSMatthias Ringwald         }
20151b9cb13dSMatthias Ringwald #endif
20161b9cb13dSMatthias Ringwald 
201700d93d79Smatthias.ringwald         default:
201800d93d79Smatthias.ringwald             break;
201900d93d79Smatthias.ringwald     }
202000d93d79Smatthias.ringwald 
202100d93d79Smatthias.ringwald 
202200d93d79Smatthias.ringwald     // Get potential destination CID
2023f8fbdce0SMatthias Ringwald     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
202400d93d79Smatthias.ringwald 
202500d93d79Smatthias.ringwald     // Find channel for this sig_id and connection handle
2026665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2027665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2028665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2029fc64f94aSMatthias Ringwald         if (channel->con_handle != handle) continue;
203000d93d79Smatthias.ringwald         if (code & 1) {
2031b1988dceSmatthias.ringwald             // match odd commands (responses) by previous signaling identifier
2032b1988dceSmatthias.ringwald             if (channel->local_sig_id == sig_id) {
203300d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
20344e32727eSmatthias.ringwald                 break;
203500d93d79Smatthias.ringwald             }
203600d93d79Smatthias.ringwald         } else {
2037b1988dceSmatthias.ringwald             // match even commands (requests) by local channel id
203800d93d79Smatthias.ringwald             if (channel->local_cid == dest_cid) {
203900d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
20404e32727eSmatthias.ringwald                 break;
204100d93d79Smatthias.ringwald             }
204200d93d79Smatthias.ringwald         }
204300d93d79Smatthias.ringwald     }
204400d93d79Smatthias.ringwald }
204509e9d05bSMatthias Ringwald #endif
204600d93d79Smatthias.ringwald 
2047e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
204809e9d05bSMatthias Ringwald 
204909e9d05bSMatthias Ringwald static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
205009e9d05bSMatthias Ringwald     uint8_t event[6];
205109e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
205209e9d05bSMatthias Ringwald     event[1] = 4;
205309e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
205409e9d05bSMatthias Ringwald     little_endian_store_16(event, 4, result);
205509e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
205609e9d05bSMatthias Ringwald     if (!l2cap_event_packet_handler) return;
205709e9d05bSMatthias Ringwald     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
205809e9d05bSMatthias Ringwald }
205909e9d05bSMatthias Ringwald 
2060c48b2a2cSMatthias Ringwald // @returns valid
2061c48b2a2cSMatthias Ringwald static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
2062e7d0c9aaSMatthias Ringwald     hci_connection_t * connection;
2063c48b2a2cSMatthias Ringwald     uint16_t result;
2064c48b2a2cSMatthias Ringwald     uint8_t  event[10];
206583fd9c76SMatthias Ringwald 
2066cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2067a3dc965aSMatthias Ringwald     btstack_linked_list_iterator_t it;
2068a3dc965aSMatthias Ringwald     l2cap_channel_t * channel;
2069a3dc965aSMatthias Ringwald     uint16_t local_cid;
207083fd9c76SMatthias Ringwald     uint16_t le_psm;
207163f0ac45SMatthias Ringwald     uint16_t new_credits;
207263f0ac45SMatthias Ringwald     uint16_t credits_before;
2073e7d0c9aaSMatthias Ringwald     l2cap_service_t * service;
207411cae19eSMilanka Ringwald     uint16_t source_cid;
207583fd9c76SMatthias Ringwald #endif
207600d93d79Smatthias.ringwald 
20771b8b8d05SMatthias Ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
207823017473SMatthias Ringwald     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u", code, sig_id);
20791b8b8d05SMatthias Ringwald 
20801b8b8d05SMatthias Ringwald     switch (code){
208100d93d79Smatthias.ringwald 
2082c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
2083c48b2a2cSMatthias Ringwald             result = little_endian_read_16(command, 4);
2084ccf076adS[email protected]             l2cap_emit_connection_parameter_update_response(handle, result);
2085ccf076adS[email protected]             break;
2086da886c03S[email protected] 
2087c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_REQUEST:
2088e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
2089da886c03S[email protected]             if (connection){
20906d91fb6cSMatthias Ringwald                 if (connection->role != HCI_ROLE_MASTER){
20916d91fb6cSMatthias Ringwald                     // reject command without notifying upper layer when not in master role
2092c48b2a2cSMatthias Ringwald                     return 0;
20936d91fb6cSMatthias Ringwald                 }
2094da886c03S[email protected]                 int update_parameter = 1;
2095a4c06b28SMatthias Ringwald                 le_connection_parameter_range_t existing_range;
20964ced4e8cSMatthias Ringwald                 gap_get_connection_parameter_range(&existing_range);
2097c48b2a2cSMatthias Ringwald                 uint16_t le_conn_interval_min = little_endian_read_16(command,8);
2098c48b2a2cSMatthias Ringwald                 uint16_t le_conn_interval_max = little_endian_read_16(command,10);
2099c48b2a2cSMatthias Ringwald                 uint16_t le_conn_latency = little_endian_read_16(command,12);
2100c48b2a2cSMatthias Ringwald                 uint16_t le_supervision_timeout = little_endian_read_16(command,14);
2101da886c03S[email protected] 
2102da886c03S[email protected]                 if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
2103da886c03S[email protected]                 if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
2104da886c03S[email protected] 
2105da886c03S[email protected]                 if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
2106da886c03S[email protected]                 if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
2107da886c03S[email protected] 
2108da886c03S[email protected]                 if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
2109da886c03S[email protected]                 if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
2110da886c03S[email protected] 
2111da886c03S[email protected]                 if (update_parameter){
2112da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
2113da886c03S[email protected]                     connection->le_conn_interval_min = le_conn_interval_min;
2114da886c03S[email protected]                     connection->le_conn_interval_max = le_conn_interval_max;
2115da886c03S[email protected]                     connection->le_conn_latency = le_conn_latency;
2116da886c03S[email protected]                     connection->le_supervision_timeout = le_supervision_timeout;
2117da886c03S[email protected]                 } else {
2118da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
2119da886c03S[email protected]                 }
2120c48b2a2cSMatthias Ringwald                 connection->le_con_param_update_identifier = sig_id;
2121da886c03S[email protected]             }
2122da886c03S[email protected] 
212333c40538SMatthias Ringwald             if (!l2cap_event_packet_handler) break;
2124c48b2a2cSMatthias Ringwald 
2125c48b2a2cSMatthias Ringwald             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
2126c48b2a2cSMatthias Ringwald             event[1] = 8;
2127c48b2a2cSMatthias Ringwald             memcpy(&event[2], &command[4], 8);
2128c48b2a2cSMatthias Ringwald             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
212933c40538SMatthias Ringwald             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
2130ccf076adS[email protected]             break;
2131c48b2a2cSMatthias Ringwald 
2132a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2133a3dc965aSMatthias Ringwald 
213463f0ac45SMatthias Ringwald         case COMMAND_REJECT:
213563f0ac45SMatthias Ringwald             // Find channel for this sig_id and connection handle
213663f0ac45SMatthias Ringwald             channel = NULL;
213763f0ac45SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
213863f0ac45SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
213963f0ac45SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
214063f0ac45SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
214163f0ac45SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
214263f0ac45SMatthias Ringwald                 channel = a_channel;
214363f0ac45SMatthias Ringwald                 break;
214463f0ac45SMatthias Ringwald             }
214563f0ac45SMatthias Ringwald             if (!channel) break;
214663f0ac45SMatthias Ringwald 
214763f0ac45SMatthias Ringwald             // if received while waiting for le connection response, assume legacy device
214863f0ac45SMatthias Ringwald             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
214963f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
215063f0ac45SMatthias Ringwald                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
215144276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0x0002);
215263f0ac45SMatthias Ringwald 
215363f0ac45SMatthias Ringwald                 // discard channel
215463f0ac45SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
215563f0ac45SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
215663f0ac45SMatthias Ringwald                 break;
215763f0ac45SMatthias Ringwald             }
215863f0ac45SMatthias Ringwald             break;
215963f0ac45SMatthias Ringwald 
2160e7d0c9aaSMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_REQUEST:
2161e7d0c9aaSMatthias Ringwald 
2162e7d0c9aaSMatthias Ringwald             // get hci connection, bail if not found (must not happen)
2163e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
2164e7d0c9aaSMatthias Ringwald             if (!connection) return 0;
2165e7d0c9aaSMatthias Ringwald 
2166e7d0c9aaSMatthias Ringwald             // check if service registered
2167e7d0c9aaSMatthias Ringwald             le_psm  = little_endian_read_16(command, 4);
2168e7d0c9aaSMatthias Ringwald             service = l2cap_le_get_service(le_psm);
216911cae19eSMilanka Ringwald             source_cid = little_endian_read_16(command, 6);
2170e7d0c9aaSMatthias Ringwald 
2171e7d0c9aaSMatthias Ringwald             if (service){
2172e7d0c9aaSMatthias Ringwald                 if (source_cid < 0x40){
2173e7d0c9aaSMatthias Ringwald                     // 0x0009 Connection refused - Invalid Source CID
2174e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
2175e7d0c9aaSMatthias Ringwald                     return 1;
2176e7d0c9aaSMatthias Ringwald                 }
2177e7d0c9aaSMatthias Ringwald 
2178e7d0c9aaSMatthias Ringwald                 // go through list of channels for this ACL connection and check if we get a match
2179e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2180e7d0c9aaSMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&it)){
21811b8b8d05SMatthias Ringwald                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
21821b8b8d05SMatthias Ringwald                     if (a_channel->con_handle != handle) continue;
21831b8b8d05SMatthias Ringwald                     if (a_channel->remote_cid != source_cid) continue;
2184e7d0c9aaSMatthias Ringwald                     // 0x000a Connection refused - Source CID already allocated
2185e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
2186e7d0c9aaSMatthias Ringwald                     return 1;
2187e7d0c9aaSMatthias Ringwald                 }
2188e7d0c9aaSMatthias Ringwald 
218983fd9c76SMatthias Ringwald                 // security: check encryption
219083fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_2){
219183fd9c76SMatthias Ringwald                     if (sm_encryption_key_size(handle) == 0){
219283fd9c76SMatthias Ringwald                         // 0x0008 Connection refused - insufficient encryption
2193e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
219483fd9c76SMatthias Ringwald                         return 1;
219583fd9c76SMatthias Ringwald                     }
219683fd9c76SMatthias Ringwald                     // anything less than 16 byte key size is insufficient
219783fd9c76SMatthias Ringwald                     if (sm_encryption_key_size(handle) < 16){
219883fd9c76SMatthias Ringwald                         // 0x0007 Connection refused – insufficient encryption key size
2199e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
220083fd9c76SMatthias Ringwald                         return 1;
220183fd9c76SMatthias Ringwald                     }
220283fd9c76SMatthias Ringwald                 }
220383fd9c76SMatthias Ringwald 
220483fd9c76SMatthias Ringwald                 // security: check authencation
220583fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_3){
220683fd9c76SMatthias Ringwald                     if (!sm_authenticated(handle)){
220783fd9c76SMatthias Ringwald                         // 0x0005 Connection refused – insufficient authentication
2208e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
220983fd9c76SMatthias Ringwald                         return 1;
221083fd9c76SMatthias Ringwald                     }
221183fd9c76SMatthias Ringwald                 }
221283fd9c76SMatthias Ringwald 
221383fd9c76SMatthias Ringwald                 // security: check authorization
221483fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_4){
221583fd9c76SMatthias Ringwald                     if (sm_authorization_state(handle) != AUTHORIZATION_GRANTED){
221683fd9c76SMatthias Ringwald                         // 0x0006 Connection refused – insufficient authorization
2217e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
221883fd9c76SMatthias Ringwald                         return 1;
221983fd9c76SMatthias Ringwald                     }
222083fd9c76SMatthias Ringwald                 }
2221e7d0c9aaSMatthias Ringwald 
2222e7d0c9aaSMatthias Ringwald                 // allocate channel
22231b8b8d05SMatthias Ringwald                 channel = l2cap_create_channel_entry(service->packet_handler, connection->address,
2224e7d0c9aaSMatthias Ringwald                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
2225e7d0c9aaSMatthias Ringwald                 if (!channel){
2226e7d0c9aaSMatthias Ringwald                     // 0x0004 Connection refused – no resources available
2227e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2228e7d0c9aaSMatthias Ringwald                     return 1;
2229e7d0c9aaSMatthias Ringwald                 }
2230e7d0c9aaSMatthias Ringwald 
2231e7d0c9aaSMatthias Ringwald                 channel->con_handle = handle;
2232e7d0c9aaSMatthias Ringwald                 channel->remote_cid = source_cid;
2233e7d0c9aaSMatthias Ringwald                 channel->remote_sig_id = sig_id;
22347f107edaSMatthias Ringwald                 channel->remote_mtu = little_endian_read_16(command, 8);
22357f107edaSMatthias Ringwald                 channel->remote_mps = little_endian_read_16(command, 10);
22367f107edaSMatthias Ringwald                 channel->credits_outgoing = little_endian_read_16(command, 12);
2237e7d0c9aaSMatthias Ringwald 
2238e7d0c9aaSMatthias Ringwald                 // set initial state
2239e7d0c9aaSMatthias Ringwald                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2240c99bb618SMatthias Ringwald                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
2241e7d0c9aaSMatthias Ringwald 
2242e7d0c9aaSMatthias Ringwald                 // add to connections list
2243e7d0c9aaSMatthias Ringwald                 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2244e7d0c9aaSMatthias Ringwald 
2245e7d0c9aaSMatthias Ringwald                 // post connection request event
224644276248SMatthias Ringwald                 l2cap_emit_le_incoming_connection(channel);
2247e7d0c9aaSMatthias Ringwald 
2248e7d0c9aaSMatthias Ringwald             } else {
2249e7d0c9aaSMatthias Ringwald                 // Connection refused – LE_PSM not supported
2250e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2251e7d0c9aaSMatthias Ringwald             }
2252e7d0c9aaSMatthias Ringwald             break;
22531b8b8d05SMatthias Ringwald 
22541b8b8d05SMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
22551b8b8d05SMatthias Ringwald             // Find channel for this sig_id and connection handle
22561b8b8d05SMatthias Ringwald             channel = NULL;
22571b8b8d05SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
22581b8b8d05SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
22591b8b8d05SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
22601b8b8d05SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
22611b8b8d05SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
22621b8b8d05SMatthias Ringwald                 channel = a_channel;
22631b8b8d05SMatthias Ringwald                 break;
22641b8b8d05SMatthias Ringwald             }
22651b8b8d05SMatthias Ringwald             if (!channel) break;
22661b8b8d05SMatthias Ringwald 
22671b8b8d05SMatthias Ringwald             // cid + 0
22681b8b8d05SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
22691b8b8d05SMatthias Ringwald             if (result){
22701b8b8d05SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
22711b8b8d05SMatthias Ringwald                 // map l2cap connection response result to BTstack status enumeration
227244276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, result);
22731b8b8d05SMatthias Ringwald 
22741b8b8d05SMatthias Ringwald                 // discard channel
227563f0ac45SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
22761b8b8d05SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
22771b8b8d05SMatthias Ringwald                 break;
22781b8b8d05SMatthias Ringwald             }
22791b8b8d05SMatthias Ringwald 
22801b8b8d05SMatthias Ringwald             // success
22811b8b8d05SMatthias Ringwald             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
22821b8b8d05SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
22831b8b8d05SMatthias Ringwald             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
22841b8b8d05SMatthias Ringwald             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
22851b8b8d05SMatthias Ringwald             channel->state = L2CAP_STATE_OPEN;
228644276248SMatthias Ringwald             l2cap_emit_le_channel_opened(channel, result);
22871b8b8d05SMatthias Ringwald             break;
22881b8b8d05SMatthias Ringwald 
228985aeef60SMatthias Ringwald         case LE_FLOW_CONTROL_CREDIT:
229085aeef60SMatthias Ringwald             // find channel
229185aeef60SMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
229285aeef60SMatthias Ringwald             channel = l2cap_le_get_channel_for_local_cid(local_cid);
229363f0ac45SMatthias Ringwald             if (!channel) {
229463f0ac45SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
229563f0ac45SMatthias Ringwald                 break;
229663f0ac45SMatthias Ringwald             }
229763f0ac45SMatthias Ringwald             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
229863f0ac45SMatthias Ringwald             credits_before = channel->credits_outgoing;
229963f0ac45SMatthias Ringwald             channel->credits_outgoing += new_credits;
230063f0ac45SMatthias Ringwald             // check for credit overrun
230163f0ac45SMatthias Ringwald             if (credits_before > channel->credits_outgoing){
230263f0ac45SMatthias Ringwald                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
230363f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
230463f0ac45SMatthias Ringwald                 break;
230563f0ac45SMatthias Ringwald             }
230663f0ac45SMatthias Ringwald             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
230785aeef60SMatthias Ringwald             break;
230885aeef60SMatthias Ringwald 
2309828a7f7aSMatthias Ringwald         case DISCONNECTION_REQUEST:
2310828a7f7aSMatthias Ringwald             // find channel
2311828a7f7aSMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
2312828a7f7aSMatthias Ringwald             channel = l2cap_le_get_channel_for_local_cid(local_cid);
231363f34e00SMatthias Ringwald             if (!channel) {
231463f34e00SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
231563f34e00SMatthias Ringwald                 break;
231663f34e00SMatthias Ringwald             }
2317828a7f7aSMatthias Ringwald             channel->remote_sig_id = sig_id;
2318828a7f7aSMatthias Ringwald             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
2319828a7f7aSMatthias Ringwald             break;
2320828a7f7aSMatthias Ringwald 
2321a3dc965aSMatthias Ringwald #endif
2322a3dc965aSMatthias Ringwald 
232363f0ac45SMatthias Ringwald         case DISCONNECTION_RESPONSE:
232463f0ac45SMatthias Ringwald             break;
232563f0ac45SMatthias Ringwald 
2326c48b2a2cSMatthias Ringwald         default:
2327c48b2a2cSMatthias Ringwald             // command unknown -> reject command
2328c48b2a2cSMatthias Ringwald             return 0;
2329ccf076adS[email protected]     }
2330c48b2a2cSMatthias Ringwald     return 1;
2331c48b2a2cSMatthias Ringwald }
2332e7d0c9aaSMatthias Ringwald #endif
2333c48b2a2cSMatthias Ringwald 
2334c48b2a2cSMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size ){
23359ec2630cSMatthias Ringwald     UNUSED(packet_type);
23369ec2630cSMatthias Ringwald     UNUSED(channel);
2337c48b2a2cSMatthias Ringwald 
233809e9d05bSMatthias Ringwald     l2cap_channel_t * l2cap_channel;
2339f3963406SMatthias Ringwald     UNUSED(l2cap_channel);
234009e9d05bSMatthias Ringwald 
2341c48b2a2cSMatthias Ringwald     // Get Channel ID
2342c48b2a2cSMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
2343c48b2a2cSMatthias Ringwald     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
2344c48b2a2cSMatthias Ringwald 
2345c48b2a2cSMatthias Ringwald     switch (channel_id) {
2346c48b2a2cSMatthias Ringwald 
234709e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2348c48b2a2cSMatthias Ringwald         case L2CAP_CID_SIGNALING: {
2349c48b2a2cSMatthias Ringwald             uint16_t command_offset = 8;
2350c48b2a2cSMatthias Ringwald             while (command_offset < size) {
2351c48b2a2cSMatthias Ringwald                 // handle signaling commands
2352c48b2a2cSMatthias Ringwald                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
2353c48b2a2cSMatthias Ringwald 
2354c48b2a2cSMatthias Ringwald                 // increment command_offset
2355c48b2a2cSMatthias Ringwald                 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2356c48b2a2cSMatthias Ringwald             }
2357c48b2a2cSMatthias Ringwald             break;
2358c48b2a2cSMatthias Ringwald         }
235909e9d05bSMatthias Ringwald #endif
2360c48b2a2cSMatthias Ringwald 
2361e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
2362e7d0c9aaSMatthias Ringwald         case L2CAP_CID_SIGNALING_LE: {
2363e7d0c9aaSMatthias Ringwald             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
2364e7d0c9aaSMatthias Ringwald             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
2365c48b2a2cSMatthias Ringwald             if (!valid){
2366e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2367ccf076adS[email protected]             }
2368ccf076adS[email protected]             break;
2369e7d0c9aaSMatthias Ringwald         }
2370e7d0c9aaSMatthias Ringwald #endif
2371c48b2a2cSMatthias Ringwald 
2372c48b2a2cSMatthias Ringwald         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
2373c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback) {
2374c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2375ccf076adS[email protected]             }
2376c48b2a2cSMatthias Ringwald             break;
2377c48b2a2cSMatthias Ringwald 
2378c48b2a2cSMatthias Ringwald         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
2379c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback) {
2380c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2381c48b2a2cSMatthias Ringwald             }
2382c48b2a2cSMatthias Ringwald             break;
2383c48b2a2cSMatthias Ringwald 
2384c48b2a2cSMatthias Ringwald         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
2385c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback) {
2386c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2387c48b2a2cSMatthias Ringwald             }
2388c48b2a2cSMatthias Ringwald             break;
23891bbc0b23S[email protected] 
239009e9d05bSMatthias Ringwald         default:
239109e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
239200d93d79Smatthias.ringwald             // Find channel for this channel_id and connection handle
239364e11ca9SMatthias Ringwald             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
2394d1fd2a88SMatthias Ringwald             if (l2cap_channel) {
239527e0774aSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
239627e0774aSMatthias Ringwald                 if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
239727e0774aSMatthias Ringwald 
239827e0774aSMatthias Ringwald                     // verify FCS
239927e0774aSMatthias Ringwald                     uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
240027e0774aSMatthias Ringwald                     uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
240127e0774aSMatthias Ringwald                     log_info("Packet FCS 0x%04x, calculated FCS 0x%04x", fcs_packet, fcs_calculated);
240227e0774aSMatthias Ringwald                     if (fcs_calculated != fcs_packet){
240327e0774aSMatthias Ringwald                         log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
240427e0774aSMatthias Ringwald                         // TODO: trigger retransmission or something like that
240527e0774aSMatthias Ringwald                         break;
240627e0774aSMatthias Ringwald                     }
240727e0774aSMatthias Ringwald 
240827e0774aSMatthias Ringwald                     // switch on packet type
240927e0774aSMatthias Ringwald                     uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
241027e0774aSMatthias Ringwald                     if (control & 1){
241127e0774aSMatthias Ringwald                         log_info("S-Frame not not implemented yet");
241227e0774aSMatthias Ringwald                         // S-Frame
241327e0774aSMatthias Ringwald                         break;
241427e0774aSMatthias Ringwald                     } else {
241527e0774aSMatthias Ringwald                         // I-Frame
241627e0774aSMatthias Ringwald                         // get control
241727e0774aSMatthias Ringwald                         l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
2418ed971c5aSMatthias Ringwald                         log_info("Control: 0x%04x, SAR type %u, pos %u", control, (int) sar, l2cap_channel->rx_packets_state->pos);
2419ed971c5aSMatthias Ringwald                         uint16_t sdu_length;
2420ed971c5aSMatthias Ringwald                         uint16_t segment_length;
2421ed971c5aSMatthias Ringwald                         uint16_t payload_offset;
242227e0774aSMatthias Ringwald                         switch (sar){
242327e0774aSMatthias Ringwald                             case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
2424ed971c5aSMatthias Ringwald                                 payload_offset = COMPLETE_L2CAP_HEADER+2;
2425ed971c5aSMatthias Ringwald                                 segment_length = payload_offset-2;
2426ed971c5aSMatthias Ringwald                                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER+2], segment_length);
242727e0774aSMatthias Ringwald                                 break;
242827e0774aSMatthias Ringwald                             case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
2429ed971c5aSMatthias Ringwald                                 // TODO: use current packet
2430ed971c5aSMatthias Ringwald                                 // TODO: check if reassembly started
2431ed971c5aSMatthias Ringwald                                 // TODO: check len against local mtu
2432ed971c5aSMatthias Ringwald                                 sdu_length = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER+2);
2433ed971c5aSMatthias Ringwald                                 payload_offset = COMPLETE_L2CAP_HEADER+4;
2434ed971c5aSMatthias Ringwald                                 segment_length = size - payload_offset-2;
2435ed971c5aSMatthias Ringwald                                 memcpy(&l2cap_channel->rx_packets_data[0], &packet[payload_offset], segment_length);
2436ed971c5aSMatthias Ringwald                                 l2cap_channel->rx_packets_state->sdu_length = sdu_length;
2437ed971c5aSMatthias Ringwald                                 l2cap_channel->rx_packets_state->pos = segment_length;
2438ed971c5aSMatthias Ringwald                                 break;
243927e0774aSMatthias Ringwald                             case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
2440ed971c5aSMatthias Ringwald                                 payload_offset = COMPLETE_L2CAP_HEADER+2;
2441ed971c5aSMatthias Ringwald                                 segment_length = size - payload_offset-2;
2442ed971c5aSMatthias Ringwald                                 memcpy(&l2cap_channel->rx_packets_data[l2cap_channel->rx_packets_state->pos], &packet[payload_offset], segment_length);
2443ed971c5aSMatthias Ringwald                                 l2cap_channel->rx_packets_state->pos += segment_length;
2444ed971c5aSMatthias Ringwald                                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->rx_packets_data, l2cap_channel->rx_packets_state[0].pos);
2445ed971c5aSMatthias Ringwald                                 break;
244627e0774aSMatthias Ringwald                             case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
2447ed971c5aSMatthias Ringwald                                 payload_offset = COMPLETE_L2CAP_HEADER+2;
2448ed971c5aSMatthias Ringwald                                 segment_length = size - payload_offset-2;
2449ed971c5aSMatthias Ringwald                                 memcpy(&l2cap_channel->rx_packets_data[l2cap_channel->rx_packets_state->pos], &packet[payload_offset], segment_length);
2450ed971c5aSMatthias Ringwald                                 l2cap_channel->rx_packets_state->pos += segment_length;
245127e0774aSMatthias Ringwald                                 break;
245227e0774aSMatthias Ringwald                             }
245327e0774aSMatthias Ringwald                     }
245427e0774aSMatthias Ringwald                     break;
245527e0774aSMatthias Ringwald                 }
245627e0774aSMatthias Ringwald #endif
24573d50b4baSMatthias Ringwald                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
245800d93d79Smatthias.ringwald             }
245909e9d05bSMatthias Ringwald #endif
2460a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
246164e11ca9SMatthias Ringwald             l2cap_channel = l2cap_le_get_channel_for_local_cid(channel_id);
246264e11ca9SMatthias Ringwald             if (l2cap_channel) {
246385aeef60SMatthias Ringwald                 // credit counting
246485aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming == 0){
246585aeef60SMatthias Ringwald                     log_error("LE Data Channel packet received but no incoming credits");
246685aeef60SMatthias Ringwald                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
246785aeef60SMatthias Ringwald                     break;
246885aeef60SMatthias Ringwald                 }
246985aeef60SMatthias Ringwald                 l2cap_channel->credits_incoming--;
247085aeef60SMatthias Ringwald 
247185aeef60SMatthias Ringwald                 // automatic credits
247285aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){
247385aeef60SMatthias Ringwald                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
247485aeef60SMatthias Ringwald                 }
247585aeef60SMatthias Ringwald 
2476cd529728SMatthias Ringwald                 // first fragment
2477cd529728SMatthias Ringwald                 uint16_t pos = 0;
2478cd529728SMatthias Ringwald                 if (!l2cap_channel->receive_sdu_len){
2479cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
2480cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_pos = 0;
2481cd529728SMatthias Ringwald                     pos  += 2;
2482cd529728SMatthias Ringwald                     size -= 2;
2483cd529728SMatthias Ringwald                 }
2484cd529728SMatthias Ringwald                 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], size-COMPLETE_L2CAP_HEADER);
2485cd529728SMatthias Ringwald                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
2486cd529728SMatthias Ringwald                 // done?
248763f0ac45SMatthias Ringwald                 log_info("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
2488cd529728SMatthias Ringwald                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
2489cd529728SMatthias Ringwald                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
2490cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = 0;
2491cd529728SMatthias Ringwald                 }
249263f0ac45SMatthias Ringwald             } else {
249363f0ac45SMatthias Ringwald                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
249464e11ca9SMatthias Ringwald             }
249564e11ca9SMatthias Ringwald #endif
24965652b5ffS[email protected]             break;
24975652b5ffS[email protected]     }
249800d93d79Smatthias.ringwald 
24991eb2563eS[email protected]     l2cap_run();
25002718e2e7Smatthias.ringwald }
250100d93d79Smatthias.ringwald 
250209e9d05bSMatthias Ringwald // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
250309e9d05bSMatthias Ringwald void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
250409e9d05bSMatthias Ringwald     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
250509e9d05bSMatthias Ringwald     if (index < 0) return;
250609e9d05bSMatthias Ringwald     fixed_channels[index].callback = the_packet_handler;
250709e9d05bSMatthias Ringwald }
250809e9d05bSMatthias Ringwald 
250909e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
251015ec09bbSmatthias.ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
251127a923d0Smatthias.ringwald void l2cap_finialize_channel_close(l2cap_channel_t * channel){
2512f62db1e3Smatthias.ringwald     channel->state = L2CAP_STATE_CLOSED;
2513f62db1e3Smatthias.ringwald     l2cap_emit_channel_closed(channel);
2514f62db1e3Smatthias.ringwald     // discard channel
25159dcb2fb2S[email protected]     l2cap_stop_rtx(channel);
2516665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2517d3a9df87Smatthias.ringwald     btstack_memory_l2cap_channel_free(channel);
2518c8e4258aSmatthias.ringwald }
25191e6aba47Smatthias.ringwald 
25208f2a52f4SMatthias Ringwald static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
2521665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
2522665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, services);
2523665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2524665d90f2SMatthias Ringwald         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
25259d9bbc01Smatthias.ringwald         if ( service->psm == psm){
25269d9bbc01Smatthias.ringwald             return service;
25279d9bbc01Smatthias.ringwald         };
25289d9bbc01Smatthias.ringwald     }
25299d9bbc01Smatthias.ringwald     return NULL;
25309d9bbc01Smatthias.ringwald }
25319d9bbc01Smatthias.ringwald 
25327192e786SMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
25337192e786SMatthias Ringwald     return l2cap_get_service_internal(&l2cap_services, psm);
25347192e786SMatthias Ringwald }
25357192e786SMatthias Ringwald 
2536e0abb8e7S[email protected] 
2537be2053a6SMatthias Ringwald uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
2538be2053a6SMatthias Ringwald 
2539be2053a6SMatthias Ringwald     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
2540e0abb8e7S[email protected] 
25414bb582b6Smatthias.ringwald     // check for alread registered psm
25429d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
2543277abc2cSmatthias.ringwald     if (service) {
2544be2053a6SMatthias Ringwald         log_error("l2cap_register_service: PSM %u already registered", psm);
2545be2053a6SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
2546277abc2cSmatthias.ringwald     }
25479d9bbc01Smatthias.ringwald 
25484bb582b6Smatthias.ringwald     // alloc structure
2549bb69aaaeS[email protected]     service = btstack_memory_l2cap_service_get();
2550277abc2cSmatthias.ringwald     if (!service) {
2551be2053a6SMatthias Ringwald         log_error("l2cap_register_service: no memory for l2cap_service_t");
2552be2053a6SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
2553277abc2cSmatthias.ringwald     }
25549d9bbc01Smatthias.ringwald 
25559d9bbc01Smatthias.ringwald     // fill in
25569d9bbc01Smatthias.ringwald     service->psm = psm;
25579d9bbc01Smatthias.ringwald     service->mtu = mtu;
255805ae8de3SMatthias Ringwald     service->packet_handler = service_packet_handler;
2559df3354fcS[email protected]     service->required_security_level = security_level;
25609d9bbc01Smatthias.ringwald 
25619d9bbc01Smatthias.ringwald     // add to services list
2562665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
2563c0e866bfSmatthias.ringwald 
2564c0e866bfSmatthias.ringwald     // enable page scan
256515a95bd5SMatthias Ringwald     gap_connectable_control(1);
25665842b6d9Smatthias.ringwald 
2567be2053a6SMatthias Ringwald     return 0;
25689d9bbc01Smatthias.ringwald }
25699d9bbc01Smatthias.ringwald 
25707e8856ebSMatthias Ringwald uint8_t l2cap_unregister_service(uint16_t psm){
2571e0abb8e7S[email protected] 
2572e0abb8e7S[email protected]     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
2573e0abb8e7S[email protected] 
25749d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
25757e8856ebSMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2576665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
2577d3a9df87Smatthias.ringwald     btstack_memory_l2cap_service_free(service);
2578c0e866bfSmatthias.ringwald 
2579c0e866bfSmatthias.ringwald     // disable page scan when no services registered
25807e8856ebSMatthias Ringwald     if (btstack_linked_list_empty(&l2cap_services)) {
258115a95bd5SMatthias Ringwald         gap_connectable_control(0);
25829d9bbc01Smatthias.ringwald     }
25837e8856ebSMatthias Ringwald     return 0;
25847e8856ebSMatthias Ringwald }
258509e9d05bSMatthias Ringwald #endif
25869d9bbc01Smatthias.ringwald 
25877192e786SMatthias Ringwald 
2588cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
258983fd9c76SMatthias Ringwald 
259057be49d6SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
259157be49d6SMatthias Ringwald     if (!channel->waiting_for_can_send_now) return;
259257be49d6SMatthias Ringwald     if (channel->send_sdu_buffer) return;
259357be49d6SMatthias Ringwald     channel->waiting_for_can_send_now = 0;
259457be49d6SMatthias Ringwald     log_info("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
259557be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
259657be49d6SMatthias Ringwald }
259757be49d6SMatthias Ringwald 
259857be49d6SMatthias Ringwald // 1BH2222
259957be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
260057be49d6SMatthias Ringwald     log_info("L2CAP_EVENT_LE_INCOMING_CONNECTION addr_type %u, addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x, remote_mtu %u",
260157be49d6SMatthias Ringwald              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
260257be49d6SMatthias Ringwald     uint8_t event[19];
260357be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
260457be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
260557be49d6SMatthias Ringwald     event[2] = channel->address_type;
260657be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
260757be49d6SMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
260857be49d6SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
260957be49d6SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
261057be49d6SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
261157be49d6SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_mtu);
261257be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
261357be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
261457be49d6SMatthias Ringwald }
261557be49d6SMatthias Ringwald // 11BH22222
261657be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
261757be49d6SMatthias Ringwald     log_info("L2CAP_EVENT_LE_CHANNEL_OPENED status 0x%x addr_type %u addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x local_mtu %u, remote_mtu %u",
261857be49d6SMatthias Ringwald              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
261957be49d6SMatthias Ringwald              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
2620c99bb618SMatthias Ringwald     uint8_t event[23];
262157be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
262257be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
262357be49d6SMatthias Ringwald     event[2] = status;
262457be49d6SMatthias Ringwald     event[3] = channel->address_type;
262557be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[4]);
262657be49d6SMatthias Ringwald     little_endian_store_16(event, 10, channel->con_handle);
2627c99bb618SMatthias Ringwald     event[12] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
2628c99bb618SMatthias Ringwald     little_endian_store_16(event, 13, channel->psm);
2629c99bb618SMatthias Ringwald     little_endian_store_16(event, 15, channel->local_cid);
2630c99bb618SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_cid);
2631c99bb618SMatthias Ringwald     little_endian_store_16(event, 19, channel->local_mtu);
2632c99bb618SMatthias Ringwald     little_endian_store_16(event, 21, channel->remote_mtu);
263357be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
263457be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
263557be49d6SMatthias Ringwald }
263657be49d6SMatthias Ringwald 
263757be49d6SMatthias Ringwald static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid){
263857be49d6SMatthias Ringwald     btstack_linked_list_iterator_t it;
263957be49d6SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
264057be49d6SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
264157be49d6SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
264257be49d6SMatthias Ringwald         if ( channel->local_cid == local_cid) {
264357be49d6SMatthias Ringwald             return channel;
264457be49d6SMatthias Ringwald         }
264557be49d6SMatthias Ringwald     }
264657be49d6SMatthias Ringwald     return NULL;
264757be49d6SMatthias Ringwald }
264857be49d6SMatthias Ringwald 
264957be49d6SMatthias Ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
265057be49d6SMatthias Ringwald void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
265157be49d6SMatthias Ringwald     channel->state = L2CAP_STATE_CLOSED;
265257be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
265357be49d6SMatthias Ringwald     // discard channel
265457be49d6SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
265557be49d6SMatthias Ringwald     btstack_memory_l2cap_channel_free(channel);
265657be49d6SMatthias Ringwald }
265757be49d6SMatthias Ringwald 
2658e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
2659e7d0c9aaSMatthias Ringwald     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
26607192e786SMatthias Ringwald }
2661efedfb4cSMatthias Ringwald 
2662da144af5SMatthias Ringwald uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
26637192e786SMatthias Ringwald 
2664da144af5SMatthias Ringwald     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
26657192e786SMatthias Ringwald 
26667192e786SMatthias Ringwald     // check for alread registered psm
26677192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
26687192e786SMatthias Ringwald     if (service) {
2669da144af5SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
26707192e786SMatthias Ringwald     }
26717192e786SMatthias Ringwald 
26727192e786SMatthias Ringwald     // alloc structure
26737192e786SMatthias Ringwald     service = btstack_memory_l2cap_service_get();
26747192e786SMatthias Ringwald     if (!service) {
26757192e786SMatthias Ringwald         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
2676da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
26777192e786SMatthias Ringwald     }
26787192e786SMatthias Ringwald 
26797192e786SMatthias Ringwald     // fill in
26807192e786SMatthias Ringwald     service->psm = psm;
2681da144af5SMatthias Ringwald     service->mtu = 0;
26827192e786SMatthias Ringwald     service->packet_handler = packet_handler;
26837192e786SMatthias Ringwald     service->required_security_level = security_level;
26847192e786SMatthias Ringwald 
26857192e786SMatthias Ringwald     // add to services list
2686665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
26877192e786SMatthias Ringwald 
26887192e786SMatthias Ringwald     // done
2689da144af5SMatthias Ringwald     return 0;
26907192e786SMatthias Ringwald }
26917192e786SMatthias Ringwald 
2692da144af5SMatthias Ringwald uint8_t l2cap_le_unregister_service(uint16_t psm) {
26937192e786SMatthias Ringwald     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
26947192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
26959367f9b0SMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2696da144af5SMatthias Ringwald 
2697665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
26987192e786SMatthias Ringwald     btstack_memory_l2cap_service_free(service);
2699da144af5SMatthias Ringwald     return 0;
27007192e786SMatthias Ringwald }
2701da144af5SMatthias Ringwald 
2702da144af5SMatthias Ringwald uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
2703e7d0c9aaSMatthias Ringwald     // get channel
2704e7d0c9aaSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2705e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2706e7d0c9aaSMatthias Ringwald 
2707e7d0c9aaSMatthias Ringwald     // validate state
2708e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2709e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
2710e7d0c9aaSMatthias Ringwald     }
2711e7d0c9aaSMatthias Ringwald 
2712efedfb4cSMatthias Ringwald     // set state accept connection
271323017473SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
271423017473SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
271523017473SMatthias Ringwald     channel->local_mtu = mtu;
271685aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
271785aeef60SMatthias Ringwald     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
271885aeef60SMatthias Ringwald 
271985aeef60SMatthias Ringwald     // test
272063f0ac45SMatthias Ringwald     // channel->new_credits_incoming = 1;
2721e7d0c9aaSMatthias Ringwald 
2722e7d0c9aaSMatthias Ringwald     // go
2723e7d0c9aaSMatthias Ringwald     l2cap_run();
2724da144af5SMatthias Ringwald     return 0;
2725da144af5SMatthias Ringwald }
2726da144af5SMatthias Ringwald 
2727da144af5SMatthias Ringwald /**
2728da144af5SMatthias Ringwald  * @brief Deny incoming LE Data Channel connection due to resource constraints
2729da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2730da144af5SMatthias Ringwald  */
2731da144af5SMatthias Ringwald 
2732da144af5SMatthias Ringwald uint8_t l2cap_le_decline_connection(uint16_t local_cid){
2733e7d0c9aaSMatthias Ringwald     // get channel
2734e7d0c9aaSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2735e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2736e7d0c9aaSMatthias Ringwald 
2737e7d0c9aaSMatthias Ringwald     // validate state
2738e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2739e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
2740e7d0c9aaSMatthias Ringwald     }
2741e7d0c9aaSMatthias Ringwald 
2742efedfb4cSMatthias Ringwald     // set state decline connection
2743e7d0c9aaSMatthias Ringwald     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
2744e7d0c9aaSMatthias Ringwald     channel->reason = 0x04; // no resources available
2745e7d0c9aaSMatthias Ringwald     l2cap_run();
2746da144af5SMatthias Ringwald     return 0;
2747da144af5SMatthias Ringwald }
2748da144af5SMatthias Ringwald 
27497dafa750SMatthias Ringwald uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
2750da144af5SMatthias Ringwald     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
2751efedfb4cSMatthias Ringwald     uint16_t * out_local_cid) {
2752efedfb4cSMatthias Ringwald 
27537dafa750SMatthias Ringwald     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
2754da144af5SMatthias Ringwald 
27557dafa750SMatthias Ringwald 
27567dafa750SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
27577dafa750SMatthias Ringwald     if (!connection) {
27587dafa750SMatthias Ringwald         log_error("no hci_connection for handle 0x%04x", con_handle);
27597dafa750SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
27607dafa750SMatthias Ringwald     }
27617dafa750SMatthias Ringwald 
27627dafa750SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, connection->address, connection->address_type, psm, mtu, security_level);
2763da144af5SMatthias Ringwald     if (!channel) {
2764da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
2765da144af5SMatthias Ringwald     }
2766e7d0c9aaSMatthias Ringwald     log_info("l2cap_le_create_channel %p", channel);
2767da144af5SMatthias Ringwald 
2768da144af5SMatthias Ringwald     // store local_cid
2769da144af5SMatthias Ringwald     if (out_local_cid){
2770da144af5SMatthias Ringwald        *out_local_cid = channel->local_cid;
2771da144af5SMatthias Ringwald     }
2772da144af5SMatthias Ringwald 
27737dafa750SMatthias Ringwald     // provide buffer
27747dafa750SMatthias Ringwald     channel->con_handle = con_handle;
2775cd529728SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
27767dafa750SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
277785aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
277885aeef60SMatthias Ringwald     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
277985aeef60SMatthias Ringwald 
2780efedfb4cSMatthias Ringwald     // add to connections list
2781efedfb4cSMatthias Ringwald     btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2782efedfb4cSMatthias Ringwald 
27837dafa750SMatthias Ringwald     // go
278463f0ac45SMatthias Ringwald     l2cap_run();
2785da144af5SMatthias Ringwald     return 0;
2786da144af5SMatthias Ringwald }
2787da144af5SMatthias Ringwald 
2788da144af5SMatthias Ringwald /**
2789da144af5SMatthias Ringwald  * @brief Provide credtis for LE Data Channel
2790da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2791da144af5SMatthias Ringwald  * @param credits               Number additional credits for peer
2792da144af5SMatthias Ringwald  */
279364e11ca9SMatthias Ringwald uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
279463f0ac45SMatthias Ringwald 
279563f0ac45SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
279663f0ac45SMatthias Ringwald     if (!channel) {
279763f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
279863f0ac45SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
279963f0ac45SMatthias Ringwald     }
280063f0ac45SMatthias Ringwald 
2801efedfb4cSMatthias Ringwald     // check state
280263f0ac45SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN){
280363f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
280463f0ac45SMatthias Ringwald     }
280563f0ac45SMatthias Ringwald 
280663f0ac45SMatthias Ringwald     // assert incoming credits + credits <= 0xffff
280763f0ac45SMatthias Ringwald     uint32_t total_credits = channel->credits_incoming;
280863f0ac45SMatthias Ringwald     total_credits += channel->new_credits_incoming;
280963f0ac45SMatthias Ringwald     total_credits += credits;
281063f0ac45SMatthias Ringwald     if (total_credits > 0xffff){
281163f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
281263f0ac45SMatthias Ringwald             channel->new_credits_incoming, credits);
281363f0ac45SMatthias Ringwald     }
281463f0ac45SMatthias Ringwald 
2815efedfb4cSMatthias Ringwald     // set credits_granted
281663f0ac45SMatthias Ringwald     channel->new_credits_incoming += credits;
281763f0ac45SMatthias Ringwald 
281863f0ac45SMatthias Ringwald     // go
281963f0ac45SMatthias Ringwald     l2cap_run();
2820da144af5SMatthias Ringwald     return 0;
2821da144af5SMatthias Ringwald }
2822da144af5SMatthias Ringwald 
2823da144af5SMatthias Ringwald /**
2824da144af5SMatthias Ringwald  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
2825da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2826da144af5SMatthias Ringwald  */
282764e11ca9SMatthias Ringwald int l2cap_le_can_send_now(uint16_t local_cid){
282844276248SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
282944276248SMatthias Ringwald     if (!channel) {
283044276248SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
2831da144af5SMatthias Ringwald         return 0;
2832da144af5SMatthias Ringwald     }
2833da144af5SMatthias Ringwald 
283444276248SMatthias Ringwald     // check state
283544276248SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN) return 0;
283644276248SMatthias Ringwald 
283744276248SMatthias Ringwald     // check queue
283844276248SMatthias Ringwald     if (channel->send_sdu_buffer) return 0;
283944276248SMatthias Ringwald 
284044276248SMatthias Ringwald     // fine, go ahead
284144276248SMatthias Ringwald     return 1;
284244276248SMatthias Ringwald }
284344276248SMatthias Ringwald 
2844da144af5SMatthias Ringwald /**
2845da144af5SMatthias Ringwald  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
2846da144af5SMatthias Ringwald  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
2847da144af5SMatthias Ringwald  *       so packet handler should be ready to handle it
2848da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2849da144af5SMatthias Ringwald  */
285064e11ca9SMatthias Ringwald uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
285144276248SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
285244276248SMatthias Ringwald     if (!channel) {
285344276248SMatthias Ringwald         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
285444276248SMatthias Ringwald         return 0;
285544276248SMatthias Ringwald     }
285644276248SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
285744276248SMatthias Ringwald     l2cap_le_notify_channel_can_send(channel);
2858da144af5SMatthias Ringwald     return 0;
2859da144af5SMatthias Ringwald }
2860da144af5SMatthias Ringwald 
2861da144af5SMatthias Ringwald /**
2862da144af5SMatthias Ringwald  * @brief Send data via LE Data Channel
2863da144af5SMatthias Ringwald  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
2864da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2865da144af5SMatthias Ringwald  * @param data                  data to send
2866da144af5SMatthias Ringwald  * @param size                  data size
2867da144af5SMatthias Ringwald  */
286864e11ca9SMatthias Ringwald uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
286964e11ca9SMatthias Ringwald 
287064e11ca9SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
287164e11ca9SMatthias Ringwald     if (!channel) {
287264e11ca9SMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
2873828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
287464e11ca9SMatthias Ringwald     }
287564e11ca9SMatthias Ringwald 
287664e11ca9SMatthias Ringwald     if (len > channel->remote_mtu){
287764e11ca9SMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
287864e11ca9SMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
287964e11ca9SMatthias Ringwald     }
288064e11ca9SMatthias Ringwald 
28817f107edaSMatthias Ringwald     if (channel->send_sdu_buffer){
288264e11ca9SMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
288364e11ca9SMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
288464e11ca9SMatthias Ringwald     }
288564e11ca9SMatthias Ringwald 
28867f107edaSMatthias Ringwald     channel->send_sdu_buffer = data;
28877f107edaSMatthias Ringwald     channel->send_sdu_len    = len;
28887f107edaSMatthias Ringwald     channel->send_sdu_pos    = 0;
288964e11ca9SMatthias Ringwald 
28907f107edaSMatthias Ringwald     l2cap_run();
28917f107edaSMatthias Ringwald     return 0;
2892da144af5SMatthias Ringwald }
2893da144af5SMatthias Ringwald 
2894da144af5SMatthias Ringwald /**
2895da144af5SMatthias Ringwald  * @brief Disconnect from LE Data Channel
2896da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2897da144af5SMatthias Ringwald  */
2898828a7f7aSMatthias Ringwald uint8_t l2cap_le_disconnect(uint16_t local_cid)
2899da144af5SMatthias Ringwald {
2900828a7f7aSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2901828a7f7aSMatthias Ringwald     if (!channel) {
2902828a7f7aSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
2903828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2904828a7f7aSMatthias Ringwald     }
2905828a7f7aSMatthias Ringwald 
2906828a7f7aSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2907828a7f7aSMatthias Ringwald     l2cap_run();
2908da144af5SMatthias Ringwald     return 0;
2909da144af5SMatthias Ringwald }
2910da144af5SMatthias Ringwald 
29117f02f414SMatthias Ringwald #endif
2912