xref: /btstack/src/l2cap.c (revision 38f62777f872d8e207fb603bdd159a13f809114e)
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){
558*38f62777SMatthias 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 }
665*38f62777SMatthias Ringwald static int l2cap_ertm_send_supervisor_frame(l2cap_channel_t * channel, uint16_t control){
666*38f62777SMatthias Ringwald     hci_reserve_packet_buffer();
667*38f62777SMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
668*38f62777SMatthias Ringwald     log_info("S-Frame: control 0x%04x", control);
669*38f62777SMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
670*38f62777SMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2);
671*38f62777SMatthias 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         }
910*38f62777SMatthias Ringwald 
911*38f62777SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
912*38f62777SMatthias Ringwald         // send s-frame to acknowledge received packets
913*38f62777SMatthias Ringwald         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
914*38f62777SMatthias Ringwald         if (channel->req_seq != 0xff){
915*38f62777SMatthias Ringwald             log_info("try to send s-frame");
916*38f62777SMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 0, 0, channel->req_seq);
917*38f62777SMatthias Ringwald             channel->req_seq = 0xff;
918*38f62777SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
919*38f62777SMatthias Ringwald         }
920*38f62777SMatthias Ringwald #endif
921*38f62777SMatthias 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;
1132*38f62777SMatthias Ringwald 
1133*38f62777SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1134*38f62777SMatthias Ringwald     channel->req_seq = 0xff;
1135*38f62777SMatthias Ringwald #endif
1136*38f62777SMatthias Ringwald 
1137da144af5SMatthias Ringwald     return channel;
1138da144af5SMatthias Ringwald }
113909e9d05bSMatthias Ringwald #endif
114009e9d05bSMatthias Ringwald 
114109e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1142da144af5SMatthias Ringwald 
11439077cb15SMatthias Ringwald /**
11449077cb15SMatthias Ringwald  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
11459077cb15SMatthias Ringwald  * @param packet_handler
11469077cb15SMatthias Ringwald  * @param address
11479077cb15SMatthias Ringwald  * @param psm
11489077cb15SMatthias Ringwald  * @param mtu
11499077cb15SMatthias Ringwald  * @param local_cid
11509077cb15SMatthias Ringwald  */
11519077cb15SMatthias Ringwald 
11529d139fbaSMatthias 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){
11539d139fbaSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
11549d139fbaSMatthias Ringwald     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1155da144af5SMatthias Ringwald 
11569d139fbaSMatthias 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);
1157da144af5SMatthias Ringwald 
1158da144af5SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
1159fc64f94aSMatthias Ringwald     if (!channel) {
11609077cb15SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
11619077cb15SMatthias Ringwald     }
11629077cb15SMatthias Ringwald 
11631b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
11641b9cb13dSMatthias Ringwald     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
11651b9cb13dSMatthias Ringwald #endif
11661b9cb13dSMatthias Ringwald 
11679077cb15SMatthias Ringwald     // add to connections list
1168fc64f94aSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
11699077cb15SMatthias Ringwald 
11709077cb15SMatthias Ringwald     // store local_cid
11719077cb15SMatthias Ringwald     if (out_local_cid){
1172fc64f94aSMatthias Ringwald        *out_local_cid = channel->local_cid;
11739077cb15SMatthias Ringwald     }
11749077cb15SMatthias Ringwald 
11759077cb15SMatthias Ringwald     // check if hci connection is already usable
11769077cb15SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
11779077cb15SMatthias Ringwald     if (conn){
1178add0254bSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
1179fc64f94aSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
11809077cb15SMatthias Ringwald         // check if remote supported fearures are already received
11819077cb15SMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
1182fc64f94aSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
11839077cb15SMatthias Ringwald         }
11849077cb15SMatthias Ringwald     }
11859077cb15SMatthias Ringwald 
11869077cb15SMatthias Ringwald     l2cap_run();
11879077cb15SMatthias Ringwald 
11889077cb15SMatthias Ringwald     return 0;
11899077cb15SMatthias Ringwald }
11909077cb15SMatthias Ringwald 
11911b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
11927b181629SMatthias Ringwald 
11932b70d705SMatthias Ringwald static uint8_t l2cap_ertm_validate_local_config(uint8_t max_transmit, uint16_t retransmission_timeout_ms,
11942b70d705SMatthias Ringwald     uint16_t monitor_timeout_ms, uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size){
11952b70d705SMatthias Ringwald     UNUSED(buffer);
11962b70d705SMatthias Ringwald     UNUSED(size);
11972b70d705SMatthias Ringwald 
11982b70d705SMatthias Ringwald     uint8_t result = ERROR_CODE_SUCCESS;
11992b70d705SMatthias Ringwald     if (max_transmit < 1){
12002b70d705SMatthias Ringwald         log_error("max_transmit must be >= 1");
12012b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
12022b70d705SMatthias Ringwald     }
12032b70d705SMatthias Ringwald     if (retransmission_timeout_ms < 2000){
12042b70d705SMatthias Ringwald         log_error("retransmission_timeout_ms must be >= 2000 ms");
12052b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
12062b70d705SMatthias Ringwald     }
12072b70d705SMatthias Ringwald     if (monitor_timeout_ms < 12000){
12082b70d705SMatthias Ringwald         log_error("monitor_timeout_ms must be >= 12000 ms");
12092b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
12102b70d705SMatthias Ringwald     }
12112b70d705SMatthias Ringwald     if (num_rx_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     if (num_tx_buffers < 1){
12162b70d705SMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
12172b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
12182b70d705SMatthias Ringwald     }
12192b70d705SMatthias Ringwald     return result;
12202b70d705SMatthias Ringwald }
12212b70d705SMatthias Ringwald 
12227b181629SMatthias Ringwald static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, int ertm_mandatory, uint8_t max_transmit,
12237b181629SMatthias 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){
12247b181629SMatthias Ringwald 
12257b181629SMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
12267b181629SMatthias Ringwald     channel->ertm_mandatory = ertm_mandatory;
1227bbc0a9e7SMatthias Ringwald     channel->local_max_transmit = max_transmit;
1228bbc0a9e7SMatthias Ringwald     channel->local_retransmission_timeout_ms = retransmission_timeout_ms;
1229bbc0a9e7SMatthias Ringwald     channel->local_monitor_timeout_ms = monitor_timeout_ms;
12307b181629SMatthias Ringwald     channel->num_rx_buffers = num_rx_buffers;
12317b181629SMatthias Ringwald     channel->num_tx_buffers = num_tx_buffers;
12327b181629SMatthias Ringwald 
12337b181629SMatthias Ringwald     // TODO: align buffer pointer
12347b181629SMatthias Ringwald     uint32_t pos = 0;
12357b181629SMatthias Ringwald     channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) &buffer[pos];
12367b181629SMatthias Ringwald     pos += num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
12377b181629SMatthias Ringwald     channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) &buffer[pos];
12387b181629SMatthias Ringwald     pos += num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
12397b181629SMatthias Ringwald     // calculate MTU
12407b181629SMatthias Ringwald     channel->local_mtu = (size - pos) / (num_rx_buffers + num_tx_buffers);
12417b181629SMatthias Ringwald     log_info("Local ERTM MTU: %u", channel->local_mtu);
12427b181629SMatthias Ringwald     channel->rx_packets_data = &buffer[pos];
12437b181629SMatthias Ringwald     pos += num_rx_buffers * channel->local_mtu;
12447b181629SMatthias Ringwald     channel->tx_packets_data = &buffer[pos];
12457b181629SMatthias Ringwald     log_info("RX packets %p, TX packets %p", channel->rx_packets_data, channel->tx_packets_data);
12467b181629SMatthias Ringwald }
12477b181629SMatthias Ringwald 
1248501329faSMatthias Ringwald uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
1249501329faSMatthias Ringwald     int ertm_mandatory, uint8_t max_transmit, uint16_t retransmission_timeout_ms, uint16_t monitor_timeout_ms,
1250501329faSMatthias Ringwald     uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
1251501329faSMatthias Ringwald 
12521b9cb13dSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
1253501329faSMatthias Ringwald     uint16_t local_mtu = l2cap_max_mtu();
12541b9cb13dSMatthias Ringwald 
1255501329faSMatthias Ringwald     log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x -> local mtu %u", bd_addr_to_str(address), psm, local_mtu);
12561b9cb13dSMatthias Ringwald 
12572b70d705SMatthias Ringwald     // validate local config
12582b70d705SMatthias 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);
12592b70d705SMatthias Ringwald     if (result) return result;
12602b70d705SMatthias Ringwald 
1261501329faSMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
12621b9cb13dSMatthias Ringwald     if (!channel) {
12631b9cb13dSMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
12641b9cb13dSMatthias Ringwald     }
12651b9cb13dSMatthias Ringwald 
12667b181629SMatthias Ringwald     // configure ERTM
12677b181629SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_mandatory, max_transmit, retransmission_timeout_ms,
12687b181629SMatthias Ringwald         monitor_timeout_ms, num_tx_buffers, num_rx_buffers, buffer, size);
12691b9cb13dSMatthias Ringwald 
12701b9cb13dSMatthias Ringwald     // add to connections list
12711b9cb13dSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
12721b9cb13dSMatthias Ringwald 
12731b9cb13dSMatthias Ringwald     // store local_cid
12741b9cb13dSMatthias Ringwald     if (out_local_cid){
12751b9cb13dSMatthias Ringwald        *out_local_cid = channel->local_cid;
12761b9cb13dSMatthias Ringwald     }
12771b9cb13dSMatthias Ringwald 
12781b9cb13dSMatthias Ringwald     // check if hci connection is already usable
12791b9cb13dSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
12801b9cb13dSMatthias Ringwald     if (conn){
12811b9cb13dSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
12821b9cb13dSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
12831b9cb13dSMatthias Ringwald         // check if remote supported fearures are already received
12841b9cb13dSMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
12851b9cb13dSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
12861b9cb13dSMatthias Ringwald         }
12871b9cb13dSMatthias Ringwald     }
12881b9cb13dSMatthias Ringwald 
12891b9cb13dSMatthias Ringwald     l2cap_run();
12901b9cb13dSMatthias Ringwald 
12911b9cb13dSMatthias Ringwald     return 0;
12921b9cb13dSMatthias Ringwald }
12931b9cb13dSMatthias Ringwald #endif
12941b9cb13dSMatthias Ringwald 
1295ce8f182eSMatthias Ringwald void
1296ce8f182eSMatthias Ringwald l2cap_disconnect(uint16_t local_cid, uint8_t reason){
1297e0abb8e7S[email protected]     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
1298b35f641cSmatthias.ringwald     // find channel for local_cid
1299b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1300f62db1e3Smatthias.ringwald     if (channel) {
1301e7ff783cSmatthias.ringwald         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1302f62db1e3Smatthias.ringwald     }
13032cd0be45Smatthias.ringwald     // process
13042cd0be45Smatthias.ringwald     l2cap_run();
130543625864Smatthias.ringwald }
13061e6aba47Smatthias.ringwald 
1307afde0c52Smatthias.ringwald static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
1308665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1309665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1310665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1311665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1312058e3d6bSMatthias Ringwald         if ( bd_addr_cmp( channel->address, address) != 0) continue;
1313c22aecc9S[email protected]         // channel for this address found
1314c22aecc9S[email protected]         switch (channel->state){
1315c22aecc9S[email protected]             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
1316c22aecc9S[email protected]             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1317afde0c52Smatthias.ringwald                 // failure, forward error code
1318afde0c52Smatthias.ringwald                 l2cap_emit_channel_opened(channel, status);
1319afde0c52Smatthias.ringwald                 // discard channel
13209dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
1321665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1322d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
1323c22aecc9S[email protected]                 break;
1324c22aecc9S[email protected]             default:
1325c22aecc9S[email protected]                 break;
1326afde0c52Smatthias.ringwald         }
1327afde0c52Smatthias.ringwald     }
1328afde0c52Smatthias.ringwald }
1329afde0c52Smatthias.ringwald 
1330afde0c52Smatthias.ringwald static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
1331665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1332665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1333665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1334665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1335058e3d6bSMatthias Ringwald         if ( ! bd_addr_cmp( channel->address, address) ){
13362df5dadcS[email protected]             l2cap_handle_connection_complete(handle, channel);
1337afde0c52Smatthias.ringwald         }
1338afde0c52Smatthias.ringwald     }
13396fdcc387Smatthias.ringwald     // process
13406fdcc387Smatthias.ringwald     l2cap_run();
1341afde0c52Smatthias.ringwald }
134209e9d05bSMatthias Ringwald #endif
1343b448a0e7Smatthias.ringwald 
134433c40538SMatthias Ringwald static void l2cap_notify_channel_can_send(void){
134509e9d05bSMatthias Ringwald 
134609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
134733c40538SMatthias Ringwald     btstack_linked_list_iterator_t it;
134833c40538SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
134933c40538SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
135033c40538SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
135133c40538SMatthias Ringwald         if (!channel->waiting_for_can_send_now) continue;
1352fc64f94aSMatthias Ringwald         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
135333c40538SMatthias Ringwald         channel->waiting_for_can_send_now = 0;
135434e7e577SMatthias Ringwald         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
135533c40538SMatthias Ringwald     }
135609e9d05bSMatthias Ringwald #endif
135744276248SMatthias Ringwald 
13582125de09SMatthias Ringwald     int i;
13592125de09SMatthias Ringwald     for (i=0;i<L2CAP_FIXED_CHANNEL_TABLE_SIZE;i++){
1360773c4106SMatthias Ringwald         if (!fixed_channels[i].callback) continue;
13612125de09SMatthias Ringwald         if (!fixed_channels[i].waiting_for_can_send_now) continue;
136235454696SMatthias Ringwald         int can_send = 0;
136334e7e577SMatthias Ringwald         if (l2cap_fixed_channel_table_index_is_le(i)){
136435454696SMatthias Ringwald #ifdef ENABLE_BLE
136534e7e577SMatthias Ringwald             can_send = hci_can_send_acl_le_packet_now();
136635454696SMatthias Ringwald #endif
136734e7e577SMatthias Ringwald         } else {
136835454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
136934e7e577SMatthias Ringwald             can_send = hci_can_send_acl_classic_packet_now();
137035454696SMatthias Ringwald #endif
137134e7e577SMatthias Ringwald         }
137234e7e577SMatthias Ringwald         if (!can_send) continue;
137334e7e577SMatthias Ringwald         fixed_channels[i].waiting_for_can_send_now = 0;
137434e7e577SMatthias Ringwald         l2cap_emit_can_send_now(fixed_channels[i].callback, l2cap_fixed_channel_table_channel_id_for_index(i));
13752125de09SMatthias Ringwald     }
137633c40538SMatthias Ringwald }
137733c40538SMatthias Ringwald 
1378d9a7306aSMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
1379afde0c52Smatthias.ringwald 
13809ec2630cSMatthias Ringwald     UNUSED(packet_type);
13819ec2630cSMatthias Ringwald     UNUSED(cid);
13829ec2630cSMatthias Ringwald     UNUSED(size);
13839ec2630cSMatthias Ringwald 
1384afde0c52Smatthias.ringwald     bd_addr_t address;
1385afde0c52Smatthias.ringwald     hci_con_handle_t handle;
13862d00edd4Smatthias.ringwald     int hci_con_used;
138709e9d05bSMatthias Ringwald     btstack_linked_list_iterator_t it;
138809e9d05bSMatthias Ringwald 
138909e9d05bSMatthias Ringwald     // avoid unused warnings
1390f3963406SMatthias Ringwald     UNUSED(address);
1391f3963406SMatthias Ringwald     UNUSED(hci_con_used);
1392f3963406SMatthias Ringwald     UNUSED(it);
1393f22209dfSMatthias Ringwald     UNUSED(handle);
1394afde0c52Smatthias.ringwald 
13950e2df43fSMatthias Ringwald     switch(hci_event_packet_get_type(packet)){
1396afde0c52Smatthias.ringwald 
139709e9d05bSMatthias Ringwald         // Notify channel packet handler if they can send now
139809e9d05bSMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
139909e9d05bSMatthias Ringwald         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
140009e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
140109e9d05bSMatthias Ringwald             l2cap_notify_channel_can_send();
140209e9d05bSMatthias Ringwald             break;
140309e9d05bSMatthias Ringwald 
140409e9d05bSMatthias Ringwald         case HCI_EVENT_COMMAND_STATUS:
140509e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
140609e9d05bSMatthias Ringwald             break;
140709e9d05bSMatthias Ringwald 
140809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1409afde0c52Smatthias.ringwald         // handle connection complete events
1410afde0c52Smatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
1411724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], address);
1412afde0c52Smatthias.ringwald             if (packet[2] == 0){
1413f8fbdce0SMatthias Ringwald                 handle = little_endian_read_16(packet, 3);
1414afde0c52Smatthias.ringwald                 l2cap_handle_connection_success_for_addr(address, handle);
1415afde0c52Smatthias.ringwald             } else {
1416afde0c52Smatthias.ringwald                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
1417afde0c52Smatthias.ringwald             }
1418afde0c52Smatthias.ringwald             break;
1419afde0c52Smatthias.ringwald 
1420afde0c52Smatthias.ringwald         // handle successful create connection cancel command
1421afde0c52Smatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
1422073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
1423afde0c52Smatthias.ringwald                 if (packet[5] == 0){
1424724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[6], address);
1425afde0c52Smatthias.ringwald                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
1426afde0c52Smatthias.ringwald                     l2cap_handle_connection_failed_for_addr(address, 0x16);
142703cfbabcSmatthias.ringwald                 }
14281e6aba47Smatthias.ringwald             }
142939d59809Smatthias.ringwald             l2cap_run();    // try sending signaling packets first
143039d59809Smatthias.ringwald             break;
143109e9d05bSMatthias Ringwald #endif
143227a923d0Smatthias.ringwald 
14331e6aba47Smatthias.ringwald         // handle disconnection complete events
1434afde0c52Smatthias.ringwald         case HCI_EVENT_DISCONNECTION_COMPLETE:
1435c22aecc9S[email protected]             // send l2cap disconnect events for all channels on this handle and free them
143609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1437d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1438665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1439665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1440665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1441fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
144215ec09bbSmatthias.ringwald                 l2cap_emit_channel_closed(channel);
14439dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
1444665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1445d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
144627a923d0Smatthias.ringwald             }
144709e9d05bSMatthias Ringwald #endif
1448a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1449d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1450991fea48SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1451991fea48SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1452991fea48SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1453991fea48SMatthias Ringwald                 if (channel->con_handle != handle) continue;
1454991fea48SMatthias Ringwald                 l2cap_emit_channel_closed(channel);
1455991fea48SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1456991fea48SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
1457991fea48SMatthias Ringwald             }
1458991fea48SMatthias Ringwald #endif
1459afde0c52Smatthias.ringwald             break;
1460fcadd0caSmatthias.ringwald 
1461ee091cf1Smatthias.ringwald         // HCI Connection Timeouts
146209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1463afde0c52Smatthias.ringwald         case L2CAP_EVENT_TIMEOUT_CHECK:
1464f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
1465bd04d84aSMatthias Ringwald             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
146680ca58a0Smatthias.ringwald             if (hci_authentication_active_for_handle(handle)) break;
14672d00edd4Smatthias.ringwald             hci_con_used = 0;
1468665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1469665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1470665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1471fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
14722d00edd4Smatthias.ringwald                 hci_con_used = 1;
1473c22aecc9S[email protected]                 break;
1474ee091cf1Smatthias.ringwald             }
14752d00edd4Smatthias.ringwald             if (hci_con_used) break;
1476d94d3cafS[email protected]             if (!hci_can_send_command_packet_now()) break;
14779edc8742Smatthias.ringwald             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
1478afde0c52Smatthias.ringwald             break;
1479ee091cf1Smatthias.ringwald 
1480df3354fcS[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1481f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1482665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1483665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1484665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1485fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
14862df5dadcS[email protected]                 l2cap_handle_remote_supported_features_received(channel);
1487df3354fcS[email protected]                 break;
1488df3354fcS[email protected]             }
1489c22aecc9S[email protected]             break;
1490df3354fcS[email protected] 
14915611a760SMatthias Ringwald         case GAP_EVENT_SECURITY_LEVEL:
1492f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
1493bd63148eS[email protected]             log_info("l2cap - security level update");
1494665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1495665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1496665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1497fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
14985533f01eS[email protected] 
1499bd63148eS[email protected]                 log_info("l2cap - state %u", channel->state);
1500bd63148eS[email protected] 
1501e569dfd9SMatthias Ringwald                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
15025533f01eS[email protected]                 gap_security_level_t required_level = channel->required_security_level;
15035533f01eS[email protected] 
1504df3354fcS[email protected]                 switch (channel->state){
1505df3354fcS[email protected]                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
15065533f01eS[email protected]                         if (actual_level >= required_level){
150752606043SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
150852606043SMatthias Ringwald                             // we need to know if ERTM is supported before sending a config response
150952606043SMatthias Ringwald                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
151052606043SMatthias Ringwald                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
151152606043SMatthias Ringwald                             channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
151252606043SMatthias Ringwald #else
1513f85a9399S[email protected]                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
151444276248SMatthias Ringwald                             l2cap_emit_incoming_connection(channel);
151552606043SMatthias Ringwald #endif
15161eb2563eS[email protected]                         } else {
1517775ecc36SMatthias Ringwald                             channel->reason = 0x0003; // security block
15181eb2563eS[email protected]                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
15191eb2563eS[email protected]                         }
1520df3354fcS[email protected]                         break;
1521df3354fcS[email protected] 
1522df3354fcS[email protected]                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
15235533f01eS[email protected]                         if (actual_level >= required_level){
15241b9cb13dSMatthias Ringwald                             l2cap_ready_to_connect(channel);
1525df3354fcS[email protected]                         } else {
1526df3354fcS[email protected]                             // disconnnect, authentication not good enough
1527df3354fcS[email protected]                             hci_disconnect_security_block(handle);
1528df3354fcS[email protected]                         }
1529df3354fcS[email protected]                         break;
1530df3354fcS[email protected] 
1531df3354fcS[email protected]                     default:
1532df3354fcS[email protected]                         break;
1533df3354fcS[email protected]                 }
1534f85a9399S[email protected]             }
1535f85a9399S[email protected]             break;
153609e9d05bSMatthias Ringwald #endif
1537f85a9399S[email protected] 
1538afde0c52Smatthias.ringwald         default:
1539afde0c52Smatthias.ringwald             break;
1540afde0c52Smatthias.ringwald     }
1541afde0c52Smatthias.ringwald 
1542bd63148eS[email protected]     l2cap_run();
15431e6aba47Smatthias.ringwald }
15441e6aba47Smatthias.ringwald 
1545e74c5f58SMatthias 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){
15464cf56b4aSmatthias.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."
15472b360848Smatthias.ringwald     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
15482b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].handle = handle;
15492b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].code = code;
15502b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].sig_id = sig_id;
1551e74c5f58SMatthias Ringwald         signaling_responses[signaling_responses_pending].cid = cid;
15522b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].data = data;
15532b360848Smatthias.ringwald         signaling_responses_pending++;
15542b360848Smatthias.ringwald         l2cap_run();
15552b360848Smatthias.ringwald     }
15562b360848Smatthias.ringwald }
15572b360848Smatthias.ringwald 
155809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
155909e9d05bSMatthias Ringwald static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
156009e9d05bSMatthias Ringwald     channel->remote_sig_id = identifier;
156109e9d05bSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
156209e9d05bSMatthias Ringwald     l2cap_run();
156309e9d05bSMatthias Ringwald }
156409e9d05bSMatthias Ringwald 
1565b35f641cSmatthias.ringwald static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
1566645658c9Smatthias.ringwald 
15679da54300S[email protected]     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
1568645658c9Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
1569645658c9Smatthias.ringwald     if (!service) {
1570645658c9Smatthias.ringwald         // 0x0002 PSM not supported
1571e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
1572645658c9Smatthias.ringwald         return;
1573645658c9Smatthias.ringwald     }
1574645658c9Smatthias.ringwald 
15755061f3afS[email protected]     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
1576645658c9Smatthias.ringwald     if (!hci_connection) {
15772b360848Smatthias.ringwald         //
15789da54300S[email protected]         log_error("no hci_connection for handle %u", handle);
1579645658c9Smatthias.ringwald         return;
1580645658c9Smatthias.ringwald     }
15812bd8b7e7S[email protected] 
1582645658c9Smatthias.ringwald     // alloc structure
15839da54300S[email protected]     // log_info("l2cap_handle_connection_request register channel");
1584da144af5SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, hci_connection->address, BD_ADDR_TYPE_CLASSIC,
1585da144af5SMatthias Ringwald     psm, service->mtu, service->required_security_level);
15862b360848Smatthias.ringwald     if (!channel){
15872b360848Smatthias.ringwald         // 0x0004 No resources available
1588e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
15892b360848Smatthias.ringwald         return;
15902b360848Smatthias.ringwald     }
1591da144af5SMatthias Ringwald 
1592fc64f94aSMatthias Ringwald     channel->con_handle = handle;
1593b35f641cSmatthias.ringwald     channel->remote_cid = source_cid;
1594b1988dceSmatthias.ringwald     channel->remote_sig_id = sig_id;
1595645658c9Smatthias.ringwald 
1596f53da564S[email protected]     // limit local mtu to max acl packet length - l2cap header
15972985cb84Smatthias.ringwald     if (channel->local_mtu > l2cap_max_mtu()) {
15982985cb84Smatthias.ringwald         channel->local_mtu = l2cap_max_mtu();
15999775e25bSmatthias.ringwald     }
16009775e25bSmatthias.ringwald 
1601645658c9Smatthias.ringwald     // set initial state
1602df3354fcS[email protected]     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
1603a24785d0SMatthias Ringwald     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
1604e405ae81Smatthias.ringwald 
1605645658c9Smatthias.ringwald     // add to connections list
1606665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1607645658c9Smatthias.ringwald 
1608f85a9399S[email protected]     // assert security requirements
16091eb2563eS[email protected]     gap_request_security_level(handle, channel->required_security_level);
1610e405ae81Smatthias.ringwald }
1611645658c9Smatthias.ringwald 
1612ce8f182eSMatthias Ringwald void l2cap_accept_connection(uint16_t local_cid){
1613e0abb8e7S[email protected]     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
1614b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1615e405ae81Smatthias.ringwald     if (!channel) {
1616ce8f182eSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
1617e405ae81Smatthias.ringwald         return;
1618e405ae81Smatthias.ringwald     }
1619e405ae81Smatthias.ringwald 
162043ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
162143ec931dSMatthias Ringwald     // configure L2CAP Basic mode
162243ec931dSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
162343ec931dSMatthias Ringwald #endif
162443ec931dSMatthias Ringwald 
1625552d92a1Smatthias.ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
1626e405ae81Smatthias.ringwald 
1627552d92a1Smatthias.ringwald     // process
1628552d92a1Smatthias.ringwald     l2cap_run();
1629e405ae81Smatthias.ringwald }
1630645658c9Smatthias.ringwald 
163143ec931dSMatthias Ringwald 
163243ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
16332b70d705SMatthias Ringwald uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, int ertm_mandatory, uint8_t max_transmit,
1634501329faSMatthias 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){
1635501329faSMatthias Ringwald 
163643ec931dSMatthias Ringwald     log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
163743ec931dSMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
163843ec931dSMatthias Ringwald     if (!channel) {
163943ec931dSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
16402b70d705SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
164143ec931dSMatthias Ringwald     }
164243ec931dSMatthias Ringwald 
16432b70d705SMatthias Ringwald     // validate local config
16442b70d705SMatthias 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);
16452b70d705SMatthias Ringwald     if (result) return result;
16462b70d705SMatthias Ringwald 
164743ec931dSMatthias Ringwald     // configure L2CAP ERTM
16487b181629SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_mandatory, max_transmit, retransmission_timeout_ms, monitor_timeout_ms, num_tx_buffers, num_rx_buffers, buffer, size);
164943ec931dSMatthias Ringwald 
16507b181629SMatthias Ringwald     // continue
165143ec931dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
165243ec931dSMatthias Ringwald 
165343ec931dSMatthias Ringwald     // process
165443ec931dSMatthias Ringwald     l2cap_run();
16552b70d705SMatthias Ringwald 
16562b70d705SMatthias Ringwald     return ERROR_CODE_SUCCESS;
165743ec931dSMatthias Ringwald }
165843ec931dSMatthias Ringwald #endif
165943ec931dSMatthias Ringwald 
166043ec931dSMatthias Ringwald 
16617ef6a7bbSMatthias Ringwald void l2cap_decline_connection(uint16_t local_cid){
16627ef6a7bbSMatthias Ringwald     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
1663b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
1664e405ae81Smatthias.ringwald     if (!channel) {
1665ce8f182eSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
1666e405ae81Smatthias.ringwald         return;
1667e405ae81Smatthias.ringwald     }
1668e7ff783cSmatthias.ringwald     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
16697ef6a7bbSMatthias Ringwald     channel->reason = 0x04; // no resources available
1670e7ff783cSmatthias.ringwald     l2cap_run();
1671645658c9Smatthias.ringwald }
1672645658c9Smatthias.ringwald 
16737f02f414SMatthias Ringwald static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
1674b1988dceSmatthias.ringwald 
1675b1988dceSmatthias.ringwald     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1676b1988dceSmatthias.ringwald 
1677f8fbdce0SMatthias Ringwald     uint16_t flags = little_endian_read_16(command, 6);
167863a7246aSmatthias.ringwald     if (flags & 1) {
167963a7246aSmatthias.ringwald         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
168063a7246aSmatthias.ringwald     }
168163a7246aSmatthias.ringwald 
16822784b77dSmatthias.ringwald     // accept the other's configuration options
1683f8fbdce0SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
16843de7c0caSmatthias.ringwald     uint16_t pos     = 8;
16853de7c0caSmatthias.ringwald     while (pos < end_pos){
168663a7246aSmatthias.ringwald         uint8_t option_hint = command[pos] >> 7;
168763a7246aSmatthias.ringwald         uint8_t option_type = command[pos] & 0x7f;
168863a7246aSmatthias.ringwald         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
168963a7246aSmatthias.ringwald         pos++;
16901dc511deSmatthias.ringwald         uint8_t length = command[pos++];
16911dc511deSmatthias.ringwald         // MTU { type(8): 1, len(8):2, MTU(16) }
169263a7246aSmatthias.ringwald         if (option_type == 1 && length == 2){
1693f8fbdce0SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, pos);
16949d139fbaSMatthias Ringwald             if (channel->remote_mtu > l2cap_max_mtu()){
16959d139fbaSMatthias Ringwald                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
16969d139fbaSMatthias Ringwald                 channel->remote_mtu = l2cap_max_mtu();
16979d139fbaSMatthias Ringwald             }
169863a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
169963a7246aSmatthias.ringwald         }
17000fe7a9d0S[email protected]         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
17010fe7a9d0S[email protected]         if (option_type == 2 && length == 2){
1702f8fbdce0SMatthias Ringwald             channel->flush_timeout = little_endian_read_16(command, pos);
17030fe7a9d0S[email protected]         }
1704f2fa388dSMatthias Ringwald 
17056dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
17066dca2a0cSMatthias Ringwald         // Retransmission and Flow Control Option
17076dca2a0cSMatthias Ringwald         if (option_type == 4 && length == 9){
17083232a1c6SMatthias Ringwald             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
1709ac8f1300SMatthias Ringwald             switch(channel->mode){
1710ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
1711ac8f1300SMatthias Ringwald                     if (channel->ertm_mandatory){
1712ac8f1300SMatthias Ringwald                         // ERTM mandatory, but remote doens't offer ERTM -> disconnect
17133232a1c6SMatthias Ringwald                         if (mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
17143232a1c6SMatthias Ringwald                             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
17153232a1c6SMatthias Ringwald                         } else {
1716ac8f1300SMatthias Ringwald                             // Both sides selected ERTM
1717bbc0a9e7SMatthias Ringwald                             channel->remote_tx_window_size = command[pos+1];
1718bbc0a9e7SMatthias Ringwald                             channel->remote_max_transmit   = command[pos+2];
1719bbc0a9e7SMatthias Ringwald                             channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
1720bbc0a9e7SMatthias Ringwald                             channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
1721bbc0a9e7SMatthias Ringwald                             log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u",
1722bbc0a9e7SMatthias Ringwald                                 channel->remote_tx_window_size,
1723bbc0a9e7SMatthias Ringwald                                 channel->remote_max_transmit,
1724bbc0a9e7SMatthias Ringwald                                 channel->remote_retransmission_timeout_ms,
1725bbc0a9e7SMatthias Ringwald                                 channel->remote_monitor_timeout_ms);
1726bbc0a9e7SMatthias Ringwald                             // we store remote MPS in remote_mtu, might need to get re-evaluated
1727bbc0a9e7SMatthias Ringwald                             channel->remote_mtu = little_endian_read_16(command, pos + 7);
17286dca2a0cSMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
17296dca2a0cSMatthias Ringwald                         }
1730ac8f1300SMatthias Ringwald                     } else {
1731ac8f1300SMatthias Ringwald                         // ERTM is optional
1732ac8f1300SMatthias Ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1733ac8f1300SMatthias Ringwald                     }
1734ac8f1300SMatthias Ringwald                     break;
1735ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
1736ac8f1300SMatthias Ringwald                     switch (mode){
1737ac8f1300SMatthias Ringwald                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
1738ac8f1300SMatthias Ringwald                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
1739ac8f1300SMatthias Ringwald                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
1740ac8f1300SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1741ac8f1300SMatthias Ringwald                             }
1742ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
1743ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1744ac8f1300SMatthias Ringwald                             break;
1745ac8f1300SMatthias Ringwald                         default: // case L2CAP_CHANNEL_MODE_BASIC:
1746ac8f1300SMatthias Ringwald                             // TODO store and evaluate configuration
1747ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1748ac8f1300SMatthias Ringwald                             break;
1749ac8f1300SMatthias Ringwald                     }
1750ac8f1300SMatthias Ringwald                     break;
1751ac8f1300SMatthias Ringwald                 default:
1752ac8f1300SMatthias Ringwald                     break;
1753ac8f1300SMatthias Ringwald             }
17543232a1c6SMatthias Ringwald         }
17556dca2a0cSMatthias Ringwald #endif
175663a7246aSmatthias.ringwald         // check for unknown options
175763a7246aSmatthias.ringwald         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
1758c177a91cS[email protected]             log_info("l2cap cid %u, unknown options", channel->local_cid);
175963a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
17601dc511deSmatthias.ringwald         }
17611dc511deSmatthias.ringwald         pos += length;
17621dc511deSmatthias.ringwald     }
17632784b77dSmatthias.ringwald }
17642784b77dSmatthias.ringwald 
1765f2fa388dSMatthias Ringwald static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
1766f2fa388dSMatthias Ringwald     log_info("l2cap_signaling_handle_configure_response");
17673232a1c6SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
17683232a1c6SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1769f2fa388dSMatthias Ringwald     uint16_t pos     = 10;
17703232a1c6SMatthias Ringwald     while (pos < end_pos){
17713232a1c6SMatthias Ringwald         uint8_t option_hint = command[pos] >> 7;
17723232a1c6SMatthias Ringwald         uint8_t option_type = command[pos] & 0x7f;
17733232a1c6SMatthias Ringwald         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
17743232a1c6SMatthias Ringwald         pos++;
17753232a1c6SMatthias Ringwald         uint8_t length = command[pos++];
17763232a1c6SMatthias Ringwald 
17773232a1c6SMatthias Ringwald         // Retransmission and Flow Control Option
17783232a1c6SMatthias Ringwald         if (option_type == 4 && length == 9){
1779ac8f1300SMatthias Ringwald             switch (channel->mode){
1780ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
1781f2fa388dSMatthias Ringwald                     if (channel->ertm_mandatory){
1782ac8f1300SMatthias Ringwald                         // ??
1783f2fa388dSMatthias Ringwald                     } else {
1784ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
1785ac8f1300SMatthias Ringwald                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
1786f2fa388dSMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
17873232a1c6SMatthias Ringwald                         }
17883232a1c6SMatthias Ringwald                     }
1789ac8f1300SMatthias Ringwald                     break;
1790ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
1791ac8f1300SMatthias Ringwald                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
1792ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
1793ac8f1300SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1794ac8f1300SMatthias Ringwald                     }
1795ac8f1300SMatthias Ringwald                     break;
1796ac8f1300SMatthias Ringwald                 default:
1797ac8f1300SMatthias Ringwald                     break;
17983232a1c6SMatthias Ringwald             }
1799f2fa388dSMatthias Ringwald         }
18003232a1c6SMatthias Ringwald 
18013232a1c6SMatthias Ringwald         // check for unknown options
18023232a1c6SMatthias Ringwald         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
18033232a1c6SMatthias Ringwald             log_info("l2cap cid %u, unknown options", channel->local_cid);
18043232a1c6SMatthias Ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
18053232a1c6SMatthias Ringwald         }
18063232a1c6SMatthias Ringwald 
18073232a1c6SMatthias Ringwald         pos += length;
18083232a1c6SMatthias Ringwald     }
18093232a1c6SMatthias Ringwald #endif
18103232a1c6SMatthias Ringwald }
18113232a1c6SMatthias Ringwald 
1812fa8473a4Smatthias.ringwald static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
18139da54300S[email protected]     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
181473cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
181573cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
1816019f9b43SMatthias Ringwald     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
1817019f9b43SMatthias Ringwald     if (channel->state == L2CAP_STATE_OPEN) return 0;
1818fa8473a4Smatthias.ringwald     return 1;
1819fa8473a4Smatthias.ringwald }
1820fa8473a4Smatthias.ringwald 
1821fa8473a4Smatthias.ringwald 
18227f02f414SMatthias Ringwald static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
18231e6aba47Smatthias.ringwald 
182400d93d79Smatthias.ringwald     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
182500d93d79Smatthias.ringwald     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
182638e5900eSmatthias.ringwald     uint16_t result = 0;
18271e6aba47Smatthias.ringwald 
18289da54300S[email protected]     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
1829b35f641cSmatthias.ringwald 
18309a011532Smatthias.ringwald     // handle DISCONNECT REQUESTS seperately
18319a011532Smatthias.ringwald     if (code == DISCONNECTION_REQUEST){
18329a011532Smatthias.ringwald         switch (channel->state){
1833fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
18349a011532Smatthias.ringwald             case L2CAP_STATE_OPEN:
18352b83fb7dSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
18369a011532Smatthias.ringwald             case L2CAP_STATE_WAIT_DISCONNECT:
18379a011532Smatthias.ringwald                 l2cap_handle_disconnect_request(channel, identifier);
18389a011532Smatthias.ringwald                 break;
18399a011532Smatthias.ringwald 
18409a011532Smatthias.ringwald             default:
18419a011532Smatthias.ringwald                 // ignore in other states
18429a011532Smatthias.ringwald                 break;
18439a011532Smatthias.ringwald         }
18449a011532Smatthias.ringwald         return;
18459a011532Smatthias.ringwald     }
18469a011532Smatthias.ringwald 
184756081214Smatthias.ringwald     // @STATEMACHINE(l2cap)
18481e6aba47Smatthias.ringwald     switch (channel->state) {
18491e6aba47Smatthias.ringwald 
18501e6aba47Smatthias.ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
18511e6aba47Smatthias.ringwald             switch (code){
18521e6aba47Smatthias.ringwald                 case CONNECTION_RESPONSE:
18535932bd7cS[email protected]                     l2cap_stop_rtx(channel);
1854f8fbdce0SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
185538e5900eSmatthias.ringwald                     switch (result) {
185638e5900eSmatthias.ringwald                         case 0:
1857169f8b28Smatthias.ringwald                             // successful connection
1858f8fbdce0SMatthias Ringwald                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1859fa8473a4Smatthias.ringwald                             channel->state = L2CAP_STATE_CONFIG;
186028ca2b46S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
186138e5900eSmatthias.ringwald                             break;
186238e5900eSmatthias.ringwald                         case 1:
18635932bd7cS[email protected]                             // connection pending. get some coffee, but start the ERTX
18645932bd7cS[email protected]                             l2cap_start_ertx(channel);
186538e5900eSmatthias.ringwald                             break;
186638e5900eSmatthias.ringwald                         default:
1867eb920dbeSmatthias.ringwald                             // channel closed
1868eb920dbeSmatthias.ringwald                             channel->state = L2CAP_STATE_CLOSED;
1869f32b992eSmatthias.ringwald                             // map l2cap connection response result to BTstack status enumeration
187038e5900eSmatthias.ringwald                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
1871eb920dbeSmatthias.ringwald 
1872eb920dbeSmatthias.ringwald                             // drop link key if security block
1873eb920dbeSmatthias.ringwald                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
187415a95bd5SMatthias Ringwald                                 gap_drop_link_key_for_bd_addr(channel->address);
1875eb920dbeSmatthias.ringwald                             }
1876eb920dbeSmatthias.ringwald 
1877eb920dbeSmatthias.ringwald                             // discard channel
1878665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1879d3a9df87Smatthias.ringwald                             btstack_memory_l2cap_channel_free(channel);
188038e5900eSmatthias.ringwald                             break;
18811e6aba47Smatthias.ringwald                     }
18821e6aba47Smatthias.ringwald                     break;
188338e5900eSmatthias.ringwald 
188438e5900eSmatthias.ringwald                 default:
18851e6aba47Smatthias.ringwald                     //@TODO: implement other signaling packets
188638e5900eSmatthias.ringwald                     break;
18871e6aba47Smatthias.ringwald             }
18881e6aba47Smatthias.ringwald             break;
18891e6aba47Smatthias.ringwald 
1890fa8473a4Smatthias.ringwald         case L2CAP_STATE_CONFIG:
1891f8fbdce0SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1892ae280e73Smatthias.ringwald             switch (code) {
1893ae280e73Smatthias.ringwald                 case CONFIGURE_REQUEST:
189428ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1895ae280e73Smatthias.ringwald                     l2cap_signaling_handle_configure_request(channel, command);
189663a7246aSmatthias.ringwald                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
189763a7246aSmatthias.ringwald                         // only done if continuation not set
189863a7246aSmatthias.ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
189963a7246aSmatthias.ringwald                     }
1900ae280e73Smatthias.ringwald                     break;
19011e6aba47Smatthias.ringwald                 case CONFIGURE_RESPONSE:
19025932bd7cS[email protected]                     l2cap_stop_rtx(channel);
1903f2fa388dSMatthias Ringwald                     l2cap_signaling_handle_configure_response(channel, result, command);
19045932bd7cS[email protected]                     switch (result){
19055932bd7cS[email protected]                         case 0: // success
19065932bd7cS[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
19075932bd7cS[email protected]                             break;
19085932bd7cS[email protected]                         case 4: // pending
19095932bd7cS[email protected]                             l2cap_start_ertx(channel);
19105932bd7cS[email protected]                             break;
19115932bd7cS[email protected]                         default:
1912a32d6a03SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1913a32d6a03SMatthias Ringwald                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
1914a32d6a03SMatthias Ringwald                                 // remote does not offer ertm but it's required
1915a32d6a03SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1916a32d6a03SMatthias Ringwald                                 break;
1917a32d6a03SMatthias Ringwald                             }
1918a32d6a03SMatthias Ringwald #endif
1919fe9d8984S[email protected]                             // retry on negative result
1920fe9d8984S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1921fe9d8984S[email protected]                             break;
1922fe9d8984S[email protected]                     }
19235a67bd4aSmatthias.ringwald                     break;
19245a67bd4aSmatthias.ringwald                 default:
19255a67bd4aSmatthias.ringwald                     break;
19261e6aba47Smatthias.ringwald             }
1927fa8473a4Smatthias.ringwald             if (l2cap_channel_ready_for_open(channel)){
1928fa8473a4Smatthias.ringwald                 // for open:
19295a67bd4aSmatthias.ringwald                 channel->state = L2CAP_STATE_OPEN;
1930fa8473a4Smatthias.ringwald                 l2cap_emit_channel_opened(channel, 0);
1931c8e4258aSmatthias.ringwald             }
1932c8e4258aSmatthias.ringwald             break;
1933f62db1e3Smatthias.ringwald 
1934f62db1e3Smatthias.ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
1935f62db1e3Smatthias.ringwald             switch (code) {
1936f62db1e3Smatthias.ringwald                 case DISCONNECTION_RESPONSE:
193727a923d0Smatthias.ringwald                     l2cap_finialize_channel_close(channel);
193827a923d0Smatthias.ringwald                     break;
19395a67bd4aSmatthias.ringwald                 default:
19405a67bd4aSmatthias.ringwald                     //@TODO: implement other signaling packets
19415a67bd4aSmatthias.ringwald                     break;
194227a923d0Smatthias.ringwald             }
194327a923d0Smatthias.ringwald             break;
194484836b65Smatthias.ringwald 
194584836b65Smatthias.ringwald         case L2CAP_STATE_CLOSED:
194684836b65Smatthias.ringwald             // @TODO handle incoming requests
194784836b65Smatthias.ringwald             break;
194884836b65Smatthias.ringwald 
194984836b65Smatthias.ringwald         case L2CAP_STATE_OPEN:
195084836b65Smatthias.ringwald             //@TODO: implement other signaling packets, e.g. re-configure
195184836b65Smatthias.ringwald             break;
195210642e45Smatthias.ringwald         default:
195310642e45Smatthias.ringwald             break;
195427a923d0Smatthias.ringwald     }
19559da54300S[email protected]     // log_info("new state %u", channel->state);
195627a923d0Smatthias.ringwald }
195727a923d0Smatthias.ringwald 
195800d93d79Smatthias.ringwald 
19597f02f414SMatthias Ringwald static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
196000d93d79Smatthias.ringwald 
19611b9cb13dSMatthias Ringwald     btstack_linked_list_iterator_t it;
19621b9cb13dSMatthias Ringwald 
196300d93d79Smatthias.ringwald     // get code, signalind identifier and command len
196400d93d79Smatthias.ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
196500d93d79Smatthias.ringwald     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
196600d93d79Smatthias.ringwald 
19671b9cb13dSMatthias Ringwald     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
19681b9cb13dSMatthias Ringwald     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_RESPONSE){
1969e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
197000d93d79Smatthias.ringwald         return;
197100d93d79Smatthias.ringwald     }
197200d93d79Smatthias.ringwald 
197300d93d79Smatthias.ringwald     // general commands without an assigned channel
197400d93d79Smatthias.ringwald     switch(code) {
197500d93d79Smatthias.ringwald 
197600d93d79Smatthias.ringwald         case CONNECTION_REQUEST: {
1977f8fbdce0SMatthias Ringwald             uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1978f8fbdce0SMatthias Ringwald             uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
197900d93d79Smatthias.ringwald             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
19802b83fb7dSmatthias.ringwald             return;
198100d93d79Smatthias.ringwald         }
198200d93d79Smatthias.ringwald 
19832b360848Smatthias.ringwald         case ECHO_REQUEST:
1984e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
19852b83fb7dSmatthias.ringwald             return;
198600d93d79Smatthias.ringwald 
198700d93d79Smatthias.ringwald         case INFORMATION_REQUEST: {
1988f8fbdce0SMatthias Ringwald             uint16_t infoType = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1989e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, infoType);
19902b83fb7dSmatthias.ringwald             return;
199100d93d79Smatthias.ringwald         }
199200d93d79Smatthias.ringwald 
19931b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
19941b9cb13dSMatthias Ringwald         case INFORMATION_RESPONSE: {
19951b9cb13dSMatthias Ringwald             hci_connection_t * connection = hci_connection_for_handle(handle);
19961b9cb13dSMatthias Ringwald             if (!connection) return;
19971b9cb13dSMatthias Ringwald             uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
19981b9cb13dSMatthias Ringwald             uint16_t result =  little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
19991b9cb13dSMatthias Ringwald             if (result != 0) return;
2000543b84e4SMatthias Ringwald             if (info_type != 0x02) return;
20011b9cb13dSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
20021b9cb13dSMatthias Ringwald             connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2003543b84e4SMatthias Ringwald             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
20041b9cb13dSMatthias Ringwald             // trigger connection request
20051b9cb13dSMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
20061b9cb13dSMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
20071b9cb13dSMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2008543b84e4SMatthias Ringwald                 if (channel->con_handle != handle) continue;
2009543b84e4SMatthias Ringwald                 // bail if ERTM was requested but is not supported
2010543b84e4SMatthias Ringwald                 if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2011f073f086SMatthias Ringwald                     if (channel->ertm_mandatory){
2012543b84e4SMatthias Ringwald                         // channel closed
2013543b84e4SMatthias Ringwald                         channel->state = L2CAP_STATE_CLOSED;
2014543b84e4SMatthias Ringwald                         // map l2cap connection response result to BTstack status enumeration
2015543b84e4SMatthias Ringwald                         l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTD);
2016543b84e4SMatthias Ringwald                         // discard channel
2017543b84e4SMatthias Ringwald                         btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2018543b84e4SMatthias Ringwald                         btstack_memory_l2cap_channel_free(channel);
2019543b84e4SMatthias Ringwald                         continue;
2020f073f086SMatthias Ringwald                     } else {
2021f073f086SMatthias Ringwald                         // fallback to Basic mode
2022f073f086SMatthias Ringwald                         channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2023f073f086SMatthias Ringwald                     }
2024543b84e4SMatthias Ringwald                 }
2025543b84e4SMatthias Ringwald                 // start connecting
20261b9cb13dSMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
20271b9cb13dSMatthias Ringwald                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
20281b9cb13dSMatthias Ringwald                 }
202952606043SMatthias Ringwald                 // respond to connection request
203052606043SMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
203152606043SMatthias Ringwald                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
203252606043SMatthias Ringwald                     l2cap_emit_incoming_connection(channel);
203352606043SMatthias Ringwald                 }
20341b9cb13dSMatthias Ringwald             }
20351b9cb13dSMatthias Ringwald             return;
20361b9cb13dSMatthias Ringwald         }
20371b9cb13dSMatthias Ringwald #endif
20381b9cb13dSMatthias Ringwald 
203900d93d79Smatthias.ringwald         default:
204000d93d79Smatthias.ringwald             break;
204100d93d79Smatthias.ringwald     }
204200d93d79Smatthias.ringwald 
204300d93d79Smatthias.ringwald 
204400d93d79Smatthias.ringwald     // Get potential destination CID
2045f8fbdce0SMatthias Ringwald     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
204600d93d79Smatthias.ringwald 
204700d93d79Smatthias.ringwald     // Find channel for this sig_id and connection handle
2048665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2049665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2050665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2051fc64f94aSMatthias Ringwald         if (channel->con_handle != handle) continue;
205200d93d79Smatthias.ringwald         if (code & 1) {
2053b1988dceSmatthias.ringwald             // match odd commands (responses) by previous signaling identifier
2054b1988dceSmatthias.ringwald             if (channel->local_sig_id == sig_id) {
205500d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
20564e32727eSmatthias.ringwald                 break;
205700d93d79Smatthias.ringwald             }
205800d93d79Smatthias.ringwald         } else {
2059b1988dceSmatthias.ringwald             // match even commands (requests) by local channel id
206000d93d79Smatthias.ringwald             if (channel->local_cid == dest_cid) {
206100d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
20624e32727eSmatthias.ringwald                 break;
206300d93d79Smatthias.ringwald             }
206400d93d79Smatthias.ringwald         }
206500d93d79Smatthias.ringwald     }
206600d93d79Smatthias.ringwald }
206709e9d05bSMatthias Ringwald #endif
206800d93d79Smatthias.ringwald 
2069e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
207009e9d05bSMatthias Ringwald 
207109e9d05bSMatthias Ringwald static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
207209e9d05bSMatthias Ringwald     uint8_t event[6];
207309e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
207409e9d05bSMatthias Ringwald     event[1] = 4;
207509e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
207609e9d05bSMatthias Ringwald     little_endian_store_16(event, 4, result);
207709e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
207809e9d05bSMatthias Ringwald     if (!l2cap_event_packet_handler) return;
207909e9d05bSMatthias Ringwald     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
208009e9d05bSMatthias Ringwald }
208109e9d05bSMatthias Ringwald 
2082c48b2a2cSMatthias Ringwald // @returns valid
2083c48b2a2cSMatthias Ringwald static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
2084e7d0c9aaSMatthias Ringwald     hci_connection_t * connection;
2085c48b2a2cSMatthias Ringwald     uint16_t result;
2086c48b2a2cSMatthias Ringwald     uint8_t  event[10];
208783fd9c76SMatthias Ringwald 
2088cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2089a3dc965aSMatthias Ringwald     btstack_linked_list_iterator_t it;
2090a3dc965aSMatthias Ringwald     l2cap_channel_t * channel;
2091a3dc965aSMatthias Ringwald     uint16_t local_cid;
209283fd9c76SMatthias Ringwald     uint16_t le_psm;
209363f0ac45SMatthias Ringwald     uint16_t new_credits;
209463f0ac45SMatthias Ringwald     uint16_t credits_before;
2095e7d0c9aaSMatthias Ringwald     l2cap_service_t * service;
209611cae19eSMilanka Ringwald     uint16_t source_cid;
209783fd9c76SMatthias Ringwald #endif
209800d93d79Smatthias.ringwald 
20991b8b8d05SMatthias Ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
210023017473SMatthias Ringwald     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u", code, sig_id);
21011b8b8d05SMatthias Ringwald 
21021b8b8d05SMatthias Ringwald     switch (code){
210300d93d79Smatthias.ringwald 
2104c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
2105c48b2a2cSMatthias Ringwald             result = little_endian_read_16(command, 4);
2106ccf076adS[email protected]             l2cap_emit_connection_parameter_update_response(handle, result);
2107ccf076adS[email protected]             break;
2108da886c03S[email protected] 
2109c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_REQUEST:
2110e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
2111da886c03S[email protected]             if (connection){
21126d91fb6cSMatthias Ringwald                 if (connection->role != HCI_ROLE_MASTER){
21136d91fb6cSMatthias Ringwald                     // reject command without notifying upper layer when not in master role
2114c48b2a2cSMatthias Ringwald                     return 0;
21156d91fb6cSMatthias Ringwald                 }
2116da886c03S[email protected]                 int update_parameter = 1;
2117a4c06b28SMatthias Ringwald                 le_connection_parameter_range_t existing_range;
21184ced4e8cSMatthias Ringwald                 gap_get_connection_parameter_range(&existing_range);
2119c48b2a2cSMatthias Ringwald                 uint16_t le_conn_interval_min = little_endian_read_16(command,8);
2120c48b2a2cSMatthias Ringwald                 uint16_t le_conn_interval_max = little_endian_read_16(command,10);
2121c48b2a2cSMatthias Ringwald                 uint16_t le_conn_latency = little_endian_read_16(command,12);
2122c48b2a2cSMatthias Ringwald                 uint16_t le_supervision_timeout = little_endian_read_16(command,14);
2123da886c03S[email protected] 
2124da886c03S[email protected]                 if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
2125da886c03S[email protected]                 if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
2126da886c03S[email protected] 
2127da886c03S[email protected]                 if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
2128da886c03S[email protected]                 if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
2129da886c03S[email protected] 
2130da886c03S[email protected]                 if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
2131da886c03S[email protected]                 if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
2132da886c03S[email protected] 
2133da886c03S[email protected]                 if (update_parameter){
2134da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
2135da886c03S[email protected]                     connection->le_conn_interval_min = le_conn_interval_min;
2136da886c03S[email protected]                     connection->le_conn_interval_max = le_conn_interval_max;
2137da886c03S[email protected]                     connection->le_conn_latency = le_conn_latency;
2138da886c03S[email protected]                     connection->le_supervision_timeout = le_supervision_timeout;
2139da886c03S[email protected]                 } else {
2140da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
2141da886c03S[email protected]                 }
2142c48b2a2cSMatthias Ringwald                 connection->le_con_param_update_identifier = sig_id;
2143da886c03S[email protected]             }
2144da886c03S[email protected] 
214533c40538SMatthias Ringwald             if (!l2cap_event_packet_handler) break;
2146c48b2a2cSMatthias Ringwald 
2147c48b2a2cSMatthias Ringwald             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
2148c48b2a2cSMatthias Ringwald             event[1] = 8;
2149c48b2a2cSMatthias Ringwald             memcpy(&event[2], &command[4], 8);
2150c48b2a2cSMatthias Ringwald             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
215133c40538SMatthias Ringwald             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
2152ccf076adS[email protected]             break;
2153c48b2a2cSMatthias Ringwald 
2154a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2155a3dc965aSMatthias Ringwald 
215663f0ac45SMatthias Ringwald         case COMMAND_REJECT:
215763f0ac45SMatthias Ringwald             // Find channel for this sig_id and connection handle
215863f0ac45SMatthias Ringwald             channel = NULL;
215963f0ac45SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
216063f0ac45SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
216163f0ac45SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
216263f0ac45SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
216363f0ac45SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
216463f0ac45SMatthias Ringwald                 channel = a_channel;
216563f0ac45SMatthias Ringwald                 break;
216663f0ac45SMatthias Ringwald             }
216763f0ac45SMatthias Ringwald             if (!channel) break;
216863f0ac45SMatthias Ringwald 
216963f0ac45SMatthias Ringwald             // if received while waiting for le connection response, assume legacy device
217063f0ac45SMatthias Ringwald             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
217163f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
217263f0ac45SMatthias Ringwald                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
217344276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0x0002);
217463f0ac45SMatthias Ringwald 
217563f0ac45SMatthias Ringwald                 // discard channel
217663f0ac45SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
217763f0ac45SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
217863f0ac45SMatthias Ringwald                 break;
217963f0ac45SMatthias Ringwald             }
218063f0ac45SMatthias Ringwald             break;
218163f0ac45SMatthias Ringwald 
2182e7d0c9aaSMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_REQUEST:
2183e7d0c9aaSMatthias Ringwald 
2184e7d0c9aaSMatthias Ringwald             // get hci connection, bail if not found (must not happen)
2185e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
2186e7d0c9aaSMatthias Ringwald             if (!connection) return 0;
2187e7d0c9aaSMatthias Ringwald 
2188e7d0c9aaSMatthias Ringwald             // check if service registered
2189e7d0c9aaSMatthias Ringwald             le_psm  = little_endian_read_16(command, 4);
2190e7d0c9aaSMatthias Ringwald             service = l2cap_le_get_service(le_psm);
219111cae19eSMilanka Ringwald             source_cid = little_endian_read_16(command, 6);
2192e7d0c9aaSMatthias Ringwald 
2193e7d0c9aaSMatthias Ringwald             if (service){
2194e7d0c9aaSMatthias Ringwald                 if (source_cid < 0x40){
2195e7d0c9aaSMatthias Ringwald                     // 0x0009 Connection refused - Invalid Source CID
2196e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
2197e7d0c9aaSMatthias Ringwald                     return 1;
2198e7d0c9aaSMatthias Ringwald                 }
2199e7d0c9aaSMatthias Ringwald 
2200e7d0c9aaSMatthias Ringwald                 // go through list of channels for this ACL connection and check if we get a match
2201e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2202e7d0c9aaSMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&it)){
22031b8b8d05SMatthias Ringwald                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
22041b8b8d05SMatthias Ringwald                     if (a_channel->con_handle != handle) continue;
22051b8b8d05SMatthias Ringwald                     if (a_channel->remote_cid != source_cid) continue;
2206e7d0c9aaSMatthias Ringwald                     // 0x000a Connection refused - Source CID already allocated
2207e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
2208e7d0c9aaSMatthias Ringwald                     return 1;
2209e7d0c9aaSMatthias Ringwald                 }
2210e7d0c9aaSMatthias Ringwald 
221183fd9c76SMatthias Ringwald                 // security: check encryption
221283fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_2){
221383fd9c76SMatthias Ringwald                     if (sm_encryption_key_size(handle) == 0){
221483fd9c76SMatthias Ringwald                         // 0x0008 Connection refused - insufficient encryption
2215e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
221683fd9c76SMatthias Ringwald                         return 1;
221783fd9c76SMatthias Ringwald                     }
221883fd9c76SMatthias Ringwald                     // anything less than 16 byte key size is insufficient
221983fd9c76SMatthias Ringwald                     if (sm_encryption_key_size(handle) < 16){
222083fd9c76SMatthias Ringwald                         // 0x0007 Connection refused – insufficient encryption key size
2221e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
222283fd9c76SMatthias Ringwald                         return 1;
222383fd9c76SMatthias Ringwald                     }
222483fd9c76SMatthias Ringwald                 }
222583fd9c76SMatthias Ringwald 
222683fd9c76SMatthias Ringwald                 // security: check authencation
222783fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_3){
222883fd9c76SMatthias Ringwald                     if (!sm_authenticated(handle)){
222983fd9c76SMatthias Ringwald                         // 0x0005 Connection refused – insufficient authentication
2230e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
223183fd9c76SMatthias Ringwald                         return 1;
223283fd9c76SMatthias Ringwald                     }
223383fd9c76SMatthias Ringwald                 }
223483fd9c76SMatthias Ringwald 
223583fd9c76SMatthias Ringwald                 // security: check authorization
223683fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_4){
223783fd9c76SMatthias Ringwald                     if (sm_authorization_state(handle) != AUTHORIZATION_GRANTED){
223883fd9c76SMatthias Ringwald                         // 0x0006 Connection refused – insufficient authorization
2239e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
224083fd9c76SMatthias Ringwald                         return 1;
224183fd9c76SMatthias Ringwald                     }
224283fd9c76SMatthias Ringwald                 }
2243e7d0c9aaSMatthias Ringwald 
2244e7d0c9aaSMatthias Ringwald                 // allocate channel
22451b8b8d05SMatthias Ringwald                 channel = l2cap_create_channel_entry(service->packet_handler, connection->address,
2246e7d0c9aaSMatthias Ringwald                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
2247e7d0c9aaSMatthias Ringwald                 if (!channel){
2248e7d0c9aaSMatthias Ringwald                     // 0x0004 Connection refused – no resources available
2249e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2250e7d0c9aaSMatthias Ringwald                     return 1;
2251e7d0c9aaSMatthias Ringwald                 }
2252e7d0c9aaSMatthias Ringwald 
2253e7d0c9aaSMatthias Ringwald                 channel->con_handle = handle;
2254e7d0c9aaSMatthias Ringwald                 channel->remote_cid = source_cid;
2255e7d0c9aaSMatthias Ringwald                 channel->remote_sig_id = sig_id;
22567f107edaSMatthias Ringwald                 channel->remote_mtu = little_endian_read_16(command, 8);
22577f107edaSMatthias Ringwald                 channel->remote_mps = little_endian_read_16(command, 10);
22587f107edaSMatthias Ringwald                 channel->credits_outgoing = little_endian_read_16(command, 12);
2259e7d0c9aaSMatthias Ringwald 
2260e7d0c9aaSMatthias Ringwald                 // set initial state
2261e7d0c9aaSMatthias Ringwald                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2262c99bb618SMatthias Ringwald                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
2263e7d0c9aaSMatthias Ringwald 
2264e7d0c9aaSMatthias Ringwald                 // add to connections list
2265e7d0c9aaSMatthias Ringwald                 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2266e7d0c9aaSMatthias Ringwald 
2267e7d0c9aaSMatthias Ringwald                 // post connection request event
226844276248SMatthias Ringwald                 l2cap_emit_le_incoming_connection(channel);
2269e7d0c9aaSMatthias Ringwald 
2270e7d0c9aaSMatthias Ringwald             } else {
2271e7d0c9aaSMatthias Ringwald                 // Connection refused – LE_PSM not supported
2272e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2273e7d0c9aaSMatthias Ringwald             }
2274e7d0c9aaSMatthias Ringwald             break;
22751b8b8d05SMatthias Ringwald 
22761b8b8d05SMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
22771b8b8d05SMatthias Ringwald             // Find channel for this sig_id and connection handle
22781b8b8d05SMatthias Ringwald             channel = NULL;
22791b8b8d05SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
22801b8b8d05SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
22811b8b8d05SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
22821b8b8d05SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
22831b8b8d05SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
22841b8b8d05SMatthias Ringwald                 channel = a_channel;
22851b8b8d05SMatthias Ringwald                 break;
22861b8b8d05SMatthias Ringwald             }
22871b8b8d05SMatthias Ringwald             if (!channel) break;
22881b8b8d05SMatthias Ringwald 
22891b8b8d05SMatthias Ringwald             // cid + 0
22901b8b8d05SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
22911b8b8d05SMatthias Ringwald             if (result){
22921b8b8d05SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
22931b8b8d05SMatthias Ringwald                 // map l2cap connection response result to BTstack status enumeration
229444276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, result);
22951b8b8d05SMatthias Ringwald 
22961b8b8d05SMatthias Ringwald                 // discard channel
229763f0ac45SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
22981b8b8d05SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
22991b8b8d05SMatthias Ringwald                 break;
23001b8b8d05SMatthias Ringwald             }
23011b8b8d05SMatthias Ringwald 
23021b8b8d05SMatthias Ringwald             // success
23031b8b8d05SMatthias Ringwald             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
23041b8b8d05SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
23051b8b8d05SMatthias Ringwald             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
23061b8b8d05SMatthias Ringwald             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
23071b8b8d05SMatthias Ringwald             channel->state = L2CAP_STATE_OPEN;
230844276248SMatthias Ringwald             l2cap_emit_le_channel_opened(channel, result);
23091b8b8d05SMatthias Ringwald             break;
23101b8b8d05SMatthias Ringwald 
231185aeef60SMatthias Ringwald         case LE_FLOW_CONTROL_CREDIT:
231285aeef60SMatthias Ringwald             // find channel
231385aeef60SMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
231485aeef60SMatthias Ringwald             channel = l2cap_le_get_channel_for_local_cid(local_cid);
231563f0ac45SMatthias Ringwald             if (!channel) {
231663f0ac45SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
231763f0ac45SMatthias Ringwald                 break;
231863f0ac45SMatthias Ringwald             }
231963f0ac45SMatthias Ringwald             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
232063f0ac45SMatthias Ringwald             credits_before = channel->credits_outgoing;
232163f0ac45SMatthias Ringwald             channel->credits_outgoing += new_credits;
232263f0ac45SMatthias Ringwald             // check for credit overrun
232363f0ac45SMatthias Ringwald             if (credits_before > channel->credits_outgoing){
232463f0ac45SMatthias Ringwald                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
232563f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
232663f0ac45SMatthias Ringwald                 break;
232763f0ac45SMatthias Ringwald             }
232863f0ac45SMatthias Ringwald             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
232985aeef60SMatthias Ringwald             break;
233085aeef60SMatthias Ringwald 
2331828a7f7aSMatthias Ringwald         case DISCONNECTION_REQUEST:
2332828a7f7aSMatthias Ringwald             // find channel
2333828a7f7aSMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
2334828a7f7aSMatthias Ringwald             channel = l2cap_le_get_channel_for_local_cid(local_cid);
233563f34e00SMatthias Ringwald             if (!channel) {
233663f34e00SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
233763f34e00SMatthias Ringwald                 break;
233863f34e00SMatthias Ringwald             }
2339828a7f7aSMatthias Ringwald             channel->remote_sig_id = sig_id;
2340828a7f7aSMatthias Ringwald             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
2341828a7f7aSMatthias Ringwald             break;
2342828a7f7aSMatthias Ringwald 
2343a3dc965aSMatthias Ringwald #endif
2344a3dc965aSMatthias Ringwald 
234563f0ac45SMatthias Ringwald         case DISCONNECTION_RESPONSE:
234663f0ac45SMatthias Ringwald             break;
234763f0ac45SMatthias Ringwald 
2348c48b2a2cSMatthias Ringwald         default:
2349c48b2a2cSMatthias Ringwald             // command unknown -> reject command
2350c48b2a2cSMatthias Ringwald             return 0;
2351ccf076adS[email protected]     }
2352c48b2a2cSMatthias Ringwald     return 1;
2353c48b2a2cSMatthias Ringwald }
2354e7d0c9aaSMatthias Ringwald #endif
2355c48b2a2cSMatthias Ringwald 
2356c48b2a2cSMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size ){
23579ec2630cSMatthias Ringwald     UNUSED(packet_type);
23589ec2630cSMatthias Ringwald     UNUSED(channel);
2359c48b2a2cSMatthias Ringwald 
236009e9d05bSMatthias Ringwald     l2cap_channel_t * l2cap_channel;
2361f3963406SMatthias Ringwald     UNUSED(l2cap_channel);
236209e9d05bSMatthias Ringwald 
2363c48b2a2cSMatthias Ringwald     // Get Channel ID
2364c48b2a2cSMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
2365c48b2a2cSMatthias Ringwald     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
2366c48b2a2cSMatthias Ringwald 
2367c48b2a2cSMatthias Ringwald     switch (channel_id) {
2368c48b2a2cSMatthias Ringwald 
236909e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2370c48b2a2cSMatthias Ringwald         case L2CAP_CID_SIGNALING: {
2371c48b2a2cSMatthias Ringwald             uint16_t command_offset = 8;
2372c48b2a2cSMatthias Ringwald             while (command_offset < size) {
2373c48b2a2cSMatthias Ringwald                 // handle signaling commands
2374c48b2a2cSMatthias Ringwald                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
2375c48b2a2cSMatthias Ringwald 
2376c48b2a2cSMatthias Ringwald                 // increment command_offset
2377c48b2a2cSMatthias Ringwald                 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2378c48b2a2cSMatthias Ringwald             }
2379c48b2a2cSMatthias Ringwald             break;
2380c48b2a2cSMatthias Ringwald         }
238109e9d05bSMatthias Ringwald #endif
2382c48b2a2cSMatthias Ringwald 
2383e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
2384e7d0c9aaSMatthias Ringwald         case L2CAP_CID_SIGNALING_LE: {
2385e7d0c9aaSMatthias Ringwald             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
2386e7d0c9aaSMatthias Ringwald             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
2387c48b2a2cSMatthias Ringwald             if (!valid){
2388e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2389ccf076adS[email protected]             }
2390ccf076adS[email protected]             break;
2391e7d0c9aaSMatthias Ringwald         }
2392e7d0c9aaSMatthias Ringwald #endif
2393c48b2a2cSMatthias Ringwald 
2394c48b2a2cSMatthias Ringwald         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
2395c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback) {
2396c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2397ccf076adS[email protected]             }
2398c48b2a2cSMatthias Ringwald             break;
2399c48b2a2cSMatthias Ringwald 
2400c48b2a2cSMatthias Ringwald         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
2401c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback) {
2402c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2403c48b2a2cSMatthias Ringwald             }
2404c48b2a2cSMatthias Ringwald             break;
2405c48b2a2cSMatthias Ringwald 
2406c48b2a2cSMatthias Ringwald         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
2407c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback) {
2408c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2409c48b2a2cSMatthias Ringwald             }
2410c48b2a2cSMatthias Ringwald             break;
24111bbc0b23S[email protected] 
241209e9d05bSMatthias Ringwald         default:
241309e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
241400d93d79Smatthias.ringwald             // Find channel for this channel_id and connection handle
241564e11ca9SMatthias Ringwald             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
2416d1fd2a88SMatthias Ringwald             if (l2cap_channel) {
241727e0774aSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
241827e0774aSMatthias Ringwald                 if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
241927e0774aSMatthias Ringwald 
242027e0774aSMatthias Ringwald                     // verify FCS
242127e0774aSMatthias Ringwald                     uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
242227e0774aSMatthias Ringwald                     uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
242327e0774aSMatthias Ringwald                     log_info("Packet FCS 0x%04x, calculated FCS 0x%04x", fcs_packet, fcs_calculated);
242427e0774aSMatthias Ringwald                     if (fcs_calculated != fcs_packet){
242527e0774aSMatthias Ringwald                         log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
242627e0774aSMatthias Ringwald                         // TODO: trigger retransmission or something like that
242727e0774aSMatthias Ringwald                         break;
242827e0774aSMatthias Ringwald                     }
242927e0774aSMatthias Ringwald 
243027e0774aSMatthias Ringwald                     // switch on packet type
243127e0774aSMatthias Ringwald                     uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
2432*38f62777SMatthias Ringwald                     uint8_t  req_seq = (control >> 8) & 0x3f;
243327e0774aSMatthias Ringwald                     if (control & 1){
2434*38f62777SMatthias Ringwald                         // int poll = (control >> 7) & 0x01;
243527e0774aSMatthias Ringwald                         log_info("S-Frame not not implemented yet");
243627e0774aSMatthias Ringwald                         // S-Frame
243727e0774aSMatthias Ringwald                         break;
243827e0774aSMatthias Ringwald                     } else {
243927e0774aSMatthias Ringwald                         // I-Frame
244027e0774aSMatthias Ringwald                         // get control
244127e0774aSMatthias Ringwald                         l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
2442*38f62777SMatthias Ringwald                         uint8_t tx_seq = (control >> 1) & 0x3f;
2443*38f62777SMatthias Ringwald                         log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
2444*38f62777SMatthias Ringwald                         log_info("SAR: pos %u", l2cap_channel->rx_packets_state->pos);
2445*38f62777SMatthias Ringwald                         log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
2446*38f62777SMatthias Ringwald                         // check ordering
2447*38f62777SMatthias Ringwald                         if (l2cap_channel->expected_tx_seq == tx_seq){
2448*38f62777SMatthias Ringwald                             log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
2449*38f62777SMatthias Ringwald                             l2cap_channel->req_seq = tx_seq;
2450*38f62777SMatthias Ringwald                             l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
2451ed971c5aSMatthias Ringwald                             uint16_t sdu_length;
2452ed971c5aSMatthias Ringwald                             uint16_t segment_length;
2453ed971c5aSMatthias Ringwald                             uint16_t payload_offset;
245427e0774aSMatthias Ringwald                             switch (sar){
245527e0774aSMatthias Ringwald                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
2456ed971c5aSMatthias Ringwald                                     payload_offset = COMPLETE_L2CAP_HEADER+2;
2457ed971c5aSMatthias Ringwald                                     segment_length = payload_offset-2;
2458ed971c5aSMatthias Ringwald                                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER+2], segment_length);
245927e0774aSMatthias Ringwald                                     break;
246027e0774aSMatthias Ringwald                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
2461ed971c5aSMatthias Ringwald                                     // TODO: use current packet
2462ed971c5aSMatthias Ringwald                                     // TODO: check if reassembly started
2463ed971c5aSMatthias Ringwald                                     // TODO: check len against local mtu
2464ed971c5aSMatthias Ringwald                                     sdu_length = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER+2);
2465ed971c5aSMatthias Ringwald                                     payload_offset = COMPLETE_L2CAP_HEADER+4;
2466ed971c5aSMatthias Ringwald                                     segment_length = size - payload_offset-2;
2467ed971c5aSMatthias Ringwald                                     memcpy(&l2cap_channel->rx_packets_data[0], &packet[payload_offset], segment_length);
2468ed971c5aSMatthias Ringwald                                     l2cap_channel->rx_packets_state->sdu_length = sdu_length;
2469ed971c5aSMatthias Ringwald                                     l2cap_channel->rx_packets_state->pos = segment_length;
2470ed971c5aSMatthias Ringwald                                     break;
247127e0774aSMatthias Ringwald                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
2472ed971c5aSMatthias Ringwald                                     payload_offset = COMPLETE_L2CAP_HEADER+2;
2473ed971c5aSMatthias Ringwald                                     segment_length = size - payload_offset-2;
2474ed971c5aSMatthias Ringwald                                     memcpy(&l2cap_channel->rx_packets_data[l2cap_channel->rx_packets_state->pos], &packet[payload_offset], segment_length);
2475ed971c5aSMatthias Ringwald                                     l2cap_channel->rx_packets_state->pos += segment_length;
2476ed971c5aSMatthias Ringwald                                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->rx_packets_data, l2cap_channel->rx_packets_state[0].pos);
2477ed971c5aSMatthias Ringwald                                     break;
247827e0774aSMatthias Ringwald                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
2479ed971c5aSMatthias Ringwald                                     payload_offset = COMPLETE_L2CAP_HEADER+2;
2480ed971c5aSMatthias Ringwald                                     segment_length = size - payload_offset-2;
2481ed971c5aSMatthias Ringwald                                     memcpy(&l2cap_channel->rx_packets_data[l2cap_channel->rx_packets_state->pos], &packet[payload_offset], segment_length);
2482ed971c5aSMatthias Ringwald                                     l2cap_channel->rx_packets_state->pos += segment_length;
248327e0774aSMatthias Ringwald                                     break;
248427e0774aSMatthias Ringwald                                 }
248527e0774aSMatthias Ringwald                             }
2486*38f62777SMatthias Ringwald                         }
248727e0774aSMatthias Ringwald                     break;
248827e0774aSMatthias Ringwald                 }
248927e0774aSMatthias Ringwald #endif
24903d50b4baSMatthias Ringwald                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
249100d93d79Smatthias.ringwald             }
249209e9d05bSMatthias Ringwald #endif
2493a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
249464e11ca9SMatthias Ringwald             l2cap_channel = l2cap_le_get_channel_for_local_cid(channel_id);
249564e11ca9SMatthias Ringwald             if (l2cap_channel) {
249685aeef60SMatthias Ringwald                 // credit counting
249785aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming == 0){
249885aeef60SMatthias Ringwald                     log_error("LE Data Channel packet received but no incoming credits");
249985aeef60SMatthias Ringwald                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
250085aeef60SMatthias Ringwald                     break;
250185aeef60SMatthias Ringwald                 }
250285aeef60SMatthias Ringwald                 l2cap_channel->credits_incoming--;
250385aeef60SMatthias Ringwald 
250485aeef60SMatthias Ringwald                 // automatic credits
250585aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){
250685aeef60SMatthias Ringwald                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
250785aeef60SMatthias Ringwald                 }
250885aeef60SMatthias Ringwald 
2509cd529728SMatthias Ringwald                 // first fragment
2510cd529728SMatthias Ringwald                 uint16_t pos = 0;
2511cd529728SMatthias Ringwald                 if (!l2cap_channel->receive_sdu_len){
2512cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
2513cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_pos = 0;
2514cd529728SMatthias Ringwald                     pos  += 2;
2515cd529728SMatthias Ringwald                     size -= 2;
2516cd529728SMatthias Ringwald                 }
2517cd529728SMatthias Ringwald                 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], size-COMPLETE_L2CAP_HEADER);
2518cd529728SMatthias Ringwald                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
2519cd529728SMatthias Ringwald                 // done?
252063f0ac45SMatthias Ringwald                 log_info("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
2521cd529728SMatthias Ringwald                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
2522cd529728SMatthias Ringwald                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
2523cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = 0;
2524cd529728SMatthias Ringwald                 }
252563f0ac45SMatthias Ringwald             } else {
252663f0ac45SMatthias Ringwald                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
252764e11ca9SMatthias Ringwald             }
252864e11ca9SMatthias Ringwald #endif
25295652b5ffS[email protected]             break;
25305652b5ffS[email protected]     }
253100d93d79Smatthias.ringwald 
25321eb2563eS[email protected]     l2cap_run();
25332718e2e7Smatthias.ringwald }
253400d93d79Smatthias.ringwald 
253509e9d05bSMatthias Ringwald // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
253609e9d05bSMatthias Ringwald void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
253709e9d05bSMatthias Ringwald     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
253809e9d05bSMatthias Ringwald     if (index < 0) return;
253909e9d05bSMatthias Ringwald     fixed_channels[index].callback = the_packet_handler;
254009e9d05bSMatthias Ringwald }
254109e9d05bSMatthias Ringwald 
254209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
254315ec09bbSmatthias.ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
254427a923d0Smatthias.ringwald void l2cap_finialize_channel_close(l2cap_channel_t * channel){
2545f62db1e3Smatthias.ringwald     channel->state = L2CAP_STATE_CLOSED;
2546f62db1e3Smatthias.ringwald     l2cap_emit_channel_closed(channel);
2547f62db1e3Smatthias.ringwald     // discard channel
25489dcb2fb2S[email protected]     l2cap_stop_rtx(channel);
2549665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2550d3a9df87Smatthias.ringwald     btstack_memory_l2cap_channel_free(channel);
2551c8e4258aSmatthias.ringwald }
25521e6aba47Smatthias.ringwald 
25538f2a52f4SMatthias Ringwald static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
2554665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
2555665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, services);
2556665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2557665d90f2SMatthias Ringwald         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
25589d9bbc01Smatthias.ringwald         if ( service->psm == psm){
25599d9bbc01Smatthias.ringwald             return service;
25609d9bbc01Smatthias.ringwald         };
25619d9bbc01Smatthias.ringwald     }
25629d9bbc01Smatthias.ringwald     return NULL;
25639d9bbc01Smatthias.ringwald }
25649d9bbc01Smatthias.ringwald 
25657192e786SMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
25667192e786SMatthias Ringwald     return l2cap_get_service_internal(&l2cap_services, psm);
25677192e786SMatthias Ringwald }
25687192e786SMatthias Ringwald 
2569e0abb8e7S[email protected] 
2570be2053a6SMatthias 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){
2571be2053a6SMatthias Ringwald 
2572be2053a6SMatthias Ringwald     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
2573e0abb8e7S[email protected] 
25744bb582b6Smatthias.ringwald     // check for alread registered psm
25759d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
2576277abc2cSmatthias.ringwald     if (service) {
2577be2053a6SMatthias Ringwald         log_error("l2cap_register_service: PSM %u already registered", psm);
2578be2053a6SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
2579277abc2cSmatthias.ringwald     }
25809d9bbc01Smatthias.ringwald 
25814bb582b6Smatthias.ringwald     // alloc structure
2582bb69aaaeS[email protected]     service = btstack_memory_l2cap_service_get();
2583277abc2cSmatthias.ringwald     if (!service) {
2584be2053a6SMatthias Ringwald         log_error("l2cap_register_service: no memory for l2cap_service_t");
2585be2053a6SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
2586277abc2cSmatthias.ringwald     }
25879d9bbc01Smatthias.ringwald 
25889d9bbc01Smatthias.ringwald     // fill in
25899d9bbc01Smatthias.ringwald     service->psm = psm;
25909d9bbc01Smatthias.ringwald     service->mtu = mtu;
259105ae8de3SMatthias Ringwald     service->packet_handler = service_packet_handler;
2592df3354fcS[email protected]     service->required_security_level = security_level;
25939d9bbc01Smatthias.ringwald 
25949d9bbc01Smatthias.ringwald     // add to services list
2595665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
2596c0e866bfSmatthias.ringwald 
2597c0e866bfSmatthias.ringwald     // enable page scan
259815a95bd5SMatthias Ringwald     gap_connectable_control(1);
25995842b6d9Smatthias.ringwald 
2600be2053a6SMatthias Ringwald     return 0;
26019d9bbc01Smatthias.ringwald }
26029d9bbc01Smatthias.ringwald 
26037e8856ebSMatthias Ringwald uint8_t l2cap_unregister_service(uint16_t psm){
2604e0abb8e7S[email protected] 
2605e0abb8e7S[email protected]     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
2606e0abb8e7S[email protected] 
26079d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
26087e8856ebSMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2609665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
2610d3a9df87Smatthias.ringwald     btstack_memory_l2cap_service_free(service);
2611c0e866bfSmatthias.ringwald 
2612c0e866bfSmatthias.ringwald     // disable page scan when no services registered
26137e8856ebSMatthias Ringwald     if (btstack_linked_list_empty(&l2cap_services)) {
261415a95bd5SMatthias Ringwald         gap_connectable_control(0);
26159d9bbc01Smatthias.ringwald     }
26167e8856ebSMatthias Ringwald     return 0;
26177e8856ebSMatthias Ringwald }
261809e9d05bSMatthias Ringwald #endif
26199d9bbc01Smatthias.ringwald 
26207192e786SMatthias Ringwald 
2621cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
262283fd9c76SMatthias Ringwald 
262357be49d6SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
262457be49d6SMatthias Ringwald     if (!channel->waiting_for_can_send_now) return;
262557be49d6SMatthias Ringwald     if (channel->send_sdu_buffer) return;
262657be49d6SMatthias Ringwald     channel->waiting_for_can_send_now = 0;
262757be49d6SMatthias Ringwald     log_info("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
262857be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
262957be49d6SMatthias Ringwald }
263057be49d6SMatthias Ringwald 
263157be49d6SMatthias Ringwald // 1BH2222
263257be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
263357be49d6SMatthias 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",
263457be49d6SMatthias Ringwald              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
263557be49d6SMatthias Ringwald     uint8_t event[19];
263657be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
263757be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
263857be49d6SMatthias Ringwald     event[2] = channel->address_type;
263957be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
264057be49d6SMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
264157be49d6SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
264257be49d6SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
264357be49d6SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
264457be49d6SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_mtu);
264557be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
264657be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
264757be49d6SMatthias Ringwald }
264857be49d6SMatthias Ringwald // 11BH22222
264957be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
265057be49d6SMatthias 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",
265157be49d6SMatthias Ringwald              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
265257be49d6SMatthias Ringwald              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
2653c99bb618SMatthias Ringwald     uint8_t event[23];
265457be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
265557be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
265657be49d6SMatthias Ringwald     event[2] = status;
265757be49d6SMatthias Ringwald     event[3] = channel->address_type;
265857be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[4]);
265957be49d6SMatthias Ringwald     little_endian_store_16(event, 10, channel->con_handle);
2660c99bb618SMatthias Ringwald     event[12] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
2661c99bb618SMatthias Ringwald     little_endian_store_16(event, 13, channel->psm);
2662c99bb618SMatthias Ringwald     little_endian_store_16(event, 15, channel->local_cid);
2663c99bb618SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_cid);
2664c99bb618SMatthias Ringwald     little_endian_store_16(event, 19, channel->local_mtu);
2665c99bb618SMatthias Ringwald     little_endian_store_16(event, 21, channel->remote_mtu);
266657be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
266757be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
266857be49d6SMatthias Ringwald }
266957be49d6SMatthias Ringwald 
267057be49d6SMatthias Ringwald static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid){
267157be49d6SMatthias Ringwald     btstack_linked_list_iterator_t it;
267257be49d6SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
267357be49d6SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
267457be49d6SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
267557be49d6SMatthias Ringwald         if ( channel->local_cid == local_cid) {
267657be49d6SMatthias Ringwald             return channel;
267757be49d6SMatthias Ringwald         }
267857be49d6SMatthias Ringwald     }
267957be49d6SMatthias Ringwald     return NULL;
268057be49d6SMatthias Ringwald }
268157be49d6SMatthias Ringwald 
268257be49d6SMatthias Ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
268357be49d6SMatthias Ringwald void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
268457be49d6SMatthias Ringwald     channel->state = L2CAP_STATE_CLOSED;
268557be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
268657be49d6SMatthias Ringwald     // discard channel
268757be49d6SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
268857be49d6SMatthias Ringwald     btstack_memory_l2cap_channel_free(channel);
268957be49d6SMatthias Ringwald }
269057be49d6SMatthias Ringwald 
2691e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
2692e7d0c9aaSMatthias Ringwald     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
26937192e786SMatthias Ringwald }
2694efedfb4cSMatthias Ringwald 
2695da144af5SMatthias Ringwald uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
26967192e786SMatthias Ringwald 
2697da144af5SMatthias Ringwald     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
26987192e786SMatthias Ringwald 
26997192e786SMatthias Ringwald     // check for alread registered psm
27007192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
27017192e786SMatthias Ringwald     if (service) {
2702da144af5SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
27037192e786SMatthias Ringwald     }
27047192e786SMatthias Ringwald 
27057192e786SMatthias Ringwald     // alloc structure
27067192e786SMatthias Ringwald     service = btstack_memory_l2cap_service_get();
27077192e786SMatthias Ringwald     if (!service) {
27087192e786SMatthias Ringwald         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
2709da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
27107192e786SMatthias Ringwald     }
27117192e786SMatthias Ringwald 
27127192e786SMatthias Ringwald     // fill in
27137192e786SMatthias Ringwald     service->psm = psm;
2714da144af5SMatthias Ringwald     service->mtu = 0;
27157192e786SMatthias Ringwald     service->packet_handler = packet_handler;
27167192e786SMatthias Ringwald     service->required_security_level = security_level;
27177192e786SMatthias Ringwald 
27187192e786SMatthias Ringwald     // add to services list
2719665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
27207192e786SMatthias Ringwald 
27217192e786SMatthias Ringwald     // done
2722da144af5SMatthias Ringwald     return 0;
27237192e786SMatthias Ringwald }
27247192e786SMatthias Ringwald 
2725da144af5SMatthias Ringwald uint8_t l2cap_le_unregister_service(uint16_t psm) {
27267192e786SMatthias Ringwald     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
27277192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
27289367f9b0SMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2729da144af5SMatthias Ringwald 
2730665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
27317192e786SMatthias Ringwald     btstack_memory_l2cap_service_free(service);
2732da144af5SMatthias Ringwald     return 0;
27337192e786SMatthias Ringwald }
2734da144af5SMatthias Ringwald 
2735da144af5SMatthias Ringwald uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
2736e7d0c9aaSMatthias Ringwald     // get channel
2737e7d0c9aaSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2738e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2739e7d0c9aaSMatthias Ringwald 
2740e7d0c9aaSMatthias Ringwald     // validate state
2741e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2742e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
2743e7d0c9aaSMatthias Ringwald     }
2744e7d0c9aaSMatthias Ringwald 
2745efedfb4cSMatthias Ringwald     // set state accept connection
274623017473SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
274723017473SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
274823017473SMatthias Ringwald     channel->local_mtu = mtu;
274985aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
275085aeef60SMatthias Ringwald     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
275185aeef60SMatthias Ringwald 
275285aeef60SMatthias Ringwald     // test
275363f0ac45SMatthias Ringwald     // channel->new_credits_incoming = 1;
2754e7d0c9aaSMatthias Ringwald 
2755e7d0c9aaSMatthias Ringwald     // go
2756e7d0c9aaSMatthias Ringwald     l2cap_run();
2757da144af5SMatthias Ringwald     return 0;
2758da144af5SMatthias Ringwald }
2759da144af5SMatthias Ringwald 
2760da144af5SMatthias Ringwald /**
2761da144af5SMatthias Ringwald  * @brief Deny incoming LE Data Channel connection due to resource constraints
2762da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2763da144af5SMatthias Ringwald  */
2764da144af5SMatthias Ringwald 
2765da144af5SMatthias Ringwald uint8_t l2cap_le_decline_connection(uint16_t local_cid){
2766e7d0c9aaSMatthias Ringwald     // get channel
2767e7d0c9aaSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2768e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2769e7d0c9aaSMatthias Ringwald 
2770e7d0c9aaSMatthias Ringwald     // validate state
2771e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2772e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
2773e7d0c9aaSMatthias Ringwald     }
2774e7d0c9aaSMatthias Ringwald 
2775efedfb4cSMatthias Ringwald     // set state decline connection
2776e7d0c9aaSMatthias Ringwald     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
2777e7d0c9aaSMatthias Ringwald     channel->reason = 0x04; // no resources available
2778e7d0c9aaSMatthias Ringwald     l2cap_run();
2779da144af5SMatthias Ringwald     return 0;
2780da144af5SMatthias Ringwald }
2781da144af5SMatthias Ringwald 
27827dafa750SMatthias Ringwald uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
2783da144af5SMatthias Ringwald     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
2784efedfb4cSMatthias Ringwald     uint16_t * out_local_cid) {
2785efedfb4cSMatthias Ringwald 
27867dafa750SMatthias Ringwald     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
2787da144af5SMatthias Ringwald 
27887dafa750SMatthias Ringwald 
27897dafa750SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
27907dafa750SMatthias Ringwald     if (!connection) {
27917dafa750SMatthias Ringwald         log_error("no hci_connection for handle 0x%04x", con_handle);
27927dafa750SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
27937dafa750SMatthias Ringwald     }
27947dafa750SMatthias Ringwald 
27957dafa750SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, connection->address, connection->address_type, psm, mtu, security_level);
2796da144af5SMatthias Ringwald     if (!channel) {
2797da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
2798da144af5SMatthias Ringwald     }
2799e7d0c9aaSMatthias Ringwald     log_info("l2cap_le_create_channel %p", channel);
2800da144af5SMatthias Ringwald 
2801da144af5SMatthias Ringwald     // store local_cid
2802da144af5SMatthias Ringwald     if (out_local_cid){
2803da144af5SMatthias Ringwald        *out_local_cid = channel->local_cid;
2804da144af5SMatthias Ringwald     }
2805da144af5SMatthias Ringwald 
28067dafa750SMatthias Ringwald     // provide buffer
28077dafa750SMatthias Ringwald     channel->con_handle = con_handle;
2808cd529728SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
28097dafa750SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
281085aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
281185aeef60SMatthias Ringwald     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
281285aeef60SMatthias Ringwald 
2813efedfb4cSMatthias Ringwald     // add to connections list
2814efedfb4cSMatthias Ringwald     btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2815efedfb4cSMatthias Ringwald 
28167dafa750SMatthias Ringwald     // go
281763f0ac45SMatthias Ringwald     l2cap_run();
2818da144af5SMatthias Ringwald     return 0;
2819da144af5SMatthias Ringwald }
2820da144af5SMatthias Ringwald 
2821da144af5SMatthias Ringwald /**
2822da144af5SMatthias Ringwald  * @brief Provide credtis for LE Data Channel
2823da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2824da144af5SMatthias Ringwald  * @param credits               Number additional credits for peer
2825da144af5SMatthias Ringwald  */
282664e11ca9SMatthias Ringwald uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
282763f0ac45SMatthias Ringwald 
282863f0ac45SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
282963f0ac45SMatthias Ringwald     if (!channel) {
283063f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
283163f0ac45SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
283263f0ac45SMatthias Ringwald     }
283363f0ac45SMatthias Ringwald 
2834efedfb4cSMatthias Ringwald     // check state
283563f0ac45SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN){
283663f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
283763f0ac45SMatthias Ringwald     }
283863f0ac45SMatthias Ringwald 
283963f0ac45SMatthias Ringwald     // assert incoming credits + credits <= 0xffff
284063f0ac45SMatthias Ringwald     uint32_t total_credits = channel->credits_incoming;
284163f0ac45SMatthias Ringwald     total_credits += channel->new_credits_incoming;
284263f0ac45SMatthias Ringwald     total_credits += credits;
284363f0ac45SMatthias Ringwald     if (total_credits > 0xffff){
284463f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
284563f0ac45SMatthias Ringwald             channel->new_credits_incoming, credits);
284663f0ac45SMatthias Ringwald     }
284763f0ac45SMatthias Ringwald 
2848efedfb4cSMatthias Ringwald     // set credits_granted
284963f0ac45SMatthias Ringwald     channel->new_credits_incoming += credits;
285063f0ac45SMatthias Ringwald 
285163f0ac45SMatthias Ringwald     // go
285263f0ac45SMatthias Ringwald     l2cap_run();
2853da144af5SMatthias Ringwald     return 0;
2854da144af5SMatthias Ringwald }
2855da144af5SMatthias Ringwald 
2856da144af5SMatthias Ringwald /**
2857da144af5SMatthias Ringwald  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
2858da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2859da144af5SMatthias Ringwald  */
286064e11ca9SMatthias Ringwald int l2cap_le_can_send_now(uint16_t local_cid){
286144276248SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
286244276248SMatthias Ringwald     if (!channel) {
286344276248SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
2864da144af5SMatthias Ringwald         return 0;
2865da144af5SMatthias Ringwald     }
2866da144af5SMatthias Ringwald 
286744276248SMatthias Ringwald     // check state
286844276248SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN) return 0;
286944276248SMatthias Ringwald 
287044276248SMatthias Ringwald     // check queue
287144276248SMatthias Ringwald     if (channel->send_sdu_buffer) return 0;
287244276248SMatthias Ringwald 
287344276248SMatthias Ringwald     // fine, go ahead
287444276248SMatthias Ringwald     return 1;
287544276248SMatthias Ringwald }
287644276248SMatthias Ringwald 
2877da144af5SMatthias Ringwald /**
2878da144af5SMatthias Ringwald  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
2879da144af5SMatthias Ringwald  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
2880da144af5SMatthias Ringwald  *       so packet handler should be ready to handle it
2881da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2882da144af5SMatthias Ringwald  */
288364e11ca9SMatthias Ringwald uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
288444276248SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
288544276248SMatthias Ringwald     if (!channel) {
288644276248SMatthias Ringwald         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
288744276248SMatthias Ringwald         return 0;
288844276248SMatthias Ringwald     }
288944276248SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
289044276248SMatthias Ringwald     l2cap_le_notify_channel_can_send(channel);
2891da144af5SMatthias Ringwald     return 0;
2892da144af5SMatthias Ringwald }
2893da144af5SMatthias Ringwald 
2894da144af5SMatthias Ringwald /**
2895da144af5SMatthias Ringwald  * @brief Send data via LE Data Channel
2896da144af5SMatthias Ringwald  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
2897da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2898da144af5SMatthias Ringwald  * @param data                  data to send
2899da144af5SMatthias Ringwald  * @param size                  data size
2900da144af5SMatthias Ringwald  */
290164e11ca9SMatthias Ringwald uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
290264e11ca9SMatthias Ringwald 
290364e11ca9SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
290464e11ca9SMatthias Ringwald     if (!channel) {
290564e11ca9SMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
2906828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
290764e11ca9SMatthias Ringwald     }
290864e11ca9SMatthias Ringwald 
290964e11ca9SMatthias Ringwald     if (len > channel->remote_mtu){
291064e11ca9SMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
291164e11ca9SMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
291264e11ca9SMatthias Ringwald     }
291364e11ca9SMatthias Ringwald 
29147f107edaSMatthias Ringwald     if (channel->send_sdu_buffer){
291564e11ca9SMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
291664e11ca9SMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
291764e11ca9SMatthias Ringwald     }
291864e11ca9SMatthias Ringwald 
29197f107edaSMatthias Ringwald     channel->send_sdu_buffer = data;
29207f107edaSMatthias Ringwald     channel->send_sdu_len    = len;
29217f107edaSMatthias Ringwald     channel->send_sdu_pos    = 0;
292264e11ca9SMatthias Ringwald 
29237f107edaSMatthias Ringwald     l2cap_run();
29247f107edaSMatthias Ringwald     return 0;
2925da144af5SMatthias Ringwald }
2926da144af5SMatthias Ringwald 
2927da144af5SMatthias Ringwald /**
2928da144af5SMatthias Ringwald  * @brief Disconnect from LE Data Channel
2929da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2930da144af5SMatthias Ringwald  */
2931828a7f7aSMatthias Ringwald uint8_t l2cap_le_disconnect(uint16_t local_cid)
2932da144af5SMatthias Ringwald {
2933828a7f7aSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2934828a7f7aSMatthias Ringwald     if (!channel) {
2935828a7f7aSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
2936828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2937828a7f7aSMatthias Ringwald     }
2938828a7f7aSMatthias Ringwald 
2939828a7f7aSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2940828a7f7aSMatthias Ringwald     l2cap_run();
2941da144af5SMatthias Ringwald     return 0;
2942da144af5SMatthias Ringwald }
2943da144af5SMatthias Ringwald 
29447f02f414SMatthias Ringwald #endif
2945