xref: /btstack/src/l2cap.c (revision d84e866fb87b02372d5534d4932cd5fa66d5315b)
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 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){
55838f62777SMatthias Ringwald     return (req_seq << 8) | (final << 7) | (poll << 4) | (((int) supervisory_function) << 2) | 1;
55985ddcd84SMatthias Ringwald }
56085ddcd84SMatthias Ringwald static int l2cap_next_ertm_seq_nr(int seq_nr){
56185ddcd84SMatthias Ringwald     return (seq_nr + 1) & 0x3f;
56285ddcd84SMatthias Ringwald }
56385ddcd84SMatthias Ringwald #endif
56458de5610Smatthias.ringwald 
565f511cefaSMatthias Ringwald // assumption - only on Classic connections
566ce8f182eSMatthias Ringwald int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
567b1d43497Smatthias.ringwald 
568a35252c8S[email protected]     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
569a35252c8S[email protected]     if (!channel) {
570ce8f182eSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
571a35252c8S[email protected]         return -1;   // TODO: define error
572a35252c8S[email protected]     }
573a35252c8S[email protected] 
574f0efaa57S[email protected]     if (len > channel->remote_mtu){
575ce8f182eSMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
576f0efaa57S[email protected]         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
577f0efaa57S[email protected]     }
578f0efaa57S[email protected] 
579fc64f94aSMatthias Ringwald     if (!hci_can_send_acl_packet_now(channel->con_handle)){
580ce8f182eSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
581b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
582b1d43497Smatthias.ringwald     }
583b1d43497Smatthias.ringwald 
5842a373862S[email protected]     hci_reserve_packet_buffer();
585facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
586b1d43497Smatthias.ringwald 
58785ddcd84SMatthias Ringwald     int control_size = 0;
58885ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
58985ddcd84SMatthias Ringwald     // hack to send i-frames
59085ddcd84SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
59185ddcd84SMatthias Ringwald         uint16_t control = l2cap_encanced_control_field_for_information_frame(channel->next_tx_seq, 0, 0, L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU);
59285ddcd84SMatthias Ringwald         log_info("I-Frame: control 0x%04x", control);
59385ddcd84SMatthias Ringwald         little_endian_store_16(acl_buffer, 8, control);
59485ddcd84SMatthias Ringwald         channel->next_tx_seq = l2cap_next_ertm_seq_nr(channel->next_tx_seq);
59585ddcd84SMatthias Ringwald         control_size = 2;
59685ddcd84SMatthias Ringwald     }
59785ddcd84SMatthias Ringwald #endif
598b1d43497Smatthias.ringwald 
59985ddcd84SMatthias Ringwald     memcpy(&acl_buffer[8+control_size], data, len);
60085ddcd84SMatthias Ringwald 
60185ddcd84SMatthias Ringwald     return l2cap_send_prepared(local_cid, len+control_size);
602b1d43497Smatthias.ringwald }
603b1d43497Smatthias.ringwald 
604fc64f94aSMatthias Ringwald int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
605fc64f94aSMatthias Ringwald     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
6060e37e417S[email protected] }
6070e37e417S[email protected] 
60828ca2b46S[email protected] static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
60928ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
61028ca2b46S[email protected] }
61128ca2b46S[email protected] 
61228ca2b46S[email protected] static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
61328ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
61428ca2b46S[email protected] }
61509e9d05bSMatthias Ringwald #endif
61628ca2b46S[email protected] 
61728ca2b46S[email protected] 
61809e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
61909e9d05bSMatthias Ringwald static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
62009e9d05bSMatthias Ringwald 
62109e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(handle)){
62209e9d05bSMatthias Ringwald         log_info("l2cap_send_le_signaling_packet, cannot send");
62309e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
62409e9d05bSMatthias Ringwald     }
62509e9d05bSMatthias Ringwald 
62609e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
62709e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
62809e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
62909e9d05bSMatthias Ringwald     va_list argptr;
63009e9d05bSMatthias Ringwald     va_start(argptr, identifier);
63109e9d05bSMatthias Ringwald     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
63209e9d05bSMatthias Ringwald     va_end(argptr);
63309e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
63409e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len);
63509e9d05bSMatthias Ringwald }
63609e9d05bSMatthias Ringwald #endif
63709e9d05bSMatthias Ringwald 
63809e9d05bSMatthias Ringwald uint16_t l2cap_max_mtu(void){
63909e9d05bSMatthias Ringwald     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
64009e9d05bSMatthias Ringwald }
64109e9d05bSMatthias Ringwald 
64209e9d05bSMatthias Ringwald uint16_t l2cap_max_le_mtu(void){
64309e9d05bSMatthias Ringwald     return l2cap_max_mtu();
64409e9d05bSMatthias Ringwald }
645b1d43497Smatthias.ringwald 
646450ad7ecSMatthias Ringwald static uint16_t l2cap_setup_options_mtu(l2cap_channel_t * channel, uint8_t * config_options){
647450ad7ecSMatthias Ringwald     config_options[0] = 1; // MTU
648450ad7ecSMatthias Ringwald     config_options[1] = 2; // len param
649450ad7ecSMatthias Ringwald     little_endian_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
650450ad7ecSMatthias Ringwald     return 4;
651450ad7ecSMatthias Ringwald }
652450ad7ecSMatthias Ringwald 
6536dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
654450ad7ecSMatthias Ringwald static uint16_t l2cap_setup_options_ertm(l2cap_channel_t * channel, uint8_t * config_options){
6556dca2a0cSMatthias Ringwald     config_options[0] = 0x04;   // RETRANSMISSION AND FLOW CONTROL OPTION
6566dca2a0cSMatthias Ringwald     config_options[1] = 9;      // length
6576dca2a0cSMatthias Ringwald     config_options[2] = (uint8_t) channel->mode;
6587b181629SMatthias Ringwald     config_options[3] = channel->num_rx_buffers;    // == TxWindows size
659bbc0a9e7SMatthias Ringwald     config_options[4] = channel->local_max_transmit;
660bbc0a9e7SMatthias Ringwald     little_endian_store_16( config_options, 5, channel->local_retransmission_timeout_ms);
661bbc0a9e7SMatthias Ringwald     little_endian_store_16( config_options, 7, channel->local_monitor_timeout_ms);
6627b181629SMatthias Ringwald     little_endian_store_16( config_options, 9, channel->local_mtu);
663450ad7ecSMatthias Ringwald     return 11;
6646dca2a0cSMatthias Ringwald }
66538f62777SMatthias Ringwald static int l2cap_ertm_send_supervisor_frame(l2cap_channel_t * channel, uint16_t control){
66638f62777SMatthias Ringwald     hci_reserve_packet_buffer();
66738f62777SMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
66838f62777SMatthias Ringwald     log_info("S-Frame: control 0x%04x", control);
66938f62777SMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
67038f62777SMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2);
67138f62777SMatthias Ringwald }
672450ad7ecSMatthias Ringwald #endif
673450ad7ecSMatthias Ringwald 
674450ad7ecSMatthias Ringwald static uint16_t l2cap_setup_options(l2cap_channel_t * channel, uint8_t * config_options){
675450ad7ecSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
676450ad7ecSMatthias Ringwald     // use ERTM options if supported
677450ad7ecSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
678450ad7ecSMatthias Ringwald     if ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE) && (connection->l2cap_state.extended_feature_mask & 0x08)){
679450ad7ecSMatthias Ringwald         return l2cap_setup_options_ertm(channel, config_options);
680450ad7ecSMatthias Ringwald 
681450ad7ecSMatthias Ringwald     }
682450ad7ecSMatthias Ringwald #endif
683450ad7ecSMatthias Ringwald     return l2cap_setup_options_mtu(channel, config_options);
6846dca2a0cSMatthias Ringwald }
6856dca2a0cSMatthias Ringwald 
6861b9cb13dSMatthias Ringwald static uint32_t l2cap_extended_features_mask(void){
6871b9cb13dSMatthias Ringwald     // extended features request supported, features: fixed channels, unicast connectionless data reception
6881b9cb13dSMatthias Ringwald     uint32_t features = 0x280;
6891b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
6901b9cb13dSMatthias Ringwald     features |= 0x0008;
6911b9cb13dSMatthias Ringwald #endif
6921b9cb13dSMatthias Ringwald     return features;
6931b9cb13dSMatthias Ringwald }
6941b9cb13dSMatthias Ringwald 
6958158c421Smatthias.ringwald // MARK: L2CAP_RUN
6962cd0be45Smatthias.ringwald // process outstanding signaling tasks
6977f02f414SMatthias Ringwald static void l2cap_run(void){
6982b83fb7dSmatthias.ringwald 
69922c29ab4SMatthias Ringwald     // log_info("l2cap_run: entered");
70022c29ab4SMatthias Ringwald 
7012b83fb7dSmatthias.ringwald     // check pending signaling responses
7022b83fb7dSmatthias.ringwald     while (signaling_responses_pending){
7032b83fb7dSmatthias.ringwald 
7042b83fb7dSmatthias.ringwald         hci_con_handle_t handle = signaling_responses[0].handle;
705a35252c8S[email protected] 
706a35252c8S[email protected]         if (!hci_can_send_acl_packet_now(handle)) break;
707a35252c8S[email protected] 
7082b83fb7dSmatthias.ringwald         uint8_t  sig_id        = signaling_responses[0].sig_id;
709e74c5f58SMatthias Ringwald         uint8_t  response_code = signaling_responses[0].code;
7102b360848Smatthias.ringwald         uint16_t infoType      = signaling_responses[0].data;  // INFORMATION_REQUEST
71163a7246aSmatthias.ringwald         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
712b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
713b3264428SMatthias Ringwald         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
714b3264428SMatthias Ringwald #endif
715f3963406SMatthias Ringwald         UNUSED(infoType);
71609e9d05bSMatthias Ringwald 
717f53da564S[email protected]         // remove first item before sending (to avoid sending response mutliple times)
718f53da564S[email protected]         signaling_responses_pending--;
719f53da564S[email protected]         int i;
720f53da564S[email protected]         for (i=0; i < signaling_responses_pending; i++){
721f53da564S[email protected]             memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t));
722f53da564S[email protected]         }
723f53da564S[email protected] 
724f53da564S[email protected]         switch (response_code){
72509e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
7262b360848Smatthias.ringwald             case CONNECTION_REQUEST:
727e74c5f58SMatthias Ringwald                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
7282bd8b7e7S[email protected]                 // also disconnect if result is 0x0003 - security blocked
7294d816277S[email protected]                 if (result == 0x0003){
7302bd8b7e7S[email protected]                     hci_disconnect_security_block(handle);
7314d816277S[email protected]                 }
7322b360848Smatthias.ringwald                 break;
7332b83fb7dSmatthias.ringwald             case ECHO_REQUEST:
7342b83fb7dSmatthias.ringwald                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
7352b83fb7dSmatthias.ringwald                 break;
7362b83fb7dSmatthias.ringwald             case INFORMATION_REQUEST:
7373b0484b3S[email protected]                 switch (infoType){
7383b0484b3S[email protected]                     case 1: { // Connectionless MTU
7393b0484b3S[email protected]                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
7403b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(connectionless_mtu), &connectionless_mtu);
7413b0484b3S[email protected]                         }
742202c8a4cSMatthias Ringwald                         break;
7433b0484b3S[email protected]                     case 2: {  // Extended Features Supported
7441b9cb13dSMatthias Ringwald                             uint32_t features = l2cap_extended_features_mask();
7453b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(features), &features);
7463b0484b3S[email protected]                         }
747202c8a4cSMatthias Ringwald                         break;
7483b0484b3S[email protected]                     case 3: { // Fixed Channels Supported
7493b0484b3S[email protected]                             uint8_t map[8];
7503b0484b3S[email protected]                             memset(map, 0, 8);
751288636a2SMatthias Ringwald                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
7523b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(map), &map);
7533b0484b3S[email protected]                         }
754202c8a4cSMatthias Ringwald                         break;
7553b0484b3S[email protected]                     default:
7562b83fb7dSmatthias.ringwald                         // all other types are not supported
7572b83fb7dSmatthias.ringwald                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
7583b0484b3S[email protected]                         break;
7592b83fb7dSmatthias.ringwald                 }
7602b83fb7dSmatthias.ringwald                 break;
76163a7246aSmatthias.ringwald             case COMMAND_REJECT:
7625ca8d57bS[email protected]                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
76363f0ac45SMatthias Ringwald                 break;
76409e9d05bSMatthias Ringwald #endif
765a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
76663f0ac45SMatthias Ringwald             case LE_CREDIT_BASED_CONNECTION_REQUEST:
76763f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
76863f0ac45SMatthias Ringwald                 break;
76970efece1S[email protected]             case COMMAND_REJECT_LE:
77070efece1S[email protected]                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
77163a7246aSmatthias.ringwald                 break;
77270efece1S[email protected] #endif
7732b83fb7dSmatthias.ringwald             default:
7742b83fb7dSmatthias.ringwald                 // should not happen
7752b83fb7dSmatthias.ringwald                 break;
7762b83fb7dSmatthias.ringwald         }
7772b83fb7dSmatthias.ringwald     }
7782b83fb7dSmatthias.ringwald 
779665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
780f3963406SMatthias Ringwald     UNUSED(it);
78109e9d05bSMatthias Ringwald 
7821b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
7831b9cb13dSMatthias Ringwald     // send l2cap information request if neccessary
7841b9cb13dSMatthias Ringwald     hci_connections_get_iterator(&it);
7851b9cb13dSMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
7861b9cb13dSMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
7871b9cb13dSMatthias Ringwald         if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST){
7881b9cb13dSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
7891b9cb13dSMatthias Ringwald             // send information request for extended features
7901b9cb13dSMatthias Ringwald             uint8_t sig_id = l2cap_next_sig_id();
7911b9cb13dSMatthias Ringwald             uint8_t info_type = 2;
7921b9cb13dSMatthias Ringwald             l2cap_send_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
7931b9cb13dSMatthias Ringwald             return;
7941b9cb13dSMatthias Ringwald         }
7951b9cb13dSMatthias Ringwald     }
7961b9cb13dSMatthias Ringwald #endif
7971b9cb13dSMatthias Ringwald 
79809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
79943ec931dSMatthias Ringwald     uint8_t  config_options[10];
800665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
801665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
802baf94f06S[email protected] 
803665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
80422c29ab4SMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
8052cd0be45Smatthias.ringwald         switch (channel->state){
8062cd0be45Smatthias.ringwald 
807df3354fcS[email protected]             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
808ad671560S[email protected]             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
809fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
810a00031e2S[email protected]                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
811ad671560S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
812fc64f94aSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
813ad671560S[email protected]                 }
814ad671560S[email protected]                 break;
815ad671560S[email protected] 
81602b22dc4Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
817baf94f06S[email protected]                 if (!hci_can_send_command_packet_now()) break;
81864472d52Smatthias.ringwald                 // send connection request - set state first
81964472d52Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
82002b22dc4Smatthias.ringwald                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
8218f8108aaSmatthias.ringwald                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
82202b22dc4Smatthias.ringwald                 break;
82302b22dc4Smatthias.ringwald 
824e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
825fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
82622c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
827fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
828e7ff783cSmatthias.ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
8299dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
830665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
831d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
832e7ff783cSmatthias.ringwald                 break;
833e7ff783cSmatthias.ringwald 
834552d92a1Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
835fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
836fa8473a4Smatthias.ringwald                 channel->state = L2CAP_STATE_CONFIG;
83728ca2b46S[email protected]                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
838fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
839552d92a1Smatthias.ringwald                 break;
840552d92a1Smatthias.ringwald 
8416fdcc387Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
842fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
8436fdcc387Smatthias.ringwald                 // success, start l2cap handshake
844b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
8456fdcc387Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
846fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
8475932bd7cS[email protected]                 l2cap_start_rtx(channel);
8486fdcc387Smatthias.ringwald                 break;
8496fdcc387Smatthias.ringwald 
850fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
851fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
85273cf2b3dSmatthias.ringwald                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
85363a7246aSmatthias.ringwald                     uint16_t flags = 0;
85428ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
85563a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
85663a7246aSmatthias.ringwald                         flags = 1;
85763a7246aSmatthias.ringwald                     } else {
85828ca2b46S[email protected]                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
85963a7246aSmatthias.ringwald                     }
86063a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
861ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
862fc64f94aSMatthias 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);
863ac8f1300SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
864ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
865ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
866ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
8676dca2a0cSMatthias 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_UNACCEPTABLE_PARAMETERS, options_size, &config_options);
869ac8f1300SMatthias Ringwald #endif
870ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
87163a7246aSmatthias.ringwald                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
872ac8f1300SMatthias Ringwald                         uint16_t options_size = l2cap_setup_options(channel, config_options);
873ac8f1300SMatthias 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);
87463a7246aSmatthias.ringwald                     } else {
875ac8f1300SMatthias Ringwald                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
87663a7246aSmatthias.ringwald                     }
87763a7246aSmatthias.ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
878fa8473a4Smatthias.ringwald                 }
87973cf2b3dSmatthias.ringwald                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
88028ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
88128ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
882b1988dceSmatthias.ringwald                     channel->local_sig_id = l2cap_next_sig_id();
8836dca2a0cSMatthias Ringwald                     uint16_t options_size = l2cap_setup_options(channel, config_options);
8846dca2a0cSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options);
8855932bd7cS[email protected]                     l2cap_start_rtx(channel);
886fa8473a4Smatthias.ringwald                 }
887fa8473a4Smatthias.ringwald                 if (l2cap_channel_ready_for_open(channel)){
888552d92a1Smatthias.ringwald                     channel->state = L2CAP_STATE_OPEN;
889552d92a1Smatthias.ringwald                     l2cap_emit_channel_opened(channel, 0);  // success
890fa8473a4Smatthias.ringwald                 }
891552d92a1Smatthias.ringwald                 break;
892552d92a1Smatthias.ringwald 
893e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
894fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
89522c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
896fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
8975932bd7cS[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 :)
898756102d3Smatthias.ringwald                 l2cap_finialize_channel_close(channel);  // -- remove from list
899e7ff783cSmatthias.ringwald                 break;
900e7ff783cSmatthias.ringwald 
901e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
902fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
903b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
9042cd0be45Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
905fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
9062cd0be45Smatthias.ringwald                 break;
9072cd0be45Smatthias.ringwald             default:
9082cd0be45Smatthias.ringwald                 break;
9092cd0be45Smatthias.ringwald         }
91038f62777SMatthias Ringwald 
91138f62777SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
91238f62777SMatthias Ringwald         // send s-frame to acknowledge received packets
91338f62777SMatthias Ringwald         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
914*d84e866fSMatthias Ringwald         if (channel->send_supervisor_frame_receiver_ready){
915*d84e866fSMatthias Ringwald             channel->send_supervisor_frame_receiver_ready = 0;;
916*d84e866fSMatthias Ringwald             log_info("Send S-Frame: RR %u", channel->req_seq);
91738f62777SMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 0, 0, channel->req_seq);
91838f62777SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
91938f62777SMatthias Ringwald         }
92038f62777SMatthias Ringwald #endif
92138f62777SMatthias Ringwald 
9222cd0be45Smatthias.ringwald     }
92309e9d05bSMatthias Ringwald #endif
924da886c03S[email protected] 
925cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
926efedfb4cSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
927efedfb4cSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
9287f107edaSMatthias Ringwald         uint8_t  * acl_buffer;
9297f107edaSMatthias Ringwald         uint8_t  * l2cap_payload;
9307f107edaSMatthias Ringwald         uint16_t pos;
9317f107edaSMatthias Ringwald         uint16_t payload_size;
932efedfb4cSMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
933efedfb4cSMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
934efedfb4cSMatthias Ringwald         switch (channel->state){
9355cb87675SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
9365cb87675SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
9375cb87675SMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
9385cb87675SMatthias Ringwald                 // le psm, source cid, mtu, mps, initial credits
9391b8b8d05SMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
94063f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
94163f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
94263f0ac45SMatthias 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);
9435cb87675SMatthias Ringwald                 break;
94423017473SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
94523017473SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
94623017473SMatthias Ringwald                 // TODO: support larger MPS
94723017473SMatthias Ringwald                 channel->state = L2CAP_STATE_OPEN;
94863f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
94963f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
95063f0ac45SMatthias 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);
95164e11ca9SMatthias Ringwald                 // notify client
95244276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0);
95323017473SMatthias Ringwald                 break;
954e7d0c9aaSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
955e7d0c9aaSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
956e7d0c9aaSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
95763f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
958e7d0c9aaSMatthias Ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
959e7d0c9aaSMatthias Ringwald                 l2cap_stop_rtx(channel);
960e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
961e7d0c9aaSMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
962e7d0c9aaSMatthias Ringwald                 break;
9637f107edaSMatthias Ringwald             case L2CAP_STATE_OPEN:
96485aeef60SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
96585aeef60SMatthias Ringwald 
96685aeef60SMatthias Ringwald                 // send credits
96785aeef60SMatthias Ringwald                 if (channel->new_credits_incoming){
96885aeef60SMatthias Ringwald                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
96985aeef60SMatthias Ringwald                     channel->local_sig_id = l2cap_next_sig_id();
97085aeef60SMatthias Ringwald                     uint16_t new_credits = channel->new_credits_incoming;
97185aeef60SMatthias Ringwald                     channel->new_credits_incoming = 0;
97285aeef60SMatthias Ringwald                     channel->credits_incoming += new_credits;
97385aeef60SMatthias Ringwald                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
97485aeef60SMatthias Ringwald                     break;
97585aeef60SMatthias Ringwald                 }
97685aeef60SMatthias Ringwald 
97785aeef60SMatthias Ringwald                 // send data
9787f107edaSMatthias Ringwald                 if (!channel->send_sdu_buffer) break;
9797f107edaSMatthias Ringwald                 if (!channel->credits_outgoing) break;
98085aeef60SMatthias Ringwald 
9817f107edaSMatthias Ringwald                 // send part of SDU
9827f107edaSMatthias Ringwald                 hci_reserve_packet_buffer();
9837f107edaSMatthias Ringwald                 acl_buffer = hci_get_outgoing_packet_buffer();
9847f107edaSMatthias Ringwald                 l2cap_payload = acl_buffer + 8;
9857f107edaSMatthias Ringwald                 pos = 0;
9867f107edaSMatthias Ringwald                 if (!channel->send_sdu_pos){
9877f107edaSMatthias Ringwald                     // store SDU len
9887f107edaSMatthias Ringwald                     channel->send_sdu_pos += 2;
9897f107edaSMatthias Ringwald                     little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
9907f107edaSMatthias Ringwald                     pos += 2;
9917f107edaSMatthias Ringwald                 }
9927f107edaSMatthias Ringwald                 payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
99385aeef60SMatthias Ringwald                 log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
9947f107edaSMatthias Ringwald                 memcpy(&l2cap_payload[pos], &channel->send_sdu_buffer[channel->send_sdu_pos-2], payload_size); // -2 for virtual SDU len
9957f107edaSMatthias Ringwald                 pos += payload_size;
9967f107edaSMatthias Ringwald                 channel->send_sdu_pos += payload_size;
997f511cefaSMatthias Ringwald                 l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
9987f107edaSMatthias Ringwald                 // done
9997f107edaSMatthias Ringwald 
100085aeef60SMatthias Ringwald                 channel->credits_outgoing--;
10017f107edaSMatthias Ringwald 
10027f107edaSMatthias Ringwald                 if (channel->send_sdu_pos >= channel->send_sdu_len + 2){
10037f107edaSMatthias Ringwald                     channel->send_sdu_buffer = NULL;
100444276248SMatthias Ringwald                     // send done event
100544276248SMatthias Ringwald                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
100644276248SMatthias Ringwald                     // inform about can send now
100744276248SMatthias Ringwald                     l2cap_le_notify_channel_can_send(channel);
10087f107edaSMatthias Ringwald                 }
10097f107edaSMatthias Ringwald                 hci_send_acl_packet_buffer(8 + pos);
10107f107edaSMatthias Ringwald                 break;
1011828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1012828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1013828a7f7aSMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
1014828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1015828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1016828a7f7aSMatthias Ringwald                 break;
1017828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1018828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1019828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1020828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1021828a7f7aSMatthias Ringwald                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
1022828a7f7aSMatthias Ringwald                 break;
1023efedfb4cSMatthias Ringwald             default:
1024efedfb4cSMatthias Ringwald                 break;
1025efedfb4cSMatthias Ringwald         }
1026efedfb4cSMatthias Ringwald     }
102709e9d05bSMatthias Ringwald #endif
1028efedfb4cSMatthias Ringwald 
102909e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
1030da886c03S[email protected]     // send l2cap con paramter update if necessary
1031da886c03S[email protected]     hci_connections_get_iterator(&it);
1032665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
1033665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
10345d14fa8fSMatthias Ringwald         if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue;
1035b68d7bc3SMatthias Ringwald         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
1036da886c03S[email protected]         switch (connection->le_con_parameter_update_state){
1037b68d7bc3SMatthias Ringwald             case CON_PARAMETER_UPDATE_SEND_REQUEST:
1038b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1039b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier,
1040b68d7bc3SMatthias Ringwald                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
1041b68d7bc3SMatthias Ringwald                 break;
1042da886c03S[email protected]             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
1043b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
1044b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
1045da886c03S[email protected]                 break;
1046da886c03S[email protected]             case CON_PARAMETER_UPDATE_DENY:
1047b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1048b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
1049da886c03S[email protected]                 break;
1050da886c03S[email protected]             default:
1051da886c03S[email protected]                 break;
1052da886c03S[email protected]         }
1053da886c03S[email protected]     }
10544d7157c3S[email protected] #endif
1055da886c03S[email protected] 
105622c29ab4SMatthias Ringwald     // log_info("l2cap_run: exit");
10572cd0be45Smatthias.ringwald }
10582cd0be45Smatthias.ringwald 
105909e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1060fc64f94aSMatthias Ringwald static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
10612df5dadcS[email protected]     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
10625533f01eS[email protected]         log_info("l2cap_handle_connection_complete expected state");
10632df5dadcS[email protected]         // success, start l2cap handshake
1064fc64f94aSMatthias Ringwald         channel->con_handle = con_handle;
10652df5dadcS[email protected]         // check remote SSP feature first
10662df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
10672df5dadcS[email protected]     }
10682df5dadcS[email protected] }
10692df5dadcS[email protected] 
10701b9cb13dSMatthias Ringwald static void l2cap_ready_to_connect(l2cap_channel_t * channel){
10711b9cb13dSMatthias Ringwald 
10721b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
107327e0774aSMatthias Ringwald     // assumption: outgoing connection
10741b9cb13dSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
10751b9cb13dSMatthias Ringwald     if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
10761b9cb13dSMatthias Ringwald         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
10771b9cb13dSMatthias Ringwald         channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
10781b9cb13dSMatthias Ringwald         return;
10791b9cb13dSMatthias Ringwald     }
10801b9cb13dSMatthias Ringwald #endif
10811b9cb13dSMatthias Ringwald 
10821b9cb13dSMatthias Ringwald     // fine, go ahead
10831b9cb13dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
10841b9cb13dSMatthias Ringwald }
10851b9cb13dSMatthias Ringwald 
10862df5dadcS[email protected] static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
10872df5dadcS[email protected]     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
10882df5dadcS[email protected] 
10892df5dadcS[email protected]     // we have been waiting for remote supported features, if both support SSP,
1090ac301f95S[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));
1091fc64f94aSMatthias Ringwald     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
10922df5dadcS[email protected]         // request security level 2
10932df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
1094fc64f94aSMatthias Ringwald         gap_request_security_level(channel->con_handle, LEVEL_2);
10952df5dadcS[email protected]         return;
10962df5dadcS[email protected]     }
10971b9cb13dSMatthias Ringwald 
10981b9cb13dSMatthias Ringwald     l2cap_ready_to_connect(channel);
10992df5dadcS[email protected] }
110009e9d05bSMatthias Ringwald #endif
11012df5dadcS[email protected] 
110209e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
1103da144af5SMatthias 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,
1104da144af5SMatthias Ringwald     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
1105da144af5SMatthias Ringwald 
1106da144af5SMatthias Ringwald     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1107da144af5SMatthias Ringwald     if (!channel) {
1108da144af5SMatthias Ringwald         return NULL;
1109da144af5SMatthias Ringwald     }
1110da144af5SMatthias Ringwald 
1111da144af5SMatthias Ringwald      // Init memory (make valgrind happy)
1112da144af5SMatthias Ringwald     memset(channel, 0, sizeof(l2cap_channel_t));
1113da144af5SMatthias Ringwald 
1114da144af5SMatthias Ringwald     // fill in
1115da144af5SMatthias Ringwald     channel->packet_handler = packet_handler;
1116da144af5SMatthias Ringwald     bd_addr_copy(channel->address, address);
1117da144af5SMatthias Ringwald     channel->address_type = address_type;
1118da144af5SMatthias Ringwald     channel->psm = psm;
1119da144af5SMatthias Ringwald     channel->local_mtu  = local_mtu;
1120da144af5SMatthias Ringwald     channel->remote_mtu = L2CAP_MINIMAL_MTU;
1121da144af5SMatthias Ringwald     channel->required_security_level = security_level;
1122da144af5SMatthias Ringwald 
1123da144af5SMatthias Ringwald     //
1124da144af5SMatthias Ringwald     channel->local_cid = l2cap_next_local_cid();
1125da144af5SMatthias Ringwald     channel->con_handle = 0;
1126da144af5SMatthias Ringwald 
1127da144af5SMatthias Ringwald     // set initial state
1128da144af5SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
1129da144af5SMatthias Ringwald     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
1130da144af5SMatthias Ringwald     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
1131da144af5SMatthias Ringwald     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
113238f62777SMatthias Ringwald 
1133da144af5SMatthias Ringwald     return channel;
1134da144af5SMatthias Ringwald }
113509e9d05bSMatthias Ringwald #endif
113609e9d05bSMatthias Ringwald 
113709e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1138da144af5SMatthias Ringwald 
11399077cb15SMatthias Ringwald /**
11409077cb15SMatthias Ringwald  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
11419077cb15SMatthias Ringwald  * @param packet_handler
11429077cb15SMatthias Ringwald  * @param address
11439077cb15SMatthias Ringwald  * @param psm
11449077cb15SMatthias Ringwald  * @param mtu
11459077cb15SMatthias Ringwald  * @param local_cid
11469077cb15SMatthias Ringwald  */
11479077cb15SMatthias Ringwald 
11489d139fbaSMatthias 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){
11499d139fbaSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
11509d139fbaSMatthias Ringwald     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1151da144af5SMatthias Ringwald 
11529d139fbaSMatthias 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);
1153da144af5SMatthias Ringwald 
1154da144af5SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
1155fc64f94aSMatthias Ringwald     if (!channel) {
11569077cb15SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
11579077cb15SMatthias Ringwald     }
11589077cb15SMatthias Ringwald 
11591b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
11601b9cb13dSMatthias Ringwald     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
11611b9cb13dSMatthias Ringwald #endif
11621b9cb13dSMatthias Ringwald 
11639077cb15SMatthias Ringwald     // add to connections list
1164fc64f94aSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
11659077cb15SMatthias Ringwald 
11669077cb15SMatthias Ringwald     // store local_cid
11679077cb15SMatthias Ringwald     if (out_local_cid){
1168fc64f94aSMatthias Ringwald        *out_local_cid = channel->local_cid;
11699077cb15SMatthias Ringwald     }
11709077cb15SMatthias Ringwald 
11719077cb15SMatthias Ringwald     // check if hci connection is already usable
11729077cb15SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
11739077cb15SMatthias Ringwald     if (conn){
1174add0254bSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
1175fc64f94aSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
11769077cb15SMatthias Ringwald         // check if remote supported fearures are already received
11779077cb15SMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
1178fc64f94aSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
11799077cb15SMatthias Ringwald         }
11809077cb15SMatthias Ringwald     }
11819077cb15SMatthias Ringwald 
11829077cb15SMatthias Ringwald     l2cap_run();
11839077cb15SMatthias Ringwald 
11849077cb15SMatthias Ringwald     return 0;
11859077cb15SMatthias Ringwald }
11869077cb15SMatthias Ringwald 
11871b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
11887b181629SMatthias Ringwald 
11892b70d705SMatthias Ringwald static uint8_t l2cap_ertm_validate_local_config(uint8_t max_transmit, uint16_t retransmission_timeout_ms,
11902b70d705SMatthias Ringwald     uint16_t monitor_timeout_ms, uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size){
11912b70d705SMatthias Ringwald     UNUSED(buffer);
11922b70d705SMatthias Ringwald     UNUSED(size);
11932b70d705SMatthias Ringwald 
11942b70d705SMatthias Ringwald     uint8_t result = ERROR_CODE_SUCCESS;
11952b70d705SMatthias Ringwald     if (max_transmit < 1){
11962b70d705SMatthias Ringwald         log_error("max_transmit must be >= 1");
11972b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
11982b70d705SMatthias Ringwald     }
11992b70d705SMatthias Ringwald     if (retransmission_timeout_ms < 2000){
12002b70d705SMatthias Ringwald         log_error("retransmission_timeout_ms must be >= 2000 ms");
12012b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
12022b70d705SMatthias Ringwald     }
12032b70d705SMatthias Ringwald     if (monitor_timeout_ms < 12000){
12042b70d705SMatthias Ringwald         log_error("monitor_timeout_ms must be >= 12000 ms");
12052b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
12062b70d705SMatthias Ringwald     }
12072b70d705SMatthias Ringwald     if (num_rx_buffers < 1){
12082b70d705SMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
12092b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
12102b70d705SMatthias Ringwald     }
12112b70d705SMatthias Ringwald     if (num_tx_buffers < 1){
12122b70d705SMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
12132b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
12142b70d705SMatthias Ringwald     }
12152b70d705SMatthias Ringwald     return result;
12162b70d705SMatthias Ringwald }
12172b70d705SMatthias Ringwald 
12187b181629SMatthias Ringwald static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, int ertm_mandatory, uint8_t max_transmit,
12197b181629SMatthias 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){
12207b181629SMatthias Ringwald 
12217b181629SMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
12227b181629SMatthias Ringwald     channel->ertm_mandatory = ertm_mandatory;
1223bbc0a9e7SMatthias Ringwald     channel->local_max_transmit = max_transmit;
1224bbc0a9e7SMatthias Ringwald     channel->local_retransmission_timeout_ms = retransmission_timeout_ms;
1225bbc0a9e7SMatthias Ringwald     channel->local_monitor_timeout_ms = monitor_timeout_ms;
12267b181629SMatthias Ringwald     channel->num_rx_buffers = num_rx_buffers;
12277b181629SMatthias Ringwald     channel->num_tx_buffers = num_tx_buffers;
12287b181629SMatthias Ringwald 
12297b181629SMatthias Ringwald     // TODO: align buffer pointer
12307b181629SMatthias Ringwald     uint32_t pos = 0;
12317b181629SMatthias Ringwald     channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) &buffer[pos];
12327b181629SMatthias Ringwald     pos += num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
12337b181629SMatthias Ringwald     channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) &buffer[pos];
12347b181629SMatthias Ringwald     pos += num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
12357b181629SMatthias Ringwald     // calculate MTU
12367b181629SMatthias Ringwald     channel->local_mtu = (size - pos) / (num_rx_buffers + num_tx_buffers);
12377b181629SMatthias Ringwald     log_info("Local ERTM MTU: %u", channel->local_mtu);
12387b181629SMatthias Ringwald     channel->rx_packets_data = &buffer[pos];
12397b181629SMatthias Ringwald     pos += num_rx_buffers * channel->local_mtu;
12407b181629SMatthias Ringwald     channel->tx_packets_data = &buffer[pos];
12417b181629SMatthias Ringwald     log_info("RX packets %p, TX packets %p", channel->rx_packets_data, channel->tx_packets_data);
12427b181629SMatthias Ringwald }
12437b181629SMatthias Ringwald 
1244501329faSMatthias Ringwald uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
1245501329faSMatthias Ringwald     int ertm_mandatory, uint8_t max_transmit, uint16_t retransmission_timeout_ms, uint16_t monitor_timeout_ms,
1246501329faSMatthias Ringwald     uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
1247501329faSMatthias Ringwald 
12481b9cb13dSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
1249501329faSMatthias Ringwald     uint16_t local_mtu = l2cap_max_mtu();
12501b9cb13dSMatthias Ringwald 
1251501329faSMatthias Ringwald     log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x -> local mtu %u", bd_addr_to_str(address), psm, local_mtu);
12521b9cb13dSMatthias Ringwald 
12532b70d705SMatthias Ringwald     // validate local config
12542b70d705SMatthias 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);
12552b70d705SMatthias Ringwald     if (result) return result;
12562b70d705SMatthias Ringwald 
1257501329faSMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
12581b9cb13dSMatthias Ringwald     if (!channel) {
12591b9cb13dSMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
12601b9cb13dSMatthias Ringwald     }
12611b9cb13dSMatthias Ringwald 
12627b181629SMatthias Ringwald     // configure ERTM
12637b181629SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_mandatory, max_transmit, retransmission_timeout_ms,
12647b181629SMatthias Ringwald         monitor_timeout_ms, num_tx_buffers, num_rx_buffers, buffer, size);
12651b9cb13dSMatthias Ringwald 
12661b9cb13dSMatthias Ringwald     // add to connections list
12671b9cb13dSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
12681b9cb13dSMatthias Ringwald 
12691b9cb13dSMatthias Ringwald     // store local_cid
12701b9cb13dSMatthias Ringwald     if (out_local_cid){
12711b9cb13dSMatthias Ringwald        *out_local_cid = channel->local_cid;
12721b9cb13dSMatthias Ringwald     }
12731b9cb13dSMatthias Ringwald 
12741b9cb13dSMatthias Ringwald     // check if hci connection is already usable
12751b9cb13dSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
12761b9cb13dSMatthias Ringwald     if (conn){
12771b9cb13dSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
12781b9cb13dSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
12791b9cb13dSMatthias Ringwald         // check if remote supported fearures are already received
12801b9cb13dSMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
12811b9cb13dSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
12821b9cb13dSMatthias Ringwald         }
12831b9cb13dSMatthias Ringwald     }
12841b9cb13dSMatthias Ringwald 
12851b9cb13dSMatthias Ringwald     l2cap_run();
12861b9cb13dSMatthias Ringwald 
12871b9cb13dSMatthias Ringwald     return 0;
12881b9cb13dSMatthias Ringwald }
12891b9cb13dSMatthias Ringwald #endif
12901b9cb13dSMatthias Ringwald 
1291ce8f182eSMatthias Ringwald void
1292ce8f182eSMatthias Ringwald l2cap_disconnect(uint16_t local_cid, uint8_t reason){
1293e0abb8e7S[email protected]     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
1294b35f641cSmatthias.ringwald     // find channel for local_cid
1295b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1296f62db1e3Smatthias.ringwald     if (channel) {
1297e7ff783cSmatthias.ringwald         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1298f62db1e3Smatthias.ringwald     }
12992cd0be45Smatthias.ringwald     // process
13002cd0be45Smatthias.ringwald     l2cap_run();
130143625864Smatthias.ringwald }
13021e6aba47Smatthias.ringwald 
1303afde0c52Smatthias.ringwald static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
1304665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1305665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1306665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1307665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1308058e3d6bSMatthias Ringwald         if ( bd_addr_cmp( channel->address, address) != 0) continue;
1309c22aecc9S[email protected]         // channel for this address found
1310c22aecc9S[email protected]         switch (channel->state){
1311c22aecc9S[email protected]             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
1312c22aecc9S[email protected]             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1313afde0c52Smatthias.ringwald                 // failure, forward error code
1314afde0c52Smatthias.ringwald                 l2cap_emit_channel_opened(channel, status);
1315afde0c52Smatthias.ringwald                 // discard channel
13169dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
1317665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1318d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
1319c22aecc9S[email protected]                 break;
1320c22aecc9S[email protected]             default:
1321c22aecc9S[email protected]                 break;
1322afde0c52Smatthias.ringwald         }
1323afde0c52Smatthias.ringwald     }
1324afde0c52Smatthias.ringwald }
1325afde0c52Smatthias.ringwald 
1326afde0c52Smatthias.ringwald static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
1327665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1328665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1329665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1330665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1331058e3d6bSMatthias Ringwald         if ( ! bd_addr_cmp( channel->address, address) ){
13322df5dadcS[email protected]             l2cap_handle_connection_complete(handle, channel);
1333afde0c52Smatthias.ringwald         }
1334afde0c52Smatthias.ringwald     }
13356fdcc387Smatthias.ringwald     // process
13366fdcc387Smatthias.ringwald     l2cap_run();
1337afde0c52Smatthias.ringwald }
133809e9d05bSMatthias Ringwald #endif
1339b448a0e7Smatthias.ringwald 
134033c40538SMatthias Ringwald static void l2cap_notify_channel_can_send(void){
134109e9d05bSMatthias Ringwald 
134209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
134333c40538SMatthias Ringwald     btstack_linked_list_iterator_t it;
134433c40538SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
134533c40538SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
134633c40538SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
134733c40538SMatthias Ringwald         if (!channel->waiting_for_can_send_now) continue;
1348fc64f94aSMatthias Ringwald         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
134933c40538SMatthias Ringwald         channel->waiting_for_can_send_now = 0;
135034e7e577SMatthias Ringwald         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
135133c40538SMatthias Ringwald     }
135209e9d05bSMatthias Ringwald #endif
135344276248SMatthias Ringwald 
13542125de09SMatthias Ringwald     int i;
13552125de09SMatthias Ringwald     for (i=0;i<L2CAP_FIXED_CHANNEL_TABLE_SIZE;i++){
1356773c4106SMatthias Ringwald         if (!fixed_channels[i].callback) continue;
13572125de09SMatthias Ringwald         if (!fixed_channels[i].waiting_for_can_send_now) continue;
135835454696SMatthias Ringwald         int can_send = 0;
135934e7e577SMatthias Ringwald         if (l2cap_fixed_channel_table_index_is_le(i)){
136035454696SMatthias Ringwald #ifdef ENABLE_BLE
136134e7e577SMatthias Ringwald             can_send = hci_can_send_acl_le_packet_now();
136235454696SMatthias Ringwald #endif
136334e7e577SMatthias Ringwald         } else {
136435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
136534e7e577SMatthias Ringwald             can_send = hci_can_send_acl_classic_packet_now();
136635454696SMatthias Ringwald #endif
136734e7e577SMatthias Ringwald         }
136834e7e577SMatthias Ringwald         if (!can_send) continue;
136934e7e577SMatthias Ringwald         fixed_channels[i].waiting_for_can_send_now = 0;
137034e7e577SMatthias Ringwald         l2cap_emit_can_send_now(fixed_channels[i].callback, l2cap_fixed_channel_table_channel_id_for_index(i));
13712125de09SMatthias Ringwald     }
137233c40538SMatthias Ringwald }
137333c40538SMatthias Ringwald 
1374d9a7306aSMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
1375afde0c52Smatthias.ringwald 
13769ec2630cSMatthias Ringwald     UNUSED(packet_type);
13779ec2630cSMatthias Ringwald     UNUSED(cid);
13789ec2630cSMatthias Ringwald     UNUSED(size);
13799ec2630cSMatthias Ringwald 
1380afde0c52Smatthias.ringwald     bd_addr_t address;
1381afde0c52Smatthias.ringwald     hci_con_handle_t handle;
13822d00edd4Smatthias.ringwald     int hci_con_used;
138309e9d05bSMatthias Ringwald     btstack_linked_list_iterator_t it;
138409e9d05bSMatthias Ringwald 
138509e9d05bSMatthias Ringwald     // avoid unused warnings
1386f3963406SMatthias Ringwald     UNUSED(address);
1387f3963406SMatthias Ringwald     UNUSED(hci_con_used);
1388f3963406SMatthias Ringwald     UNUSED(it);
1389f22209dfSMatthias Ringwald     UNUSED(handle);
1390afde0c52Smatthias.ringwald 
13910e2df43fSMatthias Ringwald     switch(hci_event_packet_get_type(packet)){
1392afde0c52Smatthias.ringwald 
139309e9d05bSMatthias Ringwald         // Notify channel packet handler if they can send now
139409e9d05bSMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
139509e9d05bSMatthias Ringwald         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
139609e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
139709e9d05bSMatthias Ringwald             l2cap_notify_channel_can_send();
139809e9d05bSMatthias Ringwald             break;
139909e9d05bSMatthias Ringwald 
140009e9d05bSMatthias Ringwald         case HCI_EVENT_COMMAND_STATUS:
140109e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
140209e9d05bSMatthias Ringwald             break;
140309e9d05bSMatthias Ringwald 
140409e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1405afde0c52Smatthias.ringwald         // handle connection complete events
1406afde0c52Smatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
1407724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], address);
1408afde0c52Smatthias.ringwald             if (packet[2] == 0){
1409f8fbdce0SMatthias Ringwald                 handle = little_endian_read_16(packet, 3);
1410afde0c52Smatthias.ringwald                 l2cap_handle_connection_success_for_addr(address, handle);
1411afde0c52Smatthias.ringwald             } else {
1412afde0c52Smatthias.ringwald                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
1413afde0c52Smatthias.ringwald             }
1414afde0c52Smatthias.ringwald             break;
1415afde0c52Smatthias.ringwald 
1416afde0c52Smatthias.ringwald         // handle successful create connection cancel command
1417afde0c52Smatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
1418073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
1419afde0c52Smatthias.ringwald                 if (packet[5] == 0){
1420724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[6], address);
1421afde0c52Smatthias.ringwald                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
1422afde0c52Smatthias.ringwald                     l2cap_handle_connection_failed_for_addr(address, 0x16);
142303cfbabcSmatthias.ringwald                 }
14241e6aba47Smatthias.ringwald             }
142539d59809Smatthias.ringwald             l2cap_run();    // try sending signaling packets first
142639d59809Smatthias.ringwald             break;
142709e9d05bSMatthias Ringwald #endif
142827a923d0Smatthias.ringwald 
14291e6aba47Smatthias.ringwald         // handle disconnection complete events
1430afde0c52Smatthias.ringwald         case HCI_EVENT_DISCONNECTION_COMPLETE:
1431c22aecc9S[email protected]             // send l2cap disconnect events for all channels on this handle and free them
143209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1433d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1434665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1435665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1436665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1437fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
143815ec09bbSmatthias.ringwald                 l2cap_emit_channel_closed(channel);
14399dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
1440665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1441d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
144227a923d0Smatthias.ringwald             }
144309e9d05bSMatthias Ringwald #endif
1444a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1445d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1446991fea48SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1447991fea48SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1448991fea48SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1449991fea48SMatthias Ringwald                 if (channel->con_handle != handle) continue;
1450991fea48SMatthias Ringwald                 l2cap_emit_channel_closed(channel);
1451991fea48SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1452991fea48SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
1453991fea48SMatthias Ringwald             }
1454991fea48SMatthias Ringwald #endif
1455afde0c52Smatthias.ringwald             break;
1456fcadd0caSmatthias.ringwald 
1457ee091cf1Smatthias.ringwald         // HCI Connection Timeouts
145809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1459afde0c52Smatthias.ringwald         case L2CAP_EVENT_TIMEOUT_CHECK:
1460f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
1461bd04d84aSMatthias Ringwald             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
146280ca58a0Smatthias.ringwald             if (hci_authentication_active_for_handle(handle)) break;
14632d00edd4Smatthias.ringwald             hci_con_used = 0;
1464665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1465665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1466665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1467fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
14682d00edd4Smatthias.ringwald                 hci_con_used = 1;
1469c22aecc9S[email protected]                 break;
1470ee091cf1Smatthias.ringwald             }
14712d00edd4Smatthias.ringwald             if (hci_con_used) break;
1472d94d3cafS[email protected]             if (!hci_can_send_command_packet_now()) break;
14739edc8742Smatthias.ringwald             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
1474afde0c52Smatthias.ringwald             break;
1475ee091cf1Smatthias.ringwald 
1476df3354fcS[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1477f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1478665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1479665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1480665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1481fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
14822df5dadcS[email protected]                 l2cap_handle_remote_supported_features_received(channel);
1483df3354fcS[email protected]                 break;
1484df3354fcS[email protected]             }
1485c22aecc9S[email protected]             break;
1486df3354fcS[email protected] 
14875611a760SMatthias Ringwald         case GAP_EVENT_SECURITY_LEVEL:
1488f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
1489bd63148eS[email protected]             log_info("l2cap - security level update");
1490665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1491665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1492665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1493fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
14945533f01eS[email protected] 
1495bd63148eS[email protected]                 log_info("l2cap - state %u", channel->state);
1496bd63148eS[email protected] 
1497e569dfd9SMatthias Ringwald                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
14985533f01eS[email protected]                 gap_security_level_t required_level = channel->required_security_level;
14995533f01eS[email protected] 
1500df3354fcS[email protected]                 switch (channel->state){
1501df3354fcS[email protected]                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
15025533f01eS[email protected]                         if (actual_level >= required_level){
150352606043SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
150452606043SMatthias Ringwald                             // we need to know if ERTM is supported before sending a config response
150552606043SMatthias Ringwald                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
150652606043SMatthias Ringwald                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
150752606043SMatthias Ringwald                             channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
150852606043SMatthias Ringwald #else
1509f85a9399S[email protected]                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
151044276248SMatthias Ringwald                             l2cap_emit_incoming_connection(channel);
151152606043SMatthias Ringwald #endif
15121eb2563eS[email protected]                         } else {
1513775ecc36SMatthias Ringwald                             channel->reason = 0x0003; // security block
15141eb2563eS[email protected]                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
15151eb2563eS[email protected]                         }
1516df3354fcS[email protected]                         break;
1517df3354fcS[email protected] 
1518df3354fcS[email protected]                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
15195533f01eS[email protected]                         if (actual_level >= required_level){
15201b9cb13dSMatthias Ringwald                             l2cap_ready_to_connect(channel);
1521df3354fcS[email protected]                         } else {
1522df3354fcS[email protected]                             // disconnnect, authentication not good enough
1523df3354fcS[email protected]                             hci_disconnect_security_block(handle);
1524df3354fcS[email protected]                         }
1525df3354fcS[email protected]                         break;
1526df3354fcS[email protected] 
1527df3354fcS[email protected]                     default:
1528df3354fcS[email protected]                         break;
1529df3354fcS[email protected]                 }
1530f85a9399S[email protected]             }
1531f85a9399S[email protected]             break;
153209e9d05bSMatthias Ringwald #endif
1533f85a9399S[email protected] 
1534afde0c52Smatthias.ringwald         default:
1535afde0c52Smatthias.ringwald             break;
1536afde0c52Smatthias.ringwald     }
1537afde0c52Smatthias.ringwald 
1538bd63148eS[email protected]     l2cap_run();
15391e6aba47Smatthias.ringwald }
15401e6aba47Smatthias.ringwald 
1541e74c5f58SMatthias 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){
15424cf56b4aSmatthias.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."
15432b360848Smatthias.ringwald     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
15442b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].handle = handle;
15452b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].code = code;
15462b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].sig_id = sig_id;
1547e74c5f58SMatthias Ringwald         signaling_responses[signaling_responses_pending].cid = cid;
15482b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].data = data;
15492b360848Smatthias.ringwald         signaling_responses_pending++;
15502b360848Smatthias.ringwald         l2cap_run();
15512b360848Smatthias.ringwald     }
15522b360848Smatthias.ringwald }
15532b360848Smatthias.ringwald 
155409e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
155509e9d05bSMatthias Ringwald static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
155609e9d05bSMatthias Ringwald     channel->remote_sig_id = identifier;
155709e9d05bSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
155809e9d05bSMatthias Ringwald     l2cap_run();
155909e9d05bSMatthias Ringwald }
156009e9d05bSMatthias Ringwald 
1561b35f641cSmatthias.ringwald static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
1562645658c9Smatthias.ringwald 
15639da54300S[email protected]     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
1564645658c9Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
1565645658c9Smatthias.ringwald     if (!service) {
1566645658c9Smatthias.ringwald         // 0x0002 PSM not supported
1567e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
1568645658c9Smatthias.ringwald         return;
1569645658c9Smatthias.ringwald     }
1570645658c9Smatthias.ringwald 
15715061f3afS[email protected]     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
1572645658c9Smatthias.ringwald     if (!hci_connection) {
15732b360848Smatthias.ringwald         //
15749da54300S[email protected]         log_error("no hci_connection for handle %u", handle);
1575645658c9Smatthias.ringwald         return;
1576645658c9Smatthias.ringwald     }
15772bd8b7e7S[email protected] 
1578645658c9Smatthias.ringwald     // alloc structure
15799da54300S[email protected]     // log_info("l2cap_handle_connection_request register channel");
1580da144af5SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, hci_connection->address, BD_ADDR_TYPE_CLASSIC,
1581da144af5SMatthias Ringwald     psm, service->mtu, service->required_security_level);
15822b360848Smatthias.ringwald     if (!channel){
15832b360848Smatthias.ringwald         // 0x0004 No resources available
1584e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
15852b360848Smatthias.ringwald         return;
15862b360848Smatthias.ringwald     }
1587da144af5SMatthias Ringwald 
1588fc64f94aSMatthias Ringwald     channel->con_handle = handle;
1589b35f641cSmatthias.ringwald     channel->remote_cid = source_cid;
1590b1988dceSmatthias.ringwald     channel->remote_sig_id = sig_id;
1591645658c9Smatthias.ringwald 
1592f53da564S[email protected]     // limit local mtu to max acl packet length - l2cap header
15932985cb84Smatthias.ringwald     if (channel->local_mtu > l2cap_max_mtu()) {
15942985cb84Smatthias.ringwald         channel->local_mtu = l2cap_max_mtu();
15959775e25bSmatthias.ringwald     }
15969775e25bSmatthias.ringwald 
1597645658c9Smatthias.ringwald     // set initial state
1598df3354fcS[email protected]     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
1599a24785d0SMatthias Ringwald     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
1600e405ae81Smatthias.ringwald 
1601645658c9Smatthias.ringwald     // add to connections list
1602665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1603645658c9Smatthias.ringwald 
1604f85a9399S[email protected]     // assert security requirements
16051eb2563eS[email protected]     gap_request_security_level(handle, channel->required_security_level);
1606e405ae81Smatthias.ringwald }
1607645658c9Smatthias.ringwald 
1608ce8f182eSMatthias Ringwald void l2cap_accept_connection(uint16_t local_cid){
1609e0abb8e7S[email protected]     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
1610b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1611e405ae81Smatthias.ringwald     if (!channel) {
1612ce8f182eSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
1613e405ae81Smatthias.ringwald         return;
1614e405ae81Smatthias.ringwald     }
1615e405ae81Smatthias.ringwald 
161643ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
161743ec931dSMatthias Ringwald     // configure L2CAP Basic mode
161843ec931dSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
161943ec931dSMatthias Ringwald #endif
162043ec931dSMatthias Ringwald 
1621552d92a1Smatthias.ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
1622e405ae81Smatthias.ringwald 
1623552d92a1Smatthias.ringwald     // process
1624552d92a1Smatthias.ringwald     l2cap_run();
1625e405ae81Smatthias.ringwald }
1626645658c9Smatthias.ringwald 
162743ec931dSMatthias Ringwald 
162843ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
16292b70d705SMatthias Ringwald uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, int ertm_mandatory, uint8_t max_transmit,
1630501329faSMatthias 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){
1631501329faSMatthias Ringwald 
163243ec931dSMatthias Ringwald     log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
163343ec931dSMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
163443ec931dSMatthias Ringwald     if (!channel) {
163543ec931dSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
16362b70d705SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
163743ec931dSMatthias Ringwald     }
163843ec931dSMatthias Ringwald 
16392b70d705SMatthias Ringwald     // validate local config
16402b70d705SMatthias 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);
16412b70d705SMatthias Ringwald     if (result) return result;
16422b70d705SMatthias Ringwald 
164343ec931dSMatthias Ringwald     // configure L2CAP ERTM
16447b181629SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_mandatory, max_transmit, retransmission_timeout_ms, monitor_timeout_ms, num_tx_buffers, num_rx_buffers, buffer, size);
164543ec931dSMatthias Ringwald 
16467b181629SMatthias Ringwald     // continue
164743ec931dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
164843ec931dSMatthias Ringwald 
164943ec931dSMatthias Ringwald     // process
165043ec931dSMatthias Ringwald     l2cap_run();
16512b70d705SMatthias Ringwald 
16522b70d705SMatthias Ringwald     return ERROR_CODE_SUCCESS;
165343ec931dSMatthias Ringwald }
165443ec931dSMatthias Ringwald #endif
165543ec931dSMatthias Ringwald 
165643ec931dSMatthias Ringwald 
16577ef6a7bbSMatthias Ringwald void l2cap_decline_connection(uint16_t local_cid){
16587ef6a7bbSMatthias Ringwald     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
1659b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
1660e405ae81Smatthias.ringwald     if (!channel) {
1661ce8f182eSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
1662e405ae81Smatthias.ringwald         return;
1663e405ae81Smatthias.ringwald     }
1664e7ff783cSmatthias.ringwald     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
16657ef6a7bbSMatthias Ringwald     channel->reason = 0x04; // no resources available
1666e7ff783cSmatthias.ringwald     l2cap_run();
1667645658c9Smatthias.ringwald }
1668645658c9Smatthias.ringwald 
16697f02f414SMatthias Ringwald static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
1670b1988dceSmatthias.ringwald 
1671b1988dceSmatthias.ringwald     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1672b1988dceSmatthias.ringwald 
1673f8fbdce0SMatthias Ringwald     uint16_t flags = little_endian_read_16(command, 6);
167463a7246aSmatthias.ringwald     if (flags & 1) {
167563a7246aSmatthias.ringwald         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
167663a7246aSmatthias.ringwald     }
167763a7246aSmatthias.ringwald 
16782784b77dSmatthias.ringwald     // accept the other's configuration options
1679f8fbdce0SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
16803de7c0caSmatthias.ringwald     uint16_t pos     = 8;
16813de7c0caSmatthias.ringwald     while (pos < end_pos){
168263a7246aSmatthias.ringwald         uint8_t option_hint = command[pos] >> 7;
168363a7246aSmatthias.ringwald         uint8_t option_type = command[pos] & 0x7f;
168463a7246aSmatthias.ringwald         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
168563a7246aSmatthias.ringwald         pos++;
16861dc511deSmatthias.ringwald         uint8_t length = command[pos++];
16871dc511deSmatthias.ringwald         // MTU { type(8): 1, len(8):2, MTU(16) }
168863a7246aSmatthias.ringwald         if (option_type == 1 && length == 2){
1689f8fbdce0SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, pos);
16909d139fbaSMatthias Ringwald             if (channel->remote_mtu > l2cap_max_mtu()){
16919d139fbaSMatthias Ringwald                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
16929d139fbaSMatthias Ringwald                 channel->remote_mtu = l2cap_max_mtu();
16939d139fbaSMatthias Ringwald             }
169463a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
169563a7246aSmatthias.ringwald         }
16960fe7a9d0S[email protected]         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
16970fe7a9d0S[email protected]         if (option_type == 2 && length == 2){
1698f8fbdce0SMatthias Ringwald             channel->flush_timeout = little_endian_read_16(command, pos);
16990fe7a9d0S[email protected]         }
1700f2fa388dSMatthias Ringwald 
17016dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
17026dca2a0cSMatthias Ringwald         // Retransmission and Flow Control Option
17036dca2a0cSMatthias Ringwald         if (option_type == 4 && length == 9){
17043232a1c6SMatthias Ringwald             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
1705ac8f1300SMatthias Ringwald             switch(channel->mode){
1706ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
170725cd60d3SMatthias Ringwald                     // Store remote config
1708bbc0a9e7SMatthias Ringwald                     channel->remote_tx_window_size = command[pos+1];
1709bbc0a9e7SMatthias Ringwald                     channel->remote_max_transmit   = command[pos+2];
1710bbc0a9e7SMatthias Ringwald                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
1711bbc0a9e7SMatthias Ringwald                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
1712bbc0a9e7SMatthias Ringwald                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u",
1713bbc0a9e7SMatthias Ringwald                         channel->remote_tx_window_size,
1714bbc0a9e7SMatthias Ringwald                         channel->remote_max_transmit,
1715bbc0a9e7SMatthias Ringwald                         channel->remote_retransmission_timeout_ms,
1716bbc0a9e7SMatthias Ringwald                         channel->remote_monitor_timeout_ms);
1717bbc0a9e7SMatthias Ringwald                     // we store remote MPS in remote_mtu, might need to get re-evaluated
1718bbc0a9e7SMatthias Ringwald                     channel->remote_mtu = little_endian_read_16(command, pos + 7);
171925cd60d3SMatthias Ringwald                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
172025cd60d3SMatthias Ringwald                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
172125cd60d3SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1722ac8f1300SMatthias Ringwald                     } else {
1723ac8f1300SMatthias Ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1724ac8f1300SMatthias Ringwald                     }
1725ac8f1300SMatthias Ringwald                     break;
1726ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
1727ac8f1300SMatthias Ringwald                     switch (mode){
1728ac8f1300SMatthias Ringwald                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
1729ac8f1300SMatthias Ringwald                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
1730ac8f1300SMatthias Ringwald                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
1731ac8f1300SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1732ac8f1300SMatthias Ringwald                             }
1733ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
1734ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1735ac8f1300SMatthias Ringwald                             break;
1736ac8f1300SMatthias Ringwald                         default: // case L2CAP_CHANNEL_MODE_BASIC:
1737ac8f1300SMatthias Ringwald                             // TODO store and evaluate configuration
1738ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1739ac8f1300SMatthias Ringwald                             break;
1740ac8f1300SMatthias Ringwald                     }
1741ac8f1300SMatthias Ringwald                     break;
1742ac8f1300SMatthias Ringwald                 default:
1743ac8f1300SMatthias Ringwald                     break;
1744ac8f1300SMatthias Ringwald             }
17453232a1c6SMatthias Ringwald         }
17466dca2a0cSMatthias Ringwald #endif
174763a7246aSmatthias.ringwald         // check for unknown options
174863a7246aSmatthias.ringwald         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
1749c177a91cS[email protected]             log_info("l2cap cid %u, unknown options", channel->local_cid);
175063a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
17511dc511deSmatthias.ringwald         }
17521dc511deSmatthias.ringwald         pos += length;
17531dc511deSmatthias.ringwald     }
17542784b77dSmatthias.ringwald }
17552784b77dSmatthias.ringwald 
1756f2fa388dSMatthias Ringwald static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
1757f2fa388dSMatthias Ringwald     log_info("l2cap_signaling_handle_configure_response");
17583232a1c6SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
17593232a1c6SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1760f2fa388dSMatthias Ringwald     uint16_t pos     = 10;
17613232a1c6SMatthias Ringwald     while (pos < end_pos){
17623232a1c6SMatthias Ringwald         uint8_t option_hint = command[pos] >> 7;
17633232a1c6SMatthias Ringwald         uint8_t option_type = command[pos] & 0x7f;
17643232a1c6SMatthias Ringwald         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
17653232a1c6SMatthias Ringwald         pos++;
17663232a1c6SMatthias Ringwald         uint8_t length = command[pos++];
17673232a1c6SMatthias Ringwald 
17683232a1c6SMatthias Ringwald         // Retransmission and Flow Control Option
17693232a1c6SMatthias Ringwald         if (option_type == 4 && length == 9){
1770ac8f1300SMatthias Ringwald             switch (channel->mode){
1771ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
1772f2fa388dSMatthias Ringwald                     if (channel->ertm_mandatory){
1773ac8f1300SMatthias Ringwald                         // ??
1774f2fa388dSMatthias Ringwald                     } else {
1775ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
1776ac8f1300SMatthias Ringwald                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
1777f2fa388dSMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
17783232a1c6SMatthias Ringwald                         }
17793232a1c6SMatthias Ringwald                     }
1780ac8f1300SMatthias Ringwald                     break;
1781ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
1782ac8f1300SMatthias Ringwald                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
1783ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
1784ac8f1300SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1785ac8f1300SMatthias Ringwald                     }
1786ac8f1300SMatthias Ringwald                     break;
1787ac8f1300SMatthias Ringwald                 default:
1788ac8f1300SMatthias Ringwald                     break;
17893232a1c6SMatthias Ringwald             }
1790f2fa388dSMatthias Ringwald         }
17913232a1c6SMatthias Ringwald 
17923232a1c6SMatthias Ringwald         // check for unknown options
17933232a1c6SMatthias Ringwald         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
17943232a1c6SMatthias Ringwald             log_info("l2cap cid %u, unknown options", channel->local_cid);
17953232a1c6SMatthias Ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
17963232a1c6SMatthias Ringwald         }
17973232a1c6SMatthias Ringwald 
17983232a1c6SMatthias Ringwald         pos += length;
17993232a1c6SMatthias Ringwald     }
18003232a1c6SMatthias Ringwald #endif
18013232a1c6SMatthias Ringwald }
18023232a1c6SMatthias Ringwald 
1803fa8473a4Smatthias.ringwald static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
18049da54300S[email protected]     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
180573cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
180673cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
1807019f9b43SMatthias Ringwald     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
1808019f9b43SMatthias Ringwald     if (channel->state == L2CAP_STATE_OPEN) return 0;
1809fa8473a4Smatthias.ringwald     return 1;
1810fa8473a4Smatthias.ringwald }
1811fa8473a4Smatthias.ringwald 
1812fa8473a4Smatthias.ringwald 
18137f02f414SMatthias Ringwald static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
18141e6aba47Smatthias.ringwald 
181500d93d79Smatthias.ringwald     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
181600d93d79Smatthias.ringwald     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
181738e5900eSmatthias.ringwald     uint16_t result = 0;
18181e6aba47Smatthias.ringwald 
18199da54300S[email protected]     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
1820b35f641cSmatthias.ringwald 
18219a011532Smatthias.ringwald     // handle DISCONNECT REQUESTS seperately
18229a011532Smatthias.ringwald     if (code == DISCONNECTION_REQUEST){
18239a011532Smatthias.ringwald         switch (channel->state){
1824fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
18259a011532Smatthias.ringwald             case L2CAP_STATE_OPEN:
18262b83fb7dSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
18279a011532Smatthias.ringwald             case L2CAP_STATE_WAIT_DISCONNECT:
18289a011532Smatthias.ringwald                 l2cap_handle_disconnect_request(channel, identifier);
18299a011532Smatthias.ringwald                 break;
18309a011532Smatthias.ringwald 
18319a011532Smatthias.ringwald             default:
18329a011532Smatthias.ringwald                 // ignore in other states
18339a011532Smatthias.ringwald                 break;
18349a011532Smatthias.ringwald         }
18359a011532Smatthias.ringwald         return;
18369a011532Smatthias.ringwald     }
18379a011532Smatthias.ringwald 
183856081214Smatthias.ringwald     // @STATEMACHINE(l2cap)
18391e6aba47Smatthias.ringwald     switch (channel->state) {
18401e6aba47Smatthias.ringwald 
18411e6aba47Smatthias.ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
18421e6aba47Smatthias.ringwald             switch (code){
18431e6aba47Smatthias.ringwald                 case CONNECTION_RESPONSE:
18445932bd7cS[email protected]                     l2cap_stop_rtx(channel);
1845f8fbdce0SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
184638e5900eSmatthias.ringwald                     switch (result) {
184738e5900eSmatthias.ringwald                         case 0:
1848169f8b28Smatthias.ringwald                             // successful connection
1849f8fbdce0SMatthias Ringwald                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1850fa8473a4Smatthias.ringwald                             channel->state = L2CAP_STATE_CONFIG;
185128ca2b46S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
185238e5900eSmatthias.ringwald                             break;
185338e5900eSmatthias.ringwald                         case 1:
18545932bd7cS[email protected]                             // connection pending. get some coffee, but start the ERTX
18555932bd7cS[email protected]                             l2cap_start_ertx(channel);
185638e5900eSmatthias.ringwald                             break;
185738e5900eSmatthias.ringwald                         default:
1858eb920dbeSmatthias.ringwald                             // channel closed
1859eb920dbeSmatthias.ringwald                             channel->state = L2CAP_STATE_CLOSED;
1860f32b992eSmatthias.ringwald                             // map l2cap connection response result to BTstack status enumeration
186138e5900eSmatthias.ringwald                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
1862eb920dbeSmatthias.ringwald 
1863eb920dbeSmatthias.ringwald                             // drop link key if security block
1864eb920dbeSmatthias.ringwald                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
186515a95bd5SMatthias Ringwald                                 gap_drop_link_key_for_bd_addr(channel->address);
1866eb920dbeSmatthias.ringwald                             }
1867eb920dbeSmatthias.ringwald 
1868eb920dbeSmatthias.ringwald                             // discard channel
1869665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1870d3a9df87Smatthias.ringwald                             btstack_memory_l2cap_channel_free(channel);
187138e5900eSmatthias.ringwald                             break;
18721e6aba47Smatthias.ringwald                     }
18731e6aba47Smatthias.ringwald                     break;
187438e5900eSmatthias.ringwald 
187538e5900eSmatthias.ringwald                 default:
18761e6aba47Smatthias.ringwald                     //@TODO: implement other signaling packets
187738e5900eSmatthias.ringwald                     break;
18781e6aba47Smatthias.ringwald             }
18791e6aba47Smatthias.ringwald             break;
18801e6aba47Smatthias.ringwald 
1881fa8473a4Smatthias.ringwald         case L2CAP_STATE_CONFIG:
1882f8fbdce0SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1883ae280e73Smatthias.ringwald             switch (code) {
1884ae280e73Smatthias.ringwald                 case CONFIGURE_REQUEST:
188528ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1886ae280e73Smatthias.ringwald                     l2cap_signaling_handle_configure_request(channel, command);
188763a7246aSmatthias.ringwald                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
188863a7246aSmatthias.ringwald                         // only done if continuation not set
188963a7246aSmatthias.ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
189063a7246aSmatthias.ringwald                     }
1891ae280e73Smatthias.ringwald                     break;
18921e6aba47Smatthias.ringwald                 case CONFIGURE_RESPONSE:
18935932bd7cS[email protected]                     l2cap_stop_rtx(channel);
1894f2fa388dSMatthias Ringwald                     l2cap_signaling_handle_configure_response(channel, result, command);
18955932bd7cS[email protected]                     switch (result){
18965932bd7cS[email protected]                         case 0: // success
18975932bd7cS[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
18985932bd7cS[email protected]                             break;
18995932bd7cS[email protected]                         case 4: // pending
19005932bd7cS[email protected]                             l2cap_start_ertx(channel);
19015932bd7cS[email protected]                             break;
19025932bd7cS[email protected]                         default:
1903a32d6a03SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1904a32d6a03SMatthias Ringwald                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
1905a32d6a03SMatthias Ringwald                                 // remote does not offer ertm but it's required
1906a32d6a03SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1907a32d6a03SMatthias Ringwald                                 break;
1908a32d6a03SMatthias Ringwald                             }
1909a32d6a03SMatthias Ringwald #endif
1910fe9d8984S[email protected]                             // retry on negative result
1911fe9d8984S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1912fe9d8984S[email protected]                             break;
1913fe9d8984S[email protected]                     }
19145a67bd4aSmatthias.ringwald                     break;
19155a67bd4aSmatthias.ringwald                 default:
19165a67bd4aSmatthias.ringwald                     break;
19171e6aba47Smatthias.ringwald             }
1918fa8473a4Smatthias.ringwald             if (l2cap_channel_ready_for_open(channel)){
1919fa8473a4Smatthias.ringwald                 // for open:
19205a67bd4aSmatthias.ringwald                 channel->state = L2CAP_STATE_OPEN;
1921fa8473a4Smatthias.ringwald                 l2cap_emit_channel_opened(channel, 0);
1922c8e4258aSmatthias.ringwald             }
1923c8e4258aSmatthias.ringwald             break;
1924f62db1e3Smatthias.ringwald 
1925f62db1e3Smatthias.ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
1926f62db1e3Smatthias.ringwald             switch (code) {
1927f62db1e3Smatthias.ringwald                 case DISCONNECTION_RESPONSE:
192827a923d0Smatthias.ringwald                     l2cap_finialize_channel_close(channel);
192927a923d0Smatthias.ringwald                     break;
19305a67bd4aSmatthias.ringwald                 default:
19315a67bd4aSmatthias.ringwald                     //@TODO: implement other signaling packets
19325a67bd4aSmatthias.ringwald                     break;
193327a923d0Smatthias.ringwald             }
193427a923d0Smatthias.ringwald             break;
193584836b65Smatthias.ringwald 
193684836b65Smatthias.ringwald         case L2CAP_STATE_CLOSED:
193784836b65Smatthias.ringwald             // @TODO handle incoming requests
193884836b65Smatthias.ringwald             break;
193984836b65Smatthias.ringwald 
194084836b65Smatthias.ringwald         case L2CAP_STATE_OPEN:
194184836b65Smatthias.ringwald             //@TODO: implement other signaling packets, e.g. re-configure
194284836b65Smatthias.ringwald             break;
194310642e45Smatthias.ringwald         default:
194410642e45Smatthias.ringwald             break;
194527a923d0Smatthias.ringwald     }
19469da54300S[email protected]     // log_info("new state %u", channel->state);
194727a923d0Smatthias.ringwald }
194827a923d0Smatthias.ringwald 
194900d93d79Smatthias.ringwald 
19507f02f414SMatthias Ringwald static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
195100d93d79Smatthias.ringwald 
19521b9cb13dSMatthias Ringwald     btstack_linked_list_iterator_t it;
19531b9cb13dSMatthias Ringwald 
195400d93d79Smatthias.ringwald     // get code, signalind identifier and command len
195500d93d79Smatthias.ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
195600d93d79Smatthias.ringwald     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
195700d93d79Smatthias.ringwald 
19581b9cb13dSMatthias Ringwald     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
19591b9cb13dSMatthias Ringwald     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_RESPONSE){
1960e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
196100d93d79Smatthias.ringwald         return;
196200d93d79Smatthias.ringwald     }
196300d93d79Smatthias.ringwald 
196400d93d79Smatthias.ringwald     // general commands without an assigned channel
196500d93d79Smatthias.ringwald     switch(code) {
196600d93d79Smatthias.ringwald 
196700d93d79Smatthias.ringwald         case CONNECTION_REQUEST: {
1968f8fbdce0SMatthias Ringwald             uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1969f8fbdce0SMatthias Ringwald             uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
197000d93d79Smatthias.ringwald             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
19712b83fb7dSmatthias.ringwald             return;
197200d93d79Smatthias.ringwald         }
197300d93d79Smatthias.ringwald 
19742b360848Smatthias.ringwald         case ECHO_REQUEST:
1975e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
19762b83fb7dSmatthias.ringwald             return;
197700d93d79Smatthias.ringwald 
197800d93d79Smatthias.ringwald         case INFORMATION_REQUEST: {
1979f8fbdce0SMatthias Ringwald             uint16_t infoType = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1980e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, infoType);
19812b83fb7dSmatthias.ringwald             return;
198200d93d79Smatthias.ringwald         }
198300d93d79Smatthias.ringwald 
19841b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
19851b9cb13dSMatthias Ringwald         case INFORMATION_RESPONSE: {
19861b9cb13dSMatthias Ringwald             hci_connection_t * connection = hci_connection_for_handle(handle);
19871b9cb13dSMatthias Ringwald             if (!connection) return;
19881b9cb13dSMatthias Ringwald             uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
19891b9cb13dSMatthias Ringwald             uint16_t result =  little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
19901b9cb13dSMatthias Ringwald             if (result != 0) return;
1991543b84e4SMatthias Ringwald             if (info_type != 0x02) return;
19921b9cb13dSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
19931b9cb13dSMatthias Ringwald             connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1994543b84e4SMatthias Ringwald             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
19951b9cb13dSMatthias Ringwald             // trigger connection request
19961b9cb13dSMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
19971b9cb13dSMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
19981b9cb13dSMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1999543b84e4SMatthias Ringwald                 if (channel->con_handle != handle) continue;
2000543b84e4SMatthias Ringwald                 // bail if ERTM was requested but is not supported
2001543b84e4SMatthias Ringwald                 if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2002f073f086SMatthias Ringwald                     if (channel->ertm_mandatory){
2003543b84e4SMatthias Ringwald                         // channel closed
2004543b84e4SMatthias Ringwald                         channel->state = L2CAP_STATE_CLOSED;
2005543b84e4SMatthias Ringwald                         // map l2cap connection response result to BTstack status enumeration
2006543b84e4SMatthias Ringwald                         l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTD);
2007543b84e4SMatthias Ringwald                         // discard channel
2008543b84e4SMatthias Ringwald                         btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2009543b84e4SMatthias Ringwald                         btstack_memory_l2cap_channel_free(channel);
2010543b84e4SMatthias Ringwald                         continue;
2011f073f086SMatthias Ringwald                     } else {
2012f073f086SMatthias Ringwald                         // fallback to Basic mode
2013f073f086SMatthias Ringwald                         channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2014f073f086SMatthias Ringwald                     }
2015543b84e4SMatthias Ringwald                 }
2016543b84e4SMatthias Ringwald                 // start connecting
20171b9cb13dSMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
20181b9cb13dSMatthias Ringwald                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
20191b9cb13dSMatthias Ringwald                 }
202052606043SMatthias Ringwald                 // respond to connection request
202152606043SMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
202252606043SMatthias Ringwald                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
202352606043SMatthias Ringwald                     l2cap_emit_incoming_connection(channel);
202452606043SMatthias Ringwald                 }
20251b9cb13dSMatthias Ringwald             }
20261b9cb13dSMatthias Ringwald             return;
20271b9cb13dSMatthias Ringwald         }
20281b9cb13dSMatthias Ringwald #endif
20291b9cb13dSMatthias Ringwald 
203000d93d79Smatthias.ringwald         default:
203100d93d79Smatthias.ringwald             break;
203200d93d79Smatthias.ringwald     }
203300d93d79Smatthias.ringwald 
203400d93d79Smatthias.ringwald 
203500d93d79Smatthias.ringwald     // Get potential destination CID
2036f8fbdce0SMatthias Ringwald     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
203700d93d79Smatthias.ringwald 
203800d93d79Smatthias.ringwald     // Find channel for this sig_id and connection handle
2039665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2040665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2041665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2042fc64f94aSMatthias Ringwald         if (channel->con_handle != handle) continue;
204300d93d79Smatthias.ringwald         if (code & 1) {
2044b1988dceSmatthias.ringwald             // match odd commands (responses) by previous signaling identifier
2045b1988dceSmatthias.ringwald             if (channel->local_sig_id == sig_id) {
204600d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
20474e32727eSmatthias.ringwald                 break;
204800d93d79Smatthias.ringwald             }
204900d93d79Smatthias.ringwald         } else {
2050b1988dceSmatthias.ringwald             // match even commands (requests) by local channel id
205100d93d79Smatthias.ringwald             if (channel->local_cid == dest_cid) {
205200d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
20534e32727eSmatthias.ringwald                 break;
205400d93d79Smatthias.ringwald             }
205500d93d79Smatthias.ringwald         }
205600d93d79Smatthias.ringwald     }
205700d93d79Smatthias.ringwald }
205809e9d05bSMatthias Ringwald #endif
205900d93d79Smatthias.ringwald 
2060e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
206109e9d05bSMatthias Ringwald 
206209e9d05bSMatthias Ringwald static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
206309e9d05bSMatthias Ringwald     uint8_t event[6];
206409e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
206509e9d05bSMatthias Ringwald     event[1] = 4;
206609e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
206709e9d05bSMatthias Ringwald     little_endian_store_16(event, 4, result);
206809e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
206909e9d05bSMatthias Ringwald     if (!l2cap_event_packet_handler) return;
207009e9d05bSMatthias Ringwald     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
207109e9d05bSMatthias Ringwald }
207209e9d05bSMatthias Ringwald 
2073c48b2a2cSMatthias Ringwald // @returns valid
2074c48b2a2cSMatthias Ringwald static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
2075e7d0c9aaSMatthias Ringwald     hci_connection_t * connection;
2076c48b2a2cSMatthias Ringwald     uint16_t result;
2077c48b2a2cSMatthias Ringwald     uint8_t  event[10];
207883fd9c76SMatthias Ringwald 
2079cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2080a3dc965aSMatthias Ringwald     btstack_linked_list_iterator_t it;
2081a3dc965aSMatthias Ringwald     l2cap_channel_t * channel;
2082a3dc965aSMatthias Ringwald     uint16_t local_cid;
208383fd9c76SMatthias Ringwald     uint16_t le_psm;
208463f0ac45SMatthias Ringwald     uint16_t new_credits;
208563f0ac45SMatthias Ringwald     uint16_t credits_before;
2086e7d0c9aaSMatthias Ringwald     l2cap_service_t * service;
208711cae19eSMilanka Ringwald     uint16_t source_cid;
208883fd9c76SMatthias Ringwald #endif
208900d93d79Smatthias.ringwald 
20901b8b8d05SMatthias Ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
209123017473SMatthias Ringwald     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u", code, sig_id);
20921b8b8d05SMatthias Ringwald 
20931b8b8d05SMatthias Ringwald     switch (code){
209400d93d79Smatthias.ringwald 
2095c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
2096c48b2a2cSMatthias Ringwald             result = little_endian_read_16(command, 4);
2097ccf076adS[email protected]             l2cap_emit_connection_parameter_update_response(handle, result);
2098ccf076adS[email protected]             break;
2099da886c03S[email protected] 
2100c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_REQUEST:
2101e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
2102da886c03S[email protected]             if (connection){
21036d91fb6cSMatthias Ringwald                 if (connection->role != HCI_ROLE_MASTER){
21046d91fb6cSMatthias Ringwald                     // reject command without notifying upper layer when not in master role
2105c48b2a2cSMatthias Ringwald                     return 0;
21066d91fb6cSMatthias Ringwald                 }
2107da886c03S[email protected]                 int update_parameter = 1;
2108a4c06b28SMatthias Ringwald                 le_connection_parameter_range_t existing_range;
21094ced4e8cSMatthias Ringwald                 gap_get_connection_parameter_range(&existing_range);
2110c48b2a2cSMatthias Ringwald                 uint16_t le_conn_interval_min = little_endian_read_16(command,8);
2111c48b2a2cSMatthias Ringwald                 uint16_t le_conn_interval_max = little_endian_read_16(command,10);
2112c48b2a2cSMatthias Ringwald                 uint16_t le_conn_latency = little_endian_read_16(command,12);
2113c48b2a2cSMatthias Ringwald                 uint16_t le_supervision_timeout = little_endian_read_16(command,14);
2114da886c03S[email protected] 
2115da886c03S[email protected]                 if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
2116da886c03S[email protected]                 if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
2117da886c03S[email protected] 
2118da886c03S[email protected]                 if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
2119da886c03S[email protected]                 if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
2120da886c03S[email protected] 
2121da886c03S[email protected]                 if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
2122da886c03S[email protected]                 if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
2123da886c03S[email protected] 
2124da886c03S[email protected]                 if (update_parameter){
2125da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
2126da886c03S[email protected]                     connection->le_conn_interval_min = le_conn_interval_min;
2127da886c03S[email protected]                     connection->le_conn_interval_max = le_conn_interval_max;
2128da886c03S[email protected]                     connection->le_conn_latency = le_conn_latency;
2129da886c03S[email protected]                     connection->le_supervision_timeout = le_supervision_timeout;
2130da886c03S[email protected]                 } else {
2131da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
2132da886c03S[email protected]                 }
2133c48b2a2cSMatthias Ringwald                 connection->le_con_param_update_identifier = sig_id;
2134da886c03S[email protected]             }
2135da886c03S[email protected] 
213633c40538SMatthias Ringwald             if (!l2cap_event_packet_handler) break;
2137c48b2a2cSMatthias Ringwald 
2138c48b2a2cSMatthias Ringwald             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
2139c48b2a2cSMatthias Ringwald             event[1] = 8;
2140c48b2a2cSMatthias Ringwald             memcpy(&event[2], &command[4], 8);
2141c48b2a2cSMatthias Ringwald             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
214233c40538SMatthias Ringwald             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
2143ccf076adS[email protected]             break;
2144c48b2a2cSMatthias Ringwald 
2145a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2146a3dc965aSMatthias Ringwald 
214763f0ac45SMatthias Ringwald         case COMMAND_REJECT:
214863f0ac45SMatthias Ringwald             // Find channel for this sig_id and connection handle
214963f0ac45SMatthias Ringwald             channel = NULL;
215063f0ac45SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
215163f0ac45SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
215263f0ac45SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
215363f0ac45SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
215463f0ac45SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
215563f0ac45SMatthias Ringwald                 channel = a_channel;
215663f0ac45SMatthias Ringwald                 break;
215763f0ac45SMatthias Ringwald             }
215863f0ac45SMatthias Ringwald             if (!channel) break;
215963f0ac45SMatthias Ringwald 
216063f0ac45SMatthias Ringwald             // if received while waiting for le connection response, assume legacy device
216163f0ac45SMatthias Ringwald             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
216263f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
216363f0ac45SMatthias Ringwald                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
216444276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0x0002);
216563f0ac45SMatthias Ringwald 
216663f0ac45SMatthias Ringwald                 // discard channel
216763f0ac45SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
216863f0ac45SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
216963f0ac45SMatthias Ringwald                 break;
217063f0ac45SMatthias Ringwald             }
217163f0ac45SMatthias Ringwald             break;
217263f0ac45SMatthias Ringwald 
2173e7d0c9aaSMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_REQUEST:
2174e7d0c9aaSMatthias Ringwald 
2175e7d0c9aaSMatthias Ringwald             // get hci connection, bail if not found (must not happen)
2176e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
2177e7d0c9aaSMatthias Ringwald             if (!connection) return 0;
2178e7d0c9aaSMatthias Ringwald 
2179e7d0c9aaSMatthias Ringwald             // check if service registered
2180e7d0c9aaSMatthias Ringwald             le_psm  = little_endian_read_16(command, 4);
2181e7d0c9aaSMatthias Ringwald             service = l2cap_le_get_service(le_psm);
218211cae19eSMilanka Ringwald             source_cid = little_endian_read_16(command, 6);
2183e7d0c9aaSMatthias Ringwald 
2184e7d0c9aaSMatthias Ringwald             if (service){
2185e7d0c9aaSMatthias Ringwald                 if (source_cid < 0x40){
2186e7d0c9aaSMatthias Ringwald                     // 0x0009 Connection refused - Invalid Source CID
2187e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
2188e7d0c9aaSMatthias Ringwald                     return 1;
2189e7d0c9aaSMatthias Ringwald                 }
2190e7d0c9aaSMatthias Ringwald 
2191e7d0c9aaSMatthias Ringwald                 // go through list of channels for this ACL connection and check if we get a match
2192e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2193e7d0c9aaSMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&it)){
21941b8b8d05SMatthias Ringwald                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
21951b8b8d05SMatthias Ringwald                     if (a_channel->con_handle != handle) continue;
21961b8b8d05SMatthias Ringwald                     if (a_channel->remote_cid != source_cid) continue;
2197e7d0c9aaSMatthias Ringwald                     // 0x000a Connection refused - Source CID already allocated
2198e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
2199e7d0c9aaSMatthias Ringwald                     return 1;
2200e7d0c9aaSMatthias Ringwald                 }
2201e7d0c9aaSMatthias Ringwald 
220283fd9c76SMatthias Ringwald                 // security: check encryption
220383fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_2){
220483fd9c76SMatthias Ringwald                     if (sm_encryption_key_size(handle) == 0){
220583fd9c76SMatthias Ringwald                         // 0x0008 Connection refused - insufficient encryption
2206e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
220783fd9c76SMatthias Ringwald                         return 1;
220883fd9c76SMatthias Ringwald                     }
220983fd9c76SMatthias Ringwald                     // anything less than 16 byte key size is insufficient
221083fd9c76SMatthias Ringwald                     if (sm_encryption_key_size(handle) < 16){
221183fd9c76SMatthias Ringwald                         // 0x0007 Connection refused – insufficient encryption key size
2212e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
221383fd9c76SMatthias Ringwald                         return 1;
221483fd9c76SMatthias Ringwald                     }
221583fd9c76SMatthias Ringwald                 }
221683fd9c76SMatthias Ringwald 
221783fd9c76SMatthias Ringwald                 // security: check authencation
221883fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_3){
221983fd9c76SMatthias Ringwald                     if (!sm_authenticated(handle)){
222083fd9c76SMatthias Ringwald                         // 0x0005 Connection refused – insufficient authentication
2221e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
222283fd9c76SMatthias Ringwald                         return 1;
222383fd9c76SMatthias Ringwald                     }
222483fd9c76SMatthias Ringwald                 }
222583fd9c76SMatthias Ringwald 
222683fd9c76SMatthias Ringwald                 // security: check authorization
222783fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_4){
222883fd9c76SMatthias Ringwald                     if (sm_authorization_state(handle) != AUTHORIZATION_GRANTED){
222983fd9c76SMatthias Ringwald                         // 0x0006 Connection refused – insufficient authorization
2230e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
223183fd9c76SMatthias Ringwald                         return 1;
223283fd9c76SMatthias Ringwald                     }
223383fd9c76SMatthias Ringwald                 }
2234e7d0c9aaSMatthias Ringwald 
2235e7d0c9aaSMatthias Ringwald                 // allocate channel
22361b8b8d05SMatthias Ringwald                 channel = l2cap_create_channel_entry(service->packet_handler, connection->address,
2237e7d0c9aaSMatthias Ringwald                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
2238e7d0c9aaSMatthias Ringwald                 if (!channel){
2239e7d0c9aaSMatthias Ringwald                     // 0x0004 Connection refused – no resources available
2240e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2241e7d0c9aaSMatthias Ringwald                     return 1;
2242e7d0c9aaSMatthias Ringwald                 }
2243e7d0c9aaSMatthias Ringwald 
2244e7d0c9aaSMatthias Ringwald                 channel->con_handle = handle;
2245e7d0c9aaSMatthias Ringwald                 channel->remote_cid = source_cid;
2246e7d0c9aaSMatthias Ringwald                 channel->remote_sig_id = sig_id;
22477f107edaSMatthias Ringwald                 channel->remote_mtu = little_endian_read_16(command, 8);
22487f107edaSMatthias Ringwald                 channel->remote_mps = little_endian_read_16(command, 10);
22497f107edaSMatthias Ringwald                 channel->credits_outgoing = little_endian_read_16(command, 12);
2250e7d0c9aaSMatthias Ringwald 
2251e7d0c9aaSMatthias Ringwald                 // set initial state
2252e7d0c9aaSMatthias Ringwald                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2253c99bb618SMatthias Ringwald                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
2254e7d0c9aaSMatthias Ringwald 
2255e7d0c9aaSMatthias Ringwald                 // add to connections list
2256e7d0c9aaSMatthias Ringwald                 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2257e7d0c9aaSMatthias Ringwald 
2258e7d0c9aaSMatthias Ringwald                 // post connection request event
225944276248SMatthias Ringwald                 l2cap_emit_le_incoming_connection(channel);
2260e7d0c9aaSMatthias Ringwald 
2261e7d0c9aaSMatthias Ringwald             } else {
2262e7d0c9aaSMatthias Ringwald                 // Connection refused – LE_PSM not supported
2263e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2264e7d0c9aaSMatthias Ringwald             }
2265e7d0c9aaSMatthias Ringwald             break;
22661b8b8d05SMatthias Ringwald 
22671b8b8d05SMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
22681b8b8d05SMatthias Ringwald             // Find channel for this sig_id and connection handle
22691b8b8d05SMatthias Ringwald             channel = NULL;
22701b8b8d05SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
22711b8b8d05SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
22721b8b8d05SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
22731b8b8d05SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
22741b8b8d05SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
22751b8b8d05SMatthias Ringwald                 channel = a_channel;
22761b8b8d05SMatthias Ringwald                 break;
22771b8b8d05SMatthias Ringwald             }
22781b8b8d05SMatthias Ringwald             if (!channel) break;
22791b8b8d05SMatthias Ringwald 
22801b8b8d05SMatthias Ringwald             // cid + 0
22811b8b8d05SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
22821b8b8d05SMatthias Ringwald             if (result){
22831b8b8d05SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
22841b8b8d05SMatthias Ringwald                 // map l2cap connection response result to BTstack status enumeration
228544276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, result);
22861b8b8d05SMatthias Ringwald 
22871b8b8d05SMatthias Ringwald                 // discard channel
228863f0ac45SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
22891b8b8d05SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
22901b8b8d05SMatthias Ringwald                 break;
22911b8b8d05SMatthias Ringwald             }
22921b8b8d05SMatthias Ringwald 
22931b8b8d05SMatthias Ringwald             // success
22941b8b8d05SMatthias Ringwald             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
22951b8b8d05SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
22961b8b8d05SMatthias Ringwald             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
22971b8b8d05SMatthias Ringwald             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
22981b8b8d05SMatthias Ringwald             channel->state = L2CAP_STATE_OPEN;
229944276248SMatthias Ringwald             l2cap_emit_le_channel_opened(channel, result);
23001b8b8d05SMatthias Ringwald             break;
23011b8b8d05SMatthias Ringwald 
230285aeef60SMatthias Ringwald         case LE_FLOW_CONTROL_CREDIT:
230385aeef60SMatthias Ringwald             // find channel
230485aeef60SMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
230585aeef60SMatthias Ringwald             channel = l2cap_le_get_channel_for_local_cid(local_cid);
230663f0ac45SMatthias Ringwald             if (!channel) {
230763f0ac45SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
230863f0ac45SMatthias Ringwald                 break;
230963f0ac45SMatthias Ringwald             }
231063f0ac45SMatthias Ringwald             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
231163f0ac45SMatthias Ringwald             credits_before = channel->credits_outgoing;
231263f0ac45SMatthias Ringwald             channel->credits_outgoing += new_credits;
231363f0ac45SMatthias Ringwald             // check for credit overrun
231463f0ac45SMatthias Ringwald             if (credits_before > channel->credits_outgoing){
231563f0ac45SMatthias Ringwald                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
231663f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
231763f0ac45SMatthias Ringwald                 break;
231863f0ac45SMatthias Ringwald             }
231963f0ac45SMatthias Ringwald             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
232085aeef60SMatthias Ringwald             break;
232185aeef60SMatthias Ringwald 
2322828a7f7aSMatthias Ringwald         case DISCONNECTION_REQUEST:
2323828a7f7aSMatthias Ringwald             // find channel
2324828a7f7aSMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
2325828a7f7aSMatthias Ringwald             channel = l2cap_le_get_channel_for_local_cid(local_cid);
232663f34e00SMatthias Ringwald             if (!channel) {
232763f34e00SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
232863f34e00SMatthias Ringwald                 break;
232963f34e00SMatthias Ringwald             }
2330828a7f7aSMatthias Ringwald             channel->remote_sig_id = sig_id;
2331828a7f7aSMatthias Ringwald             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
2332828a7f7aSMatthias Ringwald             break;
2333828a7f7aSMatthias Ringwald 
2334a3dc965aSMatthias Ringwald #endif
2335a3dc965aSMatthias Ringwald 
233663f0ac45SMatthias Ringwald         case DISCONNECTION_RESPONSE:
233763f0ac45SMatthias Ringwald             break;
233863f0ac45SMatthias Ringwald 
2339c48b2a2cSMatthias Ringwald         default:
2340c48b2a2cSMatthias Ringwald             // command unknown -> reject command
2341c48b2a2cSMatthias Ringwald             return 0;
2342ccf076adS[email protected]     }
2343c48b2a2cSMatthias Ringwald     return 1;
2344c48b2a2cSMatthias Ringwald }
2345e7d0c9aaSMatthias Ringwald #endif
2346c48b2a2cSMatthias Ringwald 
2347c48b2a2cSMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size ){
23489ec2630cSMatthias Ringwald     UNUSED(packet_type);
23499ec2630cSMatthias Ringwald     UNUSED(channel);
2350c48b2a2cSMatthias Ringwald 
235109e9d05bSMatthias Ringwald     l2cap_channel_t * l2cap_channel;
2352f3963406SMatthias Ringwald     UNUSED(l2cap_channel);
235309e9d05bSMatthias Ringwald 
2354c48b2a2cSMatthias Ringwald     // Get Channel ID
2355c48b2a2cSMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
2356c48b2a2cSMatthias Ringwald     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
2357c48b2a2cSMatthias Ringwald 
2358c48b2a2cSMatthias Ringwald     switch (channel_id) {
2359c48b2a2cSMatthias Ringwald 
236009e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2361c48b2a2cSMatthias Ringwald         case L2CAP_CID_SIGNALING: {
2362c48b2a2cSMatthias Ringwald             uint16_t command_offset = 8;
2363c48b2a2cSMatthias Ringwald             while (command_offset < size) {
2364c48b2a2cSMatthias Ringwald                 // handle signaling commands
2365c48b2a2cSMatthias Ringwald                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
2366c48b2a2cSMatthias Ringwald 
2367c48b2a2cSMatthias Ringwald                 // increment command_offset
2368c48b2a2cSMatthias Ringwald                 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2369c48b2a2cSMatthias Ringwald             }
2370c48b2a2cSMatthias Ringwald             break;
2371c48b2a2cSMatthias Ringwald         }
237209e9d05bSMatthias Ringwald #endif
2373c48b2a2cSMatthias Ringwald 
2374e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
2375e7d0c9aaSMatthias Ringwald         case L2CAP_CID_SIGNALING_LE: {
2376e7d0c9aaSMatthias Ringwald             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
2377e7d0c9aaSMatthias Ringwald             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
2378c48b2a2cSMatthias Ringwald             if (!valid){
2379e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2380ccf076adS[email protected]             }
2381ccf076adS[email protected]             break;
2382e7d0c9aaSMatthias Ringwald         }
2383e7d0c9aaSMatthias Ringwald #endif
2384c48b2a2cSMatthias Ringwald 
2385c48b2a2cSMatthias Ringwald         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
2386c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback) {
2387c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2388ccf076adS[email protected]             }
2389c48b2a2cSMatthias Ringwald             break;
2390c48b2a2cSMatthias Ringwald 
2391c48b2a2cSMatthias Ringwald         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
2392c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback) {
2393c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2394c48b2a2cSMatthias Ringwald             }
2395c48b2a2cSMatthias Ringwald             break;
2396c48b2a2cSMatthias Ringwald 
2397c48b2a2cSMatthias Ringwald         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
2398c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback) {
2399c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2400c48b2a2cSMatthias Ringwald             }
2401c48b2a2cSMatthias Ringwald             break;
24021bbc0b23S[email protected] 
240309e9d05bSMatthias Ringwald         default:
240409e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
240500d93d79Smatthias.ringwald             // Find channel for this channel_id and connection handle
240664e11ca9SMatthias Ringwald             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
2407d1fd2a88SMatthias Ringwald             if (l2cap_channel) {
240827e0774aSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
240927e0774aSMatthias Ringwald                 if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
241027e0774aSMatthias Ringwald 
241127e0774aSMatthias Ringwald                     // verify FCS
241227e0774aSMatthias Ringwald                     uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
241327e0774aSMatthias Ringwald                     uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
241427e0774aSMatthias Ringwald                     log_info("Packet FCS 0x%04x, calculated FCS 0x%04x", fcs_packet, fcs_calculated);
241527e0774aSMatthias Ringwald                     if (fcs_calculated != fcs_packet){
241627e0774aSMatthias Ringwald                         log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
241727e0774aSMatthias Ringwald                         // TODO: trigger retransmission or something like that
241827e0774aSMatthias Ringwald                         break;
241927e0774aSMatthias Ringwald                     }
242027e0774aSMatthias Ringwald 
242127e0774aSMatthias Ringwald                     // switch on packet type
242227e0774aSMatthias Ringwald                     uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
242338f62777SMatthias Ringwald                     uint8_t  req_seq = (control >> 8) & 0x3f;
242427e0774aSMatthias Ringwald                     if (control & 1){
242538f62777SMatthias Ringwald                         // int poll = (control >> 7) & 0x01;
242627e0774aSMatthias Ringwald                         log_info("S-Frame not not implemented yet");
242727e0774aSMatthias Ringwald                         // S-Frame
242827e0774aSMatthias Ringwald                         break;
242927e0774aSMatthias Ringwald                     } else {
243027e0774aSMatthias Ringwald                         // I-Frame
243127e0774aSMatthias Ringwald                         // get control
243227e0774aSMatthias Ringwald                         l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
243338f62777SMatthias Ringwald                         uint8_t tx_seq = (control >> 1) & 0x3f;
243438f62777SMatthias Ringwald                         log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
243538f62777SMatthias Ringwald                         log_info("SAR: pos %u", l2cap_channel->rx_packets_state->pos);
243638f62777SMatthias Ringwald                         log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
243738f62777SMatthias Ringwald                         // check ordering
243838f62777SMatthias Ringwald                         if (l2cap_channel->expected_tx_seq == tx_seq){
243938f62777SMatthias Ringwald                             log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
244038f62777SMatthias Ringwald                             l2cap_channel->req_seq = tx_seq;
2441*d84e866fSMatthias Ringwald                             l2cap_channel->send_supervisor_frame_receiver_ready = 1;
244238f62777SMatthias Ringwald                             l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
2443ed971c5aSMatthias Ringwald                             uint16_t sdu_length;
2444ed971c5aSMatthias Ringwald                             uint16_t segment_length;
2445ed971c5aSMatthias Ringwald                             uint16_t payload_offset;
244627e0774aSMatthias Ringwald                             switch (sar){
244727e0774aSMatthias Ringwald                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
2448ed971c5aSMatthias Ringwald                                     payload_offset = COMPLETE_L2CAP_HEADER+2;
2449ed971c5aSMatthias Ringwald                                     segment_length = payload_offset-2;
2450ed971c5aSMatthias Ringwald                                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER+2], segment_length);
245127e0774aSMatthias Ringwald                                     break;
245227e0774aSMatthias Ringwald                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
2453ed971c5aSMatthias Ringwald                                     // TODO: use current packet
2454ed971c5aSMatthias Ringwald                                     // TODO: check if reassembly started
2455ed971c5aSMatthias Ringwald                                     // TODO: check len against local mtu
2456ed971c5aSMatthias Ringwald                                     sdu_length = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER+2);
2457ed971c5aSMatthias Ringwald                                     payload_offset = COMPLETE_L2CAP_HEADER+4;
2458ed971c5aSMatthias Ringwald                                     segment_length = size - payload_offset-2;
2459ed971c5aSMatthias Ringwald                                     memcpy(&l2cap_channel->rx_packets_data[0], &packet[payload_offset], segment_length);
2460ed971c5aSMatthias Ringwald                                     l2cap_channel->rx_packets_state->sdu_length = sdu_length;
2461ed971c5aSMatthias Ringwald                                     l2cap_channel->rx_packets_state->pos = segment_length;
2462ed971c5aSMatthias Ringwald                                     break;
246327e0774aSMatthias Ringwald                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
2464ed971c5aSMatthias Ringwald                                     payload_offset = COMPLETE_L2CAP_HEADER+2;
2465ed971c5aSMatthias Ringwald                                     segment_length = size - payload_offset-2;
2466ed971c5aSMatthias Ringwald                                     memcpy(&l2cap_channel->rx_packets_data[l2cap_channel->rx_packets_state->pos], &packet[payload_offset], segment_length);
2467ed971c5aSMatthias Ringwald                                     l2cap_channel->rx_packets_state->pos += segment_length;
2468ed971c5aSMatthias Ringwald                                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->rx_packets_data, l2cap_channel->rx_packets_state[0].pos);
2469ed971c5aSMatthias Ringwald                                     break;
247027e0774aSMatthias Ringwald                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
2471ed971c5aSMatthias Ringwald                                     payload_offset = COMPLETE_L2CAP_HEADER+2;
2472ed971c5aSMatthias Ringwald                                     segment_length = size - payload_offset-2;
2473ed971c5aSMatthias Ringwald                                     memcpy(&l2cap_channel->rx_packets_data[l2cap_channel->rx_packets_state->pos], &packet[payload_offset], segment_length);
2474ed971c5aSMatthias Ringwald                                     l2cap_channel->rx_packets_state->pos += segment_length;
247527e0774aSMatthias Ringwald                                     break;
247627e0774aSMatthias Ringwald                                 }
247727e0774aSMatthias Ringwald                             }
247838f62777SMatthias Ringwald                         }
247927e0774aSMatthias Ringwald                     break;
248027e0774aSMatthias Ringwald                 }
248127e0774aSMatthias Ringwald #endif
24823d50b4baSMatthias Ringwald                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
248300d93d79Smatthias.ringwald             }
248409e9d05bSMatthias Ringwald #endif
2485a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
248664e11ca9SMatthias Ringwald             l2cap_channel = l2cap_le_get_channel_for_local_cid(channel_id);
248764e11ca9SMatthias Ringwald             if (l2cap_channel) {
248885aeef60SMatthias Ringwald                 // credit counting
248985aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming == 0){
249085aeef60SMatthias Ringwald                     log_error("LE Data Channel packet received but no incoming credits");
249185aeef60SMatthias Ringwald                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
249285aeef60SMatthias Ringwald                     break;
249385aeef60SMatthias Ringwald                 }
249485aeef60SMatthias Ringwald                 l2cap_channel->credits_incoming--;
249585aeef60SMatthias Ringwald 
249685aeef60SMatthias Ringwald                 // automatic credits
249785aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){
249885aeef60SMatthias Ringwald                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
249985aeef60SMatthias Ringwald                 }
250085aeef60SMatthias Ringwald 
2501cd529728SMatthias Ringwald                 // first fragment
2502cd529728SMatthias Ringwald                 uint16_t pos = 0;
2503cd529728SMatthias Ringwald                 if (!l2cap_channel->receive_sdu_len){
2504cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
2505cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_pos = 0;
2506cd529728SMatthias Ringwald                     pos  += 2;
2507cd529728SMatthias Ringwald                     size -= 2;
2508cd529728SMatthias Ringwald                 }
2509cd529728SMatthias Ringwald                 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], size-COMPLETE_L2CAP_HEADER);
2510cd529728SMatthias Ringwald                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
2511cd529728SMatthias Ringwald                 // done?
251263f0ac45SMatthias Ringwald                 log_info("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
2513cd529728SMatthias Ringwald                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
2514cd529728SMatthias Ringwald                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
2515cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = 0;
2516cd529728SMatthias Ringwald                 }
251763f0ac45SMatthias Ringwald             } else {
251863f0ac45SMatthias Ringwald                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
251964e11ca9SMatthias Ringwald             }
252064e11ca9SMatthias Ringwald #endif
25215652b5ffS[email protected]             break;
25225652b5ffS[email protected]     }
252300d93d79Smatthias.ringwald 
25241eb2563eS[email protected]     l2cap_run();
25252718e2e7Smatthias.ringwald }
252600d93d79Smatthias.ringwald 
252709e9d05bSMatthias Ringwald // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
252809e9d05bSMatthias Ringwald void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
252909e9d05bSMatthias Ringwald     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
253009e9d05bSMatthias Ringwald     if (index < 0) return;
253109e9d05bSMatthias Ringwald     fixed_channels[index].callback = the_packet_handler;
253209e9d05bSMatthias Ringwald }
253309e9d05bSMatthias Ringwald 
253409e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
253515ec09bbSmatthias.ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
253627a923d0Smatthias.ringwald void l2cap_finialize_channel_close(l2cap_channel_t * channel){
2537f62db1e3Smatthias.ringwald     channel->state = L2CAP_STATE_CLOSED;
2538f62db1e3Smatthias.ringwald     l2cap_emit_channel_closed(channel);
2539f62db1e3Smatthias.ringwald     // discard channel
25409dcb2fb2S[email protected]     l2cap_stop_rtx(channel);
2541665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2542d3a9df87Smatthias.ringwald     btstack_memory_l2cap_channel_free(channel);
2543c8e4258aSmatthias.ringwald }
25441e6aba47Smatthias.ringwald 
25458f2a52f4SMatthias Ringwald static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
2546665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
2547665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, services);
2548665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2549665d90f2SMatthias Ringwald         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
25509d9bbc01Smatthias.ringwald         if ( service->psm == psm){
25519d9bbc01Smatthias.ringwald             return service;
25529d9bbc01Smatthias.ringwald         };
25539d9bbc01Smatthias.ringwald     }
25549d9bbc01Smatthias.ringwald     return NULL;
25559d9bbc01Smatthias.ringwald }
25569d9bbc01Smatthias.ringwald 
25577192e786SMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
25587192e786SMatthias Ringwald     return l2cap_get_service_internal(&l2cap_services, psm);
25597192e786SMatthias Ringwald }
25607192e786SMatthias Ringwald 
2561e0abb8e7S[email protected] 
2562be2053a6SMatthias 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){
2563be2053a6SMatthias Ringwald 
2564be2053a6SMatthias Ringwald     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
2565e0abb8e7S[email protected] 
25664bb582b6Smatthias.ringwald     // check for alread registered psm
25679d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
2568277abc2cSmatthias.ringwald     if (service) {
2569be2053a6SMatthias Ringwald         log_error("l2cap_register_service: PSM %u already registered", psm);
2570be2053a6SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
2571277abc2cSmatthias.ringwald     }
25729d9bbc01Smatthias.ringwald 
25734bb582b6Smatthias.ringwald     // alloc structure
2574bb69aaaeS[email protected]     service = btstack_memory_l2cap_service_get();
2575277abc2cSmatthias.ringwald     if (!service) {
2576be2053a6SMatthias Ringwald         log_error("l2cap_register_service: no memory for l2cap_service_t");
2577be2053a6SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
2578277abc2cSmatthias.ringwald     }
25799d9bbc01Smatthias.ringwald 
25809d9bbc01Smatthias.ringwald     // fill in
25819d9bbc01Smatthias.ringwald     service->psm = psm;
25829d9bbc01Smatthias.ringwald     service->mtu = mtu;
258305ae8de3SMatthias Ringwald     service->packet_handler = service_packet_handler;
2584df3354fcS[email protected]     service->required_security_level = security_level;
25859d9bbc01Smatthias.ringwald 
25869d9bbc01Smatthias.ringwald     // add to services list
2587665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
2588c0e866bfSmatthias.ringwald 
2589c0e866bfSmatthias.ringwald     // enable page scan
259015a95bd5SMatthias Ringwald     gap_connectable_control(1);
25915842b6d9Smatthias.ringwald 
2592be2053a6SMatthias Ringwald     return 0;
25939d9bbc01Smatthias.ringwald }
25949d9bbc01Smatthias.ringwald 
25957e8856ebSMatthias Ringwald uint8_t l2cap_unregister_service(uint16_t psm){
2596e0abb8e7S[email protected] 
2597e0abb8e7S[email protected]     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
2598e0abb8e7S[email protected] 
25999d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
26007e8856ebSMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2601665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
2602d3a9df87Smatthias.ringwald     btstack_memory_l2cap_service_free(service);
2603c0e866bfSmatthias.ringwald 
2604c0e866bfSmatthias.ringwald     // disable page scan when no services registered
26057e8856ebSMatthias Ringwald     if (btstack_linked_list_empty(&l2cap_services)) {
260615a95bd5SMatthias Ringwald         gap_connectable_control(0);
26079d9bbc01Smatthias.ringwald     }
26087e8856ebSMatthias Ringwald     return 0;
26097e8856ebSMatthias Ringwald }
261009e9d05bSMatthias Ringwald #endif
26119d9bbc01Smatthias.ringwald 
26127192e786SMatthias Ringwald 
2613cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
261483fd9c76SMatthias Ringwald 
261557be49d6SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
261657be49d6SMatthias Ringwald     if (!channel->waiting_for_can_send_now) return;
261757be49d6SMatthias Ringwald     if (channel->send_sdu_buffer) return;
261857be49d6SMatthias Ringwald     channel->waiting_for_can_send_now = 0;
261957be49d6SMatthias Ringwald     log_info("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
262057be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
262157be49d6SMatthias Ringwald }
262257be49d6SMatthias Ringwald 
262357be49d6SMatthias Ringwald // 1BH2222
262457be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
262557be49d6SMatthias 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",
262657be49d6SMatthias Ringwald              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
262757be49d6SMatthias Ringwald     uint8_t event[19];
262857be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
262957be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
263057be49d6SMatthias Ringwald     event[2] = channel->address_type;
263157be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
263257be49d6SMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
263357be49d6SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
263457be49d6SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
263557be49d6SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
263657be49d6SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_mtu);
263757be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
263857be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
263957be49d6SMatthias Ringwald }
264057be49d6SMatthias Ringwald // 11BH22222
264157be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
264257be49d6SMatthias 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",
264357be49d6SMatthias Ringwald              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
264457be49d6SMatthias Ringwald              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
2645c99bb618SMatthias Ringwald     uint8_t event[23];
264657be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
264757be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
264857be49d6SMatthias Ringwald     event[2] = status;
264957be49d6SMatthias Ringwald     event[3] = channel->address_type;
265057be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[4]);
265157be49d6SMatthias Ringwald     little_endian_store_16(event, 10, channel->con_handle);
2652c99bb618SMatthias Ringwald     event[12] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
2653c99bb618SMatthias Ringwald     little_endian_store_16(event, 13, channel->psm);
2654c99bb618SMatthias Ringwald     little_endian_store_16(event, 15, channel->local_cid);
2655c99bb618SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_cid);
2656c99bb618SMatthias Ringwald     little_endian_store_16(event, 19, channel->local_mtu);
2657c99bb618SMatthias Ringwald     little_endian_store_16(event, 21, channel->remote_mtu);
265857be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
265957be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
266057be49d6SMatthias Ringwald }
266157be49d6SMatthias Ringwald 
266257be49d6SMatthias Ringwald static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid){
266357be49d6SMatthias Ringwald     btstack_linked_list_iterator_t it;
266457be49d6SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
266557be49d6SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
266657be49d6SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
266757be49d6SMatthias Ringwald         if ( channel->local_cid == local_cid) {
266857be49d6SMatthias Ringwald             return channel;
266957be49d6SMatthias Ringwald         }
267057be49d6SMatthias Ringwald     }
267157be49d6SMatthias Ringwald     return NULL;
267257be49d6SMatthias Ringwald }
267357be49d6SMatthias Ringwald 
267457be49d6SMatthias Ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
267557be49d6SMatthias Ringwald void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
267657be49d6SMatthias Ringwald     channel->state = L2CAP_STATE_CLOSED;
267757be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
267857be49d6SMatthias Ringwald     // discard channel
267957be49d6SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
268057be49d6SMatthias Ringwald     btstack_memory_l2cap_channel_free(channel);
268157be49d6SMatthias Ringwald }
268257be49d6SMatthias Ringwald 
2683e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
2684e7d0c9aaSMatthias Ringwald     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
26857192e786SMatthias Ringwald }
2686efedfb4cSMatthias Ringwald 
2687da144af5SMatthias Ringwald uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
26887192e786SMatthias Ringwald 
2689da144af5SMatthias Ringwald     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
26907192e786SMatthias Ringwald 
26917192e786SMatthias Ringwald     // check for alread registered psm
26927192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
26937192e786SMatthias Ringwald     if (service) {
2694da144af5SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
26957192e786SMatthias Ringwald     }
26967192e786SMatthias Ringwald 
26977192e786SMatthias Ringwald     // alloc structure
26987192e786SMatthias Ringwald     service = btstack_memory_l2cap_service_get();
26997192e786SMatthias Ringwald     if (!service) {
27007192e786SMatthias Ringwald         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
2701da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
27027192e786SMatthias Ringwald     }
27037192e786SMatthias Ringwald 
27047192e786SMatthias Ringwald     // fill in
27057192e786SMatthias Ringwald     service->psm = psm;
2706da144af5SMatthias Ringwald     service->mtu = 0;
27077192e786SMatthias Ringwald     service->packet_handler = packet_handler;
27087192e786SMatthias Ringwald     service->required_security_level = security_level;
27097192e786SMatthias Ringwald 
27107192e786SMatthias Ringwald     // add to services list
2711665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
27127192e786SMatthias Ringwald 
27137192e786SMatthias Ringwald     // done
2714da144af5SMatthias Ringwald     return 0;
27157192e786SMatthias Ringwald }
27167192e786SMatthias Ringwald 
2717da144af5SMatthias Ringwald uint8_t l2cap_le_unregister_service(uint16_t psm) {
27187192e786SMatthias Ringwald     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
27197192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
27209367f9b0SMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2721da144af5SMatthias Ringwald 
2722665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
27237192e786SMatthias Ringwald     btstack_memory_l2cap_service_free(service);
2724da144af5SMatthias Ringwald     return 0;
27257192e786SMatthias Ringwald }
2726da144af5SMatthias Ringwald 
2727da144af5SMatthias Ringwald uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
2728e7d0c9aaSMatthias Ringwald     // get channel
2729e7d0c9aaSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2730e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2731e7d0c9aaSMatthias Ringwald 
2732e7d0c9aaSMatthias Ringwald     // validate state
2733e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2734e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
2735e7d0c9aaSMatthias Ringwald     }
2736e7d0c9aaSMatthias Ringwald 
2737efedfb4cSMatthias Ringwald     // set state accept connection
273823017473SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
273923017473SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
274023017473SMatthias Ringwald     channel->local_mtu = mtu;
274185aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
274285aeef60SMatthias Ringwald     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
274385aeef60SMatthias Ringwald 
274485aeef60SMatthias Ringwald     // test
274563f0ac45SMatthias Ringwald     // channel->new_credits_incoming = 1;
2746e7d0c9aaSMatthias Ringwald 
2747e7d0c9aaSMatthias Ringwald     // go
2748e7d0c9aaSMatthias Ringwald     l2cap_run();
2749da144af5SMatthias Ringwald     return 0;
2750da144af5SMatthias Ringwald }
2751da144af5SMatthias Ringwald 
2752da144af5SMatthias Ringwald /**
2753da144af5SMatthias Ringwald  * @brief Deny incoming LE Data Channel connection due to resource constraints
2754da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2755da144af5SMatthias Ringwald  */
2756da144af5SMatthias Ringwald 
2757da144af5SMatthias Ringwald uint8_t l2cap_le_decline_connection(uint16_t local_cid){
2758e7d0c9aaSMatthias Ringwald     // get channel
2759e7d0c9aaSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2760e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2761e7d0c9aaSMatthias Ringwald 
2762e7d0c9aaSMatthias Ringwald     // validate state
2763e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2764e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
2765e7d0c9aaSMatthias Ringwald     }
2766e7d0c9aaSMatthias Ringwald 
2767efedfb4cSMatthias Ringwald     // set state decline connection
2768e7d0c9aaSMatthias Ringwald     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
2769e7d0c9aaSMatthias Ringwald     channel->reason = 0x04; // no resources available
2770e7d0c9aaSMatthias Ringwald     l2cap_run();
2771da144af5SMatthias Ringwald     return 0;
2772da144af5SMatthias Ringwald }
2773da144af5SMatthias Ringwald 
27747dafa750SMatthias Ringwald uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
2775da144af5SMatthias Ringwald     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
2776efedfb4cSMatthias Ringwald     uint16_t * out_local_cid) {
2777efedfb4cSMatthias Ringwald 
27787dafa750SMatthias Ringwald     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
2779da144af5SMatthias Ringwald 
27807dafa750SMatthias Ringwald 
27817dafa750SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
27827dafa750SMatthias Ringwald     if (!connection) {
27837dafa750SMatthias Ringwald         log_error("no hci_connection for handle 0x%04x", con_handle);
27847dafa750SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
27857dafa750SMatthias Ringwald     }
27867dafa750SMatthias Ringwald 
27877dafa750SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, connection->address, connection->address_type, psm, mtu, security_level);
2788da144af5SMatthias Ringwald     if (!channel) {
2789da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
2790da144af5SMatthias Ringwald     }
2791e7d0c9aaSMatthias Ringwald     log_info("l2cap_le_create_channel %p", channel);
2792da144af5SMatthias Ringwald 
2793da144af5SMatthias Ringwald     // store local_cid
2794da144af5SMatthias Ringwald     if (out_local_cid){
2795da144af5SMatthias Ringwald        *out_local_cid = channel->local_cid;
2796da144af5SMatthias Ringwald     }
2797da144af5SMatthias Ringwald 
27987dafa750SMatthias Ringwald     // provide buffer
27997dafa750SMatthias Ringwald     channel->con_handle = con_handle;
2800cd529728SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
28017dafa750SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
280285aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
280385aeef60SMatthias Ringwald     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
280485aeef60SMatthias Ringwald 
2805efedfb4cSMatthias Ringwald     // add to connections list
2806efedfb4cSMatthias Ringwald     btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2807efedfb4cSMatthias Ringwald 
28087dafa750SMatthias Ringwald     // go
280963f0ac45SMatthias Ringwald     l2cap_run();
2810da144af5SMatthias Ringwald     return 0;
2811da144af5SMatthias Ringwald }
2812da144af5SMatthias Ringwald 
2813da144af5SMatthias Ringwald /**
2814da144af5SMatthias Ringwald  * @brief Provide credtis for LE Data Channel
2815da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2816da144af5SMatthias Ringwald  * @param credits               Number additional credits for peer
2817da144af5SMatthias Ringwald  */
281864e11ca9SMatthias Ringwald uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
281963f0ac45SMatthias Ringwald 
282063f0ac45SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
282163f0ac45SMatthias Ringwald     if (!channel) {
282263f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
282363f0ac45SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
282463f0ac45SMatthias Ringwald     }
282563f0ac45SMatthias Ringwald 
2826efedfb4cSMatthias Ringwald     // check state
282763f0ac45SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN){
282863f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
282963f0ac45SMatthias Ringwald     }
283063f0ac45SMatthias Ringwald 
283163f0ac45SMatthias Ringwald     // assert incoming credits + credits <= 0xffff
283263f0ac45SMatthias Ringwald     uint32_t total_credits = channel->credits_incoming;
283363f0ac45SMatthias Ringwald     total_credits += channel->new_credits_incoming;
283463f0ac45SMatthias Ringwald     total_credits += credits;
283563f0ac45SMatthias Ringwald     if (total_credits > 0xffff){
283663f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
283763f0ac45SMatthias Ringwald             channel->new_credits_incoming, credits);
283863f0ac45SMatthias Ringwald     }
283963f0ac45SMatthias Ringwald 
2840efedfb4cSMatthias Ringwald     // set credits_granted
284163f0ac45SMatthias Ringwald     channel->new_credits_incoming += credits;
284263f0ac45SMatthias Ringwald 
284363f0ac45SMatthias Ringwald     // go
284463f0ac45SMatthias Ringwald     l2cap_run();
2845da144af5SMatthias Ringwald     return 0;
2846da144af5SMatthias Ringwald }
2847da144af5SMatthias Ringwald 
2848da144af5SMatthias Ringwald /**
2849da144af5SMatthias Ringwald  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
2850da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2851da144af5SMatthias Ringwald  */
285264e11ca9SMatthias Ringwald int l2cap_le_can_send_now(uint16_t local_cid){
285344276248SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
285444276248SMatthias Ringwald     if (!channel) {
285544276248SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
2856da144af5SMatthias Ringwald         return 0;
2857da144af5SMatthias Ringwald     }
2858da144af5SMatthias Ringwald 
285944276248SMatthias Ringwald     // check state
286044276248SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN) return 0;
286144276248SMatthias Ringwald 
286244276248SMatthias Ringwald     // check queue
286344276248SMatthias Ringwald     if (channel->send_sdu_buffer) return 0;
286444276248SMatthias Ringwald 
286544276248SMatthias Ringwald     // fine, go ahead
286644276248SMatthias Ringwald     return 1;
286744276248SMatthias Ringwald }
286844276248SMatthias Ringwald 
2869da144af5SMatthias Ringwald /**
2870da144af5SMatthias Ringwald  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
2871da144af5SMatthias Ringwald  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
2872da144af5SMatthias Ringwald  *       so packet handler should be ready to handle it
2873da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2874da144af5SMatthias Ringwald  */
287564e11ca9SMatthias Ringwald uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
287644276248SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
287744276248SMatthias Ringwald     if (!channel) {
287844276248SMatthias Ringwald         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
287944276248SMatthias Ringwald         return 0;
288044276248SMatthias Ringwald     }
288144276248SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
288244276248SMatthias Ringwald     l2cap_le_notify_channel_can_send(channel);
2883da144af5SMatthias Ringwald     return 0;
2884da144af5SMatthias Ringwald }
2885da144af5SMatthias Ringwald 
2886da144af5SMatthias Ringwald /**
2887da144af5SMatthias Ringwald  * @brief Send data via LE Data Channel
2888da144af5SMatthias Ringwald  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
2889da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2890da144af5SMatthias Ringwald  * @param data                  data to send
2891da144af5SMatthias Ringwald  * @param size                  data size
2892da144af5SMatthias Ringwald  */
289364e11ca9SMatthias Ringwald uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
289464e11ca9SMatthias Ringwald 
289564e11ca9SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
289664e11ca9SMatthias Ringwald     if (!channel) {
289764e11ca9SMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
2898828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
289964e11ca9SMatthias Ringwald     }
290064e11ca9SMatthias Ringwald 
290164e11ca9SMatthias Ringwald     if (len > channel->remote_mtu){
290264e11ca9SMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
290364e11ca9SMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
290464e11ca9SMatthias Ringwald     }
290564e11ca9SMatthias Ringwald 
29067f107edaSMatthias Ringwald     if (channel->send_sdu_buffer){
290764e11ca9SMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
290864e11ca9SMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
290964e11ca9SMatthias Ringwald     }
291064e11ca9SMatthias Ringwald 
29117f107edaSMatthias Ringwald     channel->send_sdu_buffer = data;
29127f107edaSMatthias Ringwald     channel->send_sdu_len    = len;
29137f107edaSMatthias Ringwald     channel->send_sdu_pos    = 0;
291464e11ca9SMatthias Ringwald 
29157f107edaSMatthias Ringwald     l2cap_run();
29167f107edaSMatthias Ringwald     return 0;
2917da144af5SMatthias Ringwald }
2918da144af5SMatthias Ringwald 
2919da144af5SMatthias Ringwald /**
2920da144af5SMatthias Ringwald  * @brief Disconnect from LE Data Channel
2921da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2922da144af5SMatthias Ringwald  */
2923828a7f7aSMatthias Ringwald uint8_t l2cap_le_disconnect(uint16_t local_cid)
2924da144af5SMatthias Ringwald {
2925828a7f7aSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2926828a7f7aSMatthias Ringwald     if (!channel) {
2927828a7f7aSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
2928828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2929828a7f7aSMatthias Ringwald     }
2930828a7f7aSMatthias Ringwald 
2931828a7f7aSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2932828a7f7aSMatthias Ringwald     l2cap_run();
2933da144af5SMatthias Ringwald     return 0;
2934da144af5SMatthias Ringwald }
2935da144af5SMatthias Ringwald 
29367f02f414SMatthias Ringwald #endif
2937