xref: /btstack/src/l2cap.c (revision f0fb4cd727a7cb54eb1a1c2b1dc9efdf67d42fde)
143625864Smatthias.ringwald /*
2a0c35809S[email protected]  * Copyright (C) 2014 BlueKitchen GmbH
31713bceaSmatthias.ringwald  *
41713bceaSmatthias.ringwald  * Redistribution and use in source and binary forms, with or without
51713bceaSmatthias.ringwald  * modification, are permitted provided that the following conditions
61713bceaSmatthias.ringwald  * are met:
71713bceaSmatthias.ringwald  *
81713bceaSmatthias.ringwald  * 1. Redistributions of source code must retain the above copyright
91713bceaSmatthias.ringwald  *    notice, this list of conditions and the following disclaimer.
101713bceaSmatthias.ringwald  * 2. Redistributions in binary form must reproduce the above copyright
111713bceaSmatthias.ringwald  *    notice, this list of conditions and the following disclaimer in the
121713bceaSmatthias.ringwald  *    documentation and/or other materials provided with the distribution.
131713bceaSmatthias.ringwald  * 3. Neither the name of the copyright holders nor the names of
141713bceaSmatthias.ringwald  *    contributors may be used to endorse or promote products derived
151713bceaSmatthias.ringwald  *    from this software without specific prior written permission.
166b64433eSmatthias.ringwald  * 4. Any redistribution, use, or modification is done solely for
176b64433eSmatthias.ringwald  *    personal benefit and not for any commercial purpose or for
186b64433eSmatthias.ringwald  *    monetary gain.
191713bceaSmatthias.ringwald  *
20a0c35809S[email protected]  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
211713bceaSmatthias.ringwald  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
221713bceaSmatthias.ringwald  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
231713bceaSmatthias.ringwald  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
241713bceaSmatthias.ringwald  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
251713bceaSmatthias.ringwald  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
261713bceaSmatthias.ringwald  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
271713bceaSmatthias.ringwald  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
281713bceaSmatthias.ringwald  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
291713bceaSmatthias.ringwald  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
301713bceaSmatthias.ringwald  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
311713bceaSmatthias.ringwald  * SUCH DAMAGE.
321713bceaSmatthias.ringwald  *
33a0c35809S[email protected]  * Please inquire about commercial licensing options at
34a0c35809S[email protected]  * [email protected]
356b64433eSmatthias.ringwald  *
361713bceaSmatthias.ringwald  */
371713bceaSmatthias.ringwald 
38ab2c6ae4SMatthias Ringwald #define __BTSTACK_FILE__ "l2cap.c"
39ab2c6ae4SMatthias Ringwald 
401713bceaSmatthias.ringwald /*
4143625864Smatthias.ringwald  *  l2cap.c
4243625864Smatthias.ringwald  *
4343625864Smatthias.ringwald  *  Logical Link Control and Adaption Protocl (L2CAP)
4443625864Smatthias.ringwald  *
4543625864Smatthias.ringwald  *  Created by Matthias Ringwald on 5/16/09.
4643625864Smatthias.ringwald  */
4743625864Smatthias.ringwald 
4843625864Smatthias.ringwald #include "l2cap.h"
49645658c9Smatthias.ringwald #include "hci.h"
502b3c6c9bSmatthias.ringwald #include "hci_dump.h"
51235946f1SMatthias Ringwald #include "bluetooth_sdp.h"
5216ece135SMatthias Ringwald #include "btstack_debug.h"
530e2df43fSMatthias Ringwald #include "btstack_event.h"
54d3a9df87Smatthias.ringwald #include "btstack_memory.h"
5543625864Smatthias.ringwald 
56cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
5783fd9c76SMatthias Ringwald #include "ble/sm.h"
5883fd9c76SMatthias Ringwald #endif
5983fd9c76SMatthias Ringwald 
6043625864Smatthias.ringwald #include <stdarg.h>
6143625864Smatthias.ringwald #include <string.h>
6243625864Smatthias.ringwald 
6343625864Smatthias.ringwald #include <stdio.h>
6443625864Smatthias.ringwald 
654c744e21Smatthias.ringwald // nr of buffered acl packets in outgoing queue to get max performance
664c744e21Smatthias.ringwald #define NR_BUFFERED_ACL_PACKETS 3
674c744e21Smatthias.ringwald 
6839bda6d5Smatthias.ringwald // used to cache l2cap rejects, echo, and informational requests
69e16a9cacSmatthias.ringwald #define NR_PENDING_SIGNALING_RESPONSES 3
7039bda6d5Smatthias.ringwald 
7185aeef60SMatthias Ringwald // nr of credits provided to remote if credits fall below watermark
7285aeef60SMatthias Ringwald #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK 5
7385aeef60SMatthias Ringwald #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT 5
7485aeef60SMatthias Ringwald 
7500d93d79Smatthias.ringwald // offsets for L2CAP SIGNALING COMMANDS
7600d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
7700d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
7800d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
7900d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
8000d93d79Smatthias.ringwald 
815628cf69SMatthias Ringwald // internal table
825628cf69SMatthias Ringwald #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL 0
835628cf69SMatthias Ringwald #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL  1
845628cf69SMatthias Ringwald #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL 2
855628cf69SMatthias Ringwald #define L2CAP_FIXED_CHANNEL_TABLE_SIZE (L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL+1)
865628cf69SMatthias Ringwald 
8709e9d05bSMatthias Ringwald #if defined(ENABLE_LE_DATA_CHANNELS) || defined(ENABLE_CLASSIC)
8809e9d05bSMatthias Ringwald #define L2CAP_USES_CHANNELS
8909e9d05bSMatthias Ringwald #endif
9009e9d05bSMatthias Ringwald 
9133c40538SMatthias Ringwald // prototypes
9233c40538SMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
933d50b4baSMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size );
9430725612SMatthias Ringwald static void l2cap_notify_channel_can_send(void);
9509e9d05bSMatthias Ringwald static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel);
9609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
9709e9d05bSMatthias Ringwald static void l2cap_finialize_channel_close(l2cap_channel_t *channel);
9809e9d05bSMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm);
9909e9d05bSMatthias Ringwald static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
10009e9d05bSMatthias Ringwald static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
10109e9d05bSMatthias Ringwald static void l2cap_emit_incoming_connection(l2cap_channel_t *channel);
10209e9d05bSMatthias Ringwald static int  l2cap_channel_ready_for_open(l2cap_channel_t *channel);
10309e9d05bSMatthias Ringwald #endif
104cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
10557be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status);
10657be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel);
10757be49d6SMatthias Ringwald static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid);
10844276248SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel);
109828a7f7aSMatthias Ringwald static void l2cap_le_finialize_channel_close(l2cap_channel_t *channel);
110e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t psm);
111e7d0c9aaSMatthias Ringwald #endif
11233c40538SMatthias Ringwald 
1135628cf69SMatthias Ringwald typedef struct l2cap_fixed_channel {
1145628cf69SMatthias Ringwald     btstack_packet_handler_t callback;
1152125de09SMatthias Ringwald     uint8_t waiting_for_can_send_now;
1165628cf69SMatthias Ringwald } l2cap_fixed_channel_t;
1175628cf69SMatthias Ringwald 
11809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1195628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_channels;
1205628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_services;
12109e9d05bSMatthias Ringwald static uint8_t require_security_level2_for_outgoing_sdp;
12209e9d05bSMatthias Ringwald #endif
12357be49d6SMatthias Ringwald 
12457be49d6SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1255628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_le_channels;
1265628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_le_services;
12757be49d6SMatthias Ringwald #endif
12839bda6d5Smatthias.ringwald 
12939bda6d5Smatthias.ringwald // used to cache l2cap rejects, echo, and informational requests
1302b83fb7dSmatthias.ringwald static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
1312b83fb7dSmatthias.ringwald static int signaling_responses_pending;
1322b83fb7dSmatthias.ringwald 
133fb37a842SMatthias Ringwald static btstack_packet_callback_registration_t hci_event_callback_registration;
1345628cf69SMatthias Ringwald static l2cap_fixed_channel_t fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_SIZE];
13539bda6d5Smatthias.ringwald 
136d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
137d6ed9f9cSMatthias Ringwald // only used for connection parameter update events
138d6ed9f9cSMatthias Ringwald static btstack_packet_handler_t l2cap_event_packet_handler;
139d6ed9f9cSMatthias Ringwald #endif
140d6ed9f9cSMatthias Ringwald 
14185ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
14285ddcd84SMatthias Ringwald 
14385ddcd84SMatthias Ringwald /*
14485ddcd84SMatthias Ringwald  * CRC lookup table for generator polynom D^16 + D^15 + D^2 + 1
14585ddcd84SMatthias Ringwald  */
14685ddcd84SMatthias Ringwald static const uint16_t crc16_table[256] = {
14785ddcd84SMatthias Ringwald     0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
14885ddcd84SMatthias Ringwald     0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841,
14985ddcd84SMatthias Ringwald     0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41,
15085ddcd84SMatthias Ringwald     0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040,
15185ddcd84SMatthias Ringwald     0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441,
15285ddcd84SMatthias Ringwald     0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840,
15385ddcd84SMatthias Ringwald     0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40,
15485ddcd84SMatthias Ringwald     0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041,
15585ddcd84SMatthias Ringwald     0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
15685ddcd84SMatthias Ringwald     0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840,
15785ddcd84SMatthias Ringwald     0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
15885ddcd84SMatthias Ringwald     0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041,
15985ddcd84SMatthias Ringwald     0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440,
16085ddcd84SMatthias Ringwald     0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841,
16185ddcd84SMatthias Ringwald     0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41,
16285ddcd84SMatthias Ringwald     0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040,
16385ddcd84SMatthias Ringwald };
16485ddcd84SMatthias Ringwald 
16585ddcd84SMatthias Ringwald static uint16_t crc16_calc(uint8_t * data, uint16_t len){
16685ddcd84SMatthias Ringwald     uint16_t crc = 0;   // initial value = 0
16785ddcd84SMatthias Ringwald     while (len--){
16885ddcd84SMatthias Ringwald         crc = (crc >> 8) ^ crc16_table[ (crc ^ ((uint16_t) *data++)) & 0x00FF ];
16985ddcd84SMatthias Ringwald     }
17085ddcd84SMatthias Ringwald     return crc;
17185ddcd84SMatthias Ringwald }
17285ddcd84SMatthias Ringwald 
17385ddcd84SMatthias Ringwald #endif
17485ddcd84SMatthias Ringwald 
17585ddcd84SMatthias Ringwald 
17634e7e577SMatthias Ringwald static uint16_t l2cap_fixed_channel_table_channel_id_for_index(int index){
17734e7e577SMatthias Ringwald     switch (index){
17834e7e577SMatthias Ringwald         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL:
17934e7e577SMatthias Ringwald             return L2CAP_CID_ATTRIBUTE_PROTOCOL;
18034e7e577SMatthias Ringwald         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL:
18134e7e577SMatthias Ringwald             return L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
18234e7e577SMatthias Ringwald         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL:
18334e7e577SMatthias Ringwald             return L2CAP_CID_CONNECTIONLESS_CHANNEL;
18434e7e577SMatthias Ringwald         default:
18534e7e577SMatthias Ringwald             return 0;
18634e7e577SMatthias Ringwald     }
18734e7e577SMatthias Ringwald }
1885628cf69SMatthias Ringwald static int l2cap_fixed_channel_table_index_for_channel_id(uint16_t channel_id){
1895628cf69SMatthias Ringwald     switch (channel_id){
1905628cf69SMatthias Ringwald         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
1915628cf69SMatthias Ringwald             return L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL;
1925628cf69SMatthias Ringwald         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
1935628cf69SMatthias Ringwald             return  L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL;
1945628cf69SMatthias Ringwald         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
1955628cf69SMatthias Ringwald             return  L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL;
1965628cf69SMatthias Ringwald         default:
1975628cf69SMatthias Ringwald             return -1;
1985628cf69SMatthias Ringwald         }
1995628cf69SMatthias Ringwald }
20039bda6d5Smatthias.ringwald 
20134e7e577SMatthias Ringwald static int l2cap_fixed_channel_table_index_is_le(int index){
20234e7e577SMatthias Ringwald     if (index == L2CAP_CID_CONNECTIONLESS_CHANNEL) return 0;
20334e7e577SMatthias Ringwald     return 1;
20434e7e577SMatthias Ringwald }
20534e7e577SMatthias Ringwald 
20671de195eSMatthias Ringwald void l2cap_init(void){
2072b83fb7dSmatthias.ringwald     signaling_responses_pending = 0;
208808a48abSmatthias.ringwald 
20985ddcd84SMatthias Ringwald     uint8_t test[] = {0x0E, 0x00, 0x40, 0x00, 0x02, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 };
21085ddcd84SMatthias Ringwald     printf("crc16: %04x\n", crc16_calc(test, sizeof(test)));
21185ddcd84SMatthias Ringwald 
21209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
213f5454fc6Smatthias.ringwald     l2cap_channels = NULL;
214f5454fc6Smatthias.ringwald     l2cap_services = NULL;
21509e9d05bSMatthias Ringwald     require_security_level2_for_outgoing_sdp = 0;
21609e9d05bSMatthias Ringwald #endif
217a3dc965aSMatthias Ringwald 
218a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2197192e786SMatthias Ringwald     l2cap_le_services = NULL;
2207192e786SMatthias Ringwald     l2cap_le_channels = NULL;
221a3dc965aSMatthias Ringwald #endif
222f5454fc6Smatthias.ringwald 
223d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
22433c40538SMatthias Ringwald     l2cap_event_packet_handler = NULL;
225d6ed9f9cSMatthias Ringwald #endif
2265628cf69SMatthias Ringwald     memset(fixed_channels, 0, sizeof(fixed_channels));
227f5454fc6Smatthias.ringwald 
228fcadd0caSmatthias.ringwald     //
2292718e2e7Smatthias.ringwald     // register callback with HCI
230fcadd0caSmatthias.ringwald     //
231d9a7306aSMatthias Ringwald     hci_event_callback_registration.callback = &l2cap_hci_event_handler;
232fb37a842SMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
233fb37a842SMatthias Ringwald 
234d9a7306aSMatthias Ringwald     hci_register_acl_packet_handler(&l2cap_acl_handler);
235fb37a842SMatthias Ringwald 
236be005ed6SMatthias Ringwald #ifdef ENABLE_CLASSIC
23715a95bd5SMatthias Ringwald     gap_connectable_control(0); // no services yet
238be005ed6SMatthias Ringwald #endif
239fcadd0caSmatthias.ringwald }
240fcadd0caSmatthias.ringwald 
241ffbf8201SMatthias Ringwald void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
242d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
24333c40538SMatthias Ringwald     l2cap_event_packet_handler = handler;
244d6ed9f9cSMatthias Ringwald #else
245d6ed9f9cSMatthias Ringwald     UNUSED(handler);
246d6ed9f9cSMatthias Ringwald #endif
2471e6aba47Smatthias.ringwald }
2481e6aba47Smatthias.ringwald 
24909e9d05bSMatthias Ringwald void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
2509ec2630cSMatthias Ringwald     UNUSED(con_handle);
2519ec2630cSMatthias Ringwald 
25209e9d05bSMatthias Ringwald     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
25309e9d05bSMatthias Ringwald     if (index < 0) return;
25409e9d05bSMatthias Ringwald     fixed_channels[index].waiting_for_can_send_now = 1;
25509e9d05bSMatthias Ringwald     l2cap_notify_channel_can_send();
25609e9d05bSMatthias Ringwald }
25709e9d05bSMatthias Ringwald 
25809e9d05bSMatthias Ringwald int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
2599ec2630cSMatthias Ringwald     UNUSED(channel_id);
2609ec2630cSMatthias Ringwald 
26109e9d05bSMatthias Ringwald     return hci_can_send_acl_packet_now(con_handle);
26209e9d05bSMatthias Ringwald }
26309e9d05bSMatthias Ringwald 
26409e9d05bSMatthias Ringwald uint8_t *l2cap_get_outgoing_buffer(void){
26509e9d05bSMatthias Ringwald     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
26609e9d05bSMatthias Ringwald }
26709e9d05bSMatthias Ringwald 
26809e9d05bSMatthias Ringwald int l2cap_reserve_packet_buffer(void){
26909e9d05bSMatthias Ringwald     return hci_reserve_packet_buffer();
27009e9d05bSMatthias Ringwald }
27109e9d05bSMatthias Ringwald 
27209e9d05bSMatthias Ringwald void l2cap_release_packet_buffer(void){
27309e9d05bSMatthias Ringwald     hci_release_packet_buffer();
27409e9d05bSMatthias Ringwald }
27509e9d05bSMatthias Ringwald 
276f511cefaSMatthias Ringwald static void l2cap_setup_header(uint8_t * acl_buffer, hci_con_handle_t con_handle, uint8_t packet_boundary, uint16_t remote_cid, uint16_t len){
27709e9d05bSMatthias Ringwald     // 0 - Connection handle : PB=pb : BC=00
278f511cefaSMatthias Ringwald     little_endian_store_16(acl_buffer, 0, con_handle | (packet_boundary << 12) | (0 << 14));
27909e9d05bSMatthias Ringwald     // 2 - ACL length
28009e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 2,  len + 4);
28109e9d05bSMatthias Ringwald     // 4 - L2CAP packet length
28209e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 4,  len + 0);
28309e9d05bSMatthias Ringwald     // 6 - L2CAP channel DEST
28409e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 6,  remote_cid);
28509e9d05bSMatthias Ringwald }
28609e9d05bSMatthias Ringwald 
287f511cefaSMatthias Ringwald // assumption - only on LE connections
28809e9d05bSMatthias Ringwald int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
28909e9d05bSMatthias Ringwald 
29009e9d05bSMatthias Ringwald     if (!hci_is_packet_buffer_reserved()){
29109e9d05bSMatthias Ringwald         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
29209e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
29309e9d05bSMatthias Ringwald     }
29409e9d05bSMatthias Ringwald 
29509e9d05bSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
29609e9d05bSMatthias Ringwald         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
29709e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
29809e9d05bSMatthias Ringwald     }
29909e9d05bSMatthias Ringwald 
30009e9d05bSMatthias Ringwald     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
30109e9d05bSMatthias Ringwald 
30209e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
303f511cefaSMatthias Ringwald     l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
30409e9d05bSMatthias Ringwald     // send
30509e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len+8);
30609e9d05bSMatthias Ringwald }
30709e9d05bSMatthias Ringwald 
308f511cefaSMatthias Ringwald // assumption - only on LE connections
30909e9d05bSMatthias Ringwald int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
31009e9d05bSMatthias Ringwald 
31109e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(con_handle)){
31209e9d05bSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", cid);
31309e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
31409e9d05bSMatthias Ringwald     }
31509e9d05bSMatthias Ringwald 
31609e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
31709e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
31809e9d05bSMatthias Ringwald 
31909e9d05bSMatthias Ringwald     memcpy(&acl_buffer[8], data, len);
32009e9d05bSMatthias Ringwald 
32109e9d05bSMatthias Ringwald     return l2cap_send_prepared_connectionless(con_handle, cid, len);
32209e9d05bSMatthias Ringwald }
32309e9d05bSMatthias Ringwald 
32409e9d05bSMatthias Ringwald static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
325d9d23054SMatthias Ringwald     log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
32609e9d05bSMatthias Ringwald     uint8_t event[4];
32709e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
32809e9d05bSMatthias Ringwald     event[1] = sizeof(event) - 2;
32909e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, channel);
33009e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
33109e9d05bSMatthias Ringwald     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
33209e9d05bSMatthias Ringwald }
33309e9d05bSMatthias Ringwald 
33409e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
33517a9b554SMatthias Ringwald static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
33658de5610Smatthias.ringwald     (* (channel->packet_handler))(type, channel->local_cid, data, size);
33758de5610Smatthias.ringwald }
33858de5610Smatthias.ringwald 
33944276248SMatthias Ringwald static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
34044276248SMatthias Ringwald     uint8_t event[4];
34144276248SMatthias Ringwald     event[0] = event_code;
34244276248SMatthias Ringwald     event[1] = sizeof(event) - 2;
34344276248SMatthias Ringwald     little_endian_store_16(event, 2, channel->local_cid);
34444276248SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
34544276248SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
34644276248SMatthias Ringwald }
34709e9d05bSMatthias Ringwald #endif
34844276248SMatthias Ringwald 
34909e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
35058de5610Smatthias.ringwald void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
351c9dc710bS[email protected]     log_info("L2CAP_EVENT_CHANNEL_OPENED status 0x%x addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x local_mtu %u, remote_mtu %u, flush_timeout %u",
352fc64f94aSMatthias Ringwald              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
353c9dc710bS[email protected]              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
354bab5f4f0SMatthias Ringwald     uint8_t event[24];
35558de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
35658de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
35758de5610Smatthias.ringwald     event[2] = status;
358724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
359fc64f94aSMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
360f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
361f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
362f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
363f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 17, channel->local_mtu);
364f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 19, channel->remote_mtu);
365f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 21, channel->flush_timeout);
366bab5f4f0SMatthias Ringwald     event[23] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
36758de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
36817a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
36958de5610Smatthias.ringwald }
37058de5610Smatthias.ringwald 
37144276248SMatthias Ringwald static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
372e0abb8e7S[email protected]     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
37344276248SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
37458de5610Smatthias.ringwald }
37558de5610Smatthias.ringwald 
37644276248SMatthias Ringwald static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
377e0abb8e7S[email protected]     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
378fc64f94aSMatthias Ringwald              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
37958de5610Smatthias.ringwald     uint8_t event[16];
38058de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
38158de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
382724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[2]);
383fc64f94aSMatthias Ringwald     little_endian_store_16(event,  8, channel->con_handle);
384f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 10, channel->psm);
385f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 12, channel->local_cid);
386f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 14, channel->remote_cid);
38758de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
38817a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3890af41d30Smatthias.ringwald }
390808a48abSmatthias.ringwald 
3917f02f414SMatthias Ringwald static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
392665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
393665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
394665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
395665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
396b35f641cSmatthias.ringwald         if ( channel->local_cid == local_cid) {
397f62db1e3Smatthias.ringwald             return channel;
398f62db1e3Smatthias.ringwald         }
399f62db1e3Smatthias.ringwald     }
400f62db1e3Smatthias.ringwald     return NULL;
401f62db1e3Smatthias.ringwald }
402f62db1e3Smatthias.ringwald 
4030b9d7e78SMatthias Ringwald ///
4040b9d7e78SMatthias Ringwald 
40530725612SMatthias Ringwald void l2cap_request_can_send_now_event(uint16_t local_cid){
40630725612SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
40730725612SMatthias Ringwald     if (!channel) return;
40830725612SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
40930725612SMatthias Ringwald     l2cap_notify_channel_can_send();
41030725612SMatthias Ringwald }
41130725612SMatthias Ringwald 
4126b1fde37Smatthias.ringwald int  l2cap_can_send_packet_now(uint16_t local_cid){
4136b1fde37Smatthias.ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
4146b1fde37Smatthias.ringwald     if (!channel) return 0;
4150b9d7e78SMatthias Ringwald     return hci_can_send_acl_packet_now(channel->con_handle);
4167856fb31S[email protected] }
4177856fb31S[email protected] 
41883e7cdd9SMatthias Ringwald int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
41983e7cdd9SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
42083e7cdd9SMatthias Ringwald     if (!channel) return 0;
4210b9d7e78SMatthias Ringwald     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
42283e7cdd9SMatthias Ringwald }
42396cbd662Smatthias.ringwald uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
42496cbd662Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
42596cbd662Smatthias.ringwald     if (channel) {
42696cbd662Smatthias.ringwald         return channel->remote_mtu;
42796cbd662Smatthias.ringwald     }
42896cbd662Smatthias.ringwald     return 0;
42996cbd662Smatthias.ringwald }
43096cbd662Smatthias.ringwald 
431ec820d77SMatthias Ringwald static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
432665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
433665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
434665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
435665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4365932bd7cS[email protected]         if ( &channel->rtx == ts) {
4375932bd7cS[email protected]             return channel;
4385932bd7cS[email protected]         }
4395932bd7cS[email protected]     }
4405932bd7cS[email protected]     return NULL;
4415932bd7cS[email protected] }
4425932bd7cS[email protected] 
443ec820d77SMatthias Ringwald static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
4445932bd7cS[email protected]     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
44595d2c8f4SMatthias Ringwald     if (!channel) return;
4465932bd7cS[email protected] 
4475932bd7cS[email protected]     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
4485932bd7cS[email protected] 
4495932bd7cS[email protected]     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
4505932bd7cS[email protected]     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
4515932bd7cS[email protected]     // notify client
4525932bd7cS[email protected]     l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
4535932bd7cS[email protected] 
4545932bd7cS[email protected]     // discard channel
4559dcb2fb2S[email protected]     // no need to stop timer here, it is removed from list during timer callback
456665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4575932bd7cS[email protected]     btstack_memory_l2cap_channel_free(channel);
4585932bd7cS[email protected] }
4595932bd7cS[email protected] 
4605932bd7cS[email protected] static void l2cap_stop_rtx(l2cap_channel_t * channel){
4615932bd7cS[email protected]     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
462528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->rtx);
4635932bd7cS[email protected] }
4645932bd7cS[email protected] 
4655932bd7cS[email protected] static void l2cap_start_rtx(l2cap_channel_t * channel){
4665932bd7cS[email protected]     l2cap_stop_rtx(channel);
467cb0ff06bS[email protected]     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
468528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
469528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
470528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
4715932bd7cS[email protected] }
4725932bd7cS[email protected] 
4735932bd7cS[email protected] static void l2cap_start_ertx(l2cap_channel_t * channel){
4745932bd7cS[email protected]     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
4755932bd7cS[email protected]     l2cap_stop_rtx(channel);
476528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
477528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
478528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
4795932bd7cS[email protected] }
4805932bd7cS[email protected] 
48171de195eSMatthias Ringwald void l2cap_require_security_level_2_for_outgoing_sdp(void){
482ac301f95S[email protected]     require_security_level2_for_outgoing_sdp = 1;
483ac301f95S[email protected] }
484ac301f95S[email protected] 
485df3354fcS[email protected] static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
486235946f1SMatthias Ringwald     return (psm == BLUETOOTH_PROTOCOL_SDP) && (!require_security_level2_for_outgoing_sdp);
487df3354fcS[email protected] }
4885932bd7cS[email protected] 
4897f02f414SMatthias Ringwald static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
490a35252c8S[email protected]     if (!hci_can_send_acl_packet_now(handle)){
4919da54300S[email protected]         log_info("l2cap_send_signaling_packet, cannot send");
492b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
493b1d43497Smatthias.ringwald     }
494b1d43497Smatthias.ringwald 
4959da54300S[email protected]     // log_info("l2cap_send_signaling_packet type %u", cmd);
4962a373862S[email protected]     hci_reserve_packet_buffer();
497facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
49858de5610Smatthias.ringwald     va_list argptr;
49958de5610Smatthias.ringwald     va_start(argptr, identifier);
50070efece1S[email protected]     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
50158de5610Smatthias.ringwald     va_end(argptr);
5029da54300S[email protected]     // log_info("l2cap_send_signaling_packet con %u!", handle);
503826f7347S[email protected]     return hci_send_acl_packet_buffer(len);
50458de5610Smatthias.ringwald }
50558de5610Smatthias.ringwald 
506f511cefaSMatthias Ringwald // assumption - only on Classic connections
507b1d43497Smatthias.ringwald int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
508b1d43497Smatthias.ringwald 
509c8b9416aS[email protected]     if (!hci_is_packet_buffer_reserved()){
510c8b9416aS[email protected]         log_error("l2cap_send_prepared called without reserving packet first");
511c8b9416aS[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
512c8b9416aS[email protected]     }
513c8b9416aS[email protected] 
51458de5610Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
515b1d43497Smatthias.ringwald     if (!channel) {
5169da54300S[email protected]         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
517b1d43497Smatthias.ringwald         return -1;   // TODO: define error
5186218e6f1Smatthias.ringwald     }
5196218e6f1Smatthias.ringwald 
520fc64f94aSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
5219da54300S[email protected]         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
522a35252c8S[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
523a35252c8S[email protected]     }
524a35252c8S[email protected] 
525fc64f94aSMatthias Ringwald     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
526b1d43497Smatthias.ringwald 
52785ddcd84SMatthias Ringwald     int fcs_size = 0;
52885ddcd84SMatthias Ringwald 
52985ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
53085ddcd84SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
53185ddcd84SMatthias Ringwald         fcs_size = 2;
53285ddcd84SMatthias Ringwald     }
53385ddcd84SMatthias Ringwald #endif
53485ddcd84SMatthias Ringwald 
535f511cefaSMatthias Ringwald     // set non-flushable packet boundary flag if supported on Controller
536facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
537f511cefaSMatthias Ringwald     uint8_t packet_boundary_flag = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
53885ddcd84SMatthias Ringwald     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
53985ddcd84SMatthias Ringwald 
54085ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
54185ddcd84SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
54285ddcd84SMatthias Ringwald         // calculate FCS over l2cap data
54385ddcd84SMatthias Ringwald         uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
54485ddcd84SMatthias Ringwald         log_info("I-Frame: fcs 0x%04x", fcs);
54585ddcd84SMatthias Ringwald         little_endian_store_16(acl_buffer, 8 + len, fcs);
54658de5610Smatthias.ringwald     }
54785ddcd84SMatthias Ringwald #endif
54885ddcd84SMatthias Ringwald 
54985ddcd84SMatthias Ringwald     // send
55085ddcd84SMatthias Ringwald     return hci_send_acl_packet_buffer(len+8+fcs_size);
55185ddcd84SMatthias Ringwald }
55285ddcd84SMatthias Ringwald 
55385ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
55485ddcd84SMatthias Ringwald static inline uint16_t l2cap_encanced_control_field_for_information_frame(uint8_t tx_seq, int final, uint8_t req_seq, l2cap_segmentation_and_reassembly_t sar){
55585ddcd84SMatthias Ringwald     return (((uint16_t) sar) << 14) | (req_seq << 8) | (final << 7) | (tx_seq << 1) | 0;
55685ddcd84SMatthias Ringwald }
55785ddcd84SMatthias Ringwald static inline uint16_t l2cap_encanced_control_field_for_supevisor_frame(l2cap_supervisory_function_t supervisory_function, int poll, int final, uint8_t req_seq){
55838f62777SMatthias Ringwald     return (req_seq << 8) | (final << 7) | (poll << 4) | (((int) supervisory_function) << 2) | 1;
55985ddcd84SMatthias Ringwald }
56085ddcd84SMatthias Ringwald static int l2cap_next_ertm_seq_nr(int seq_nr){
56185ddcd84SMatthias Ringwald     return (seq_nr + 1) & 0x3f;
56285ddcd84SMatthias Ringwald }
563*f0fb4cd7SMatthias Ringwald static void l2cap_ertm_next_tx_write_index(l2cap_channel_t * channel){
564*f0fb4cd7SMatthias Ringwald     channel->tx_write_index++;
565*f0fb4cd7SMatthias Ringwald     if (channel->tx_write_index < channel->num_tx_buffers) return;
566*f0fb4cd7SMatthias Ringwald     channel->tx_write_index = 0;
567*f0fb4cd7SMatthias Ringwald }
568*f0fb4cd7SMatthias Ringwald static int l2cap_ertm_send_information_frame(l2cap_channel_t * channel, int index){
569*f0fb4cd7SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
570*f0fb4cd7SMatthias Ringwald     hci_reserve_packet_buffer();
571*f0fb4cd7SMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
572*f0fb4cd7SMatthias Ringwald     uint16_t control = l2cap_encanced_control_field_for_information_frame(tx_state->tx_seq, 0, 0, L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU);
573*f0fb4cd7SMatthias Ringwald     log_info("I-Frame: control 0x%04x", control);
574*f0fb4cd7SMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
575*f0fb4cd7SMatthias Ringwald     memcpy(&acl_buffer[8+2], &channel->tx_packets_data[index * channel->local_mtu], tx_state->len);
576*f0fb4cd7SMatthias Ringwald     // send
577*f0fb4cd7SMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2 + tx_state->len);
578*f0fb4cd7SMatthias Ringwald }
579*f0fb4cd7SMatthias Ringwald static int l2cap_ertm_send(l2cap_channel_t * channel, uint8_t * data, uint16_t len){
580*f0fb4cd7SMatthias Ringwald     if (len > channel->remote_mtu){
581*f0fb4cd7SMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
582*f0fb4cd7SMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
583*f0fb4cd7SMatthias Ringwald     }
584*f0fb4cd7SMatthias Ringwald     // TODO: check tx_transmit
585*f0fb4cd7SMatthias Ringwald     // store int tx packet buffer
586*f0fb4cd7SMatthias Ringwald     int index = channel->tx_write_index;
587*f0fb4cd7SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
588*f0fb4cd7SMatthias Ringwald     tx_state->tx_seq = channel->next_tx_seq;
589*f0fb4cd7SMatthias Ringwald     tx_state->len = len;
590*f0fb4cd7SMatthias Ringwald     memcpy(&channel->tx_packets_data[index * channel->local_mtu], data, len);
591*f0fb4cd7SMatthias Ringwald     // update
592*f0fb4cd7SMatthias Ringwald     channel->next_tx_seq = l2cap_next_ertm_seq_nr(channel->next_tx_seq);
593*f0fb4cd7SMatthias Ringwald     l2cap_ertm_next_tx_write_index(channel);
594*f0fb4cd7SMatthias Ringwald     // test sendiging it right away
595*f0fb4cd7SMatthias Ringwald     l2cap_ertm_send_information_frame(channel, index);
596*f0fb4cd7SMatthias Ringwald     return 0;
597*f0fb4cd7SMatthias Ringwald }
59885ddcd84SMatthias Ringwald #endif
59958de5610Smatthias.ringwald 
600f511cefaSMatthias Ringwald // assumption - only on Classic connections
601ce8f182eSMatthias Ringwald int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
602a35252c8S[email protected]     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
603a35252c8S[email protected]     if (!channel) {
604ce8f182eSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
605a35252c8S[email protected]         return -1;   // TODO: define error
606a35252c8S[email protected]     }
607a35252c8S[email protected] 
608*f0fb4cd7SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
609*f0fb4cd7SMatthias Ringwald     // send in ERTM
610*f0fb4cd7SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
611*f0fb4cd7SMatthias Ringwald         return l2cap_ertm_send(channel, data, len);
612*f0fb4cd7SMatthias Ringwald     }
613*f0fb4cd7SMatthias Ringwald #endif
614*f0fb4cd7SMatthias Ringwald 
615f0efaa57S[email protected]     if (len > channel->remote_mtu){
616ce8f182eSMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
617f0efaa57S[email protected]         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
618f0efaa57S[email protected]     }
619f0efaa57S[email protected] 
620fc64f94aSMatthias Ringwald     if (!hci_can_send_acl_packet_now(channel->con_handle)){
621ce8f182eSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
622b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
623b1d43497Smatthias.ringwald     }
624b1d43497Smatthias.ringwald 
6252a373862S[email protected]     hci_reserve_packet_buffer();
626facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
627*f0fb4cd7SMatthias Ringwald     memcpy(&acl_buffer[8], data, len);
628*f0fb4cd7SMatthias Ringwald     return l2cap_send_prepared(local_cid, len);
629b1d43497Smatthias.ringwald }
630b1d43497Smatthias.ringwald 
631fc64f94aSMatthias Ringwald int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
632fc64f94aSMatthias Ringwald     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
6330e37e417S[email protected] }
6340e37e417S[email protected] 
63528ca2b46S[email protected] static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
63628ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
63728ca2b46S[email protected] }
63828ca2b46S[email protected] 
63928ca2b46S[email protected] static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
64028ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
64128ca2b46S[email protected] }
64209e9d05bSMatthias Ringwald #endif
64328ca2b46S[email protected] 
64428ca2b46S[email protected] 
64509e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
64609e9d05bSMatthias Ringwald static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
64709e9d05bSMatthias Ringwald 
64809e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(handle)){
64909e9d05bSMatthias Ringwald         log_info("l2cap_send_le_signaling_packet, cannot send");
65009e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
65109e9d05bSMatthias Ringwald     }
65209e9d05bSMatthias Ringwald 
65309e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
65409e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
65509e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
65609e9d05bSMatthias Ringwald     va_list argptr;
65709e9d05bSMatthias Ringwald     va_start(argptr, identifier);
65809e9d05bSMatthias Ringwald     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
65909e9d05bSMatthias Ringwald     va_end(argptr);
66009e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
66109e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len);
66209e9d05bSMatthias Ringwald }
66309e9d05bSMatthias Ringwald #endif
66409e9d05bSMatthias Ringwald 
66509e9d05bSMatthias Ringwald uint16_t l2cap_max_mtu(void){
66609e9d05bSMatthias Ringwald     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
66709e9d05bSMatthias Ringwald }
66809e9d05bSMatthias Ringwald 
66909e9d05bSMatthias Ringwald uint16_t l2cap_max_le_mtu(void){
67009e9d05bSMatthias Ringwald     return l2cap_max_mtu();
67109e9d05bSMatthias Ringwald }
672b1d43497Smatthias.ringwald 
673450ad7ecSMatthias Ringwald static uint16_t l2cap_setup_options_mtu(l2cap_channel_t * channel, uint8_t * config_options){
674450ad7ecSMatthias Ringwald     config_options[0] = 1; // MTU
675450ad7ecSMatthias Ringwald     config_options[1] = 2; // len param
676450ad7ecSMatthias Ringwald     little_endian_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
677450ad7ecSMatthias Ringwald     return 4;
678450ad7ecSMatthias Ringwald }
679450ad7ecSMatthias Ringwald 
6806dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
681450ad7ecSMatthias Ringwald static uint16_t l2cap_setup_options_ertm(l2cap_channel_t * channel, uint8_t * config_options){
6826dca2a0cSMatthias Ringwald     config_options[0] = 0x04;   // RETRANSMISSION AND FLOW CONTROL OPTION
6836dca2a0cSMatthias Ringwald     config_options[1] = 9;      // length
6846dca2a0cSMatthias Ringwald     config_options[2] = (uint8_t) channel->mode;
6857b181629SMatthias Ringwald     config_options[3] = channel->num_rx_buffers;    // == TxWindows size
686bbc0a9e7SMatthias Ringwald     config_options[4] = channel->local_max_transmit;
687bbc0a9e7SMatthias Ringwald     little_endian_store_16( config_options, 5, channel->local_retransmission_timeout_ms);
688bbc0a9e7SMatthias Ringwald     little_endian_store_16( config_options, 7, channel->local_monitor_timeout_ms);
6897b181629SMatthias Ringwald     little_endian_store_16( config_options, 9, channel->local_mtu);
690450ad7ecSMatthias Ringwald     return 11;
6916dca2a0cSMatthias Ringwald }
69238f62777SMatthias Ringwald static int l2cap_ertm_send_supervisor_frame(l2cap_channel_t * channel, uint16_t control){
69338f62777SMatthias Ringwald     hci_reserve_packet_buffer();
69438f62777SMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
69538f62777SMatthias Ringwald     log_info("S-Frame: control 0x%04x", control);
69638f62777SMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
69738f62777SMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2);
69838f62777SMatthias Ringwald }
699450ad7ecSMatthias Ringwald #endif
700450ad7ecSMatthias Ringwald 
701450ad7ecSMatthias Ringwald static uint16_t l2cap_setup_options(l2cap_channel_t * channel, uint8_t * config_options){
702450ad7ecSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
703450ad7ecSMatthias Ringwald     // use ERTM options if supported
704450ad7ecSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
705450ad7ecSMatthias Ringwald     if ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE) && (connection->l2cap_state.extended_feature_mask & 0x08)){
706450ad7ecSMatthias Ringwald         return l2cap_setup_options_ertm(channel, config_options);
707450ad7ecSMatthias Ringwald 
708450ad7ecSMatthias Ringwald     }
709450ad7ecSMatthias Ringwald #endif
710450ad7ecSMatthias Ringwald     return l2cap_setup_options_mtu(channel, config_options);
7116dca2a0cSMatthias Ringwald }
7126dca2a0cSMatthias Ringwald 
7131b9cb13dSMatthias Ringwald static uint32_t l2cap_extended_features_mask(void){
7141b9cb13dSMatthias Ringwald     // extended features request supported, features: fixed channels, unicast connectionless data reception
7151b9cb13dSMatthias Ringwald     uint32_t features = 0x280;
7161b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
7171b9cb13dSMatthias Ringwald     features |= 0x0008;
7181b9cb13dSMatthias Ringwald #endif
7191b9cb13dSMatthias Ringwald     return features;
7201b9cb13dSMatthias Ringwald }
7211b9cb13dSMatthias Ringwald 
7228158c421Smatthias.ringwald // MARK: L2CAP_RUN
7232cd0be45Smatthias.ringwald // process outstanding signaling tasks
7247f02f414SMatthias Ringwald static void l2cap_run(void){
7252b83fb7dSmatthias.ringwald 
72622c29ab4SMatthias Ringwald     // log_info("l2cap_run: entered");
72722c29ab4SMatthias Ringwald 
7282b83fb7dSmatthias.ringwald     // check pending signaling responses
7292b83fb7dSmatthias.ringwald     while (signaling_responses_pending){
7302b83fb7dSmatthias.ringwald 
7312b83fb7dSmatthias.ringwald         hci_con_handle_t handle = signaling_responses[0].handle;
732a35252c8S[email protected] 
733a35252c8S[email protected]         if (!hci_can_send_acl_packet_now(handle)) break;
734a35252c8S[email protected] 
7352b83fb7dSmatthias.ringwald         uint8_t  sig_id        = signaling_responses[0].sig_id;
736e74c5f58SMatthias Ringwald         uint8_t  response_code = signaling_responses[0].code;
7372b360848Smatthias.ringwald         uint16_t infoType      = signaling_responses[0].data;  // INFORMATION_REQUEST
73863a7246aSmatthias.ringwald         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
739b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
740b3264428SMatthias Ringwald         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
741b3264428SMatthias Ringwald #endif
742f3963406SMatthias Ringwald         UNUSED(infoType);
74309e9d05bSMatthias Ringwald 
744f53da564S[email protected]         // remove first item before sending (to avoid sending response mutliple times)
745f53da564S[email protected]         signaling_responses_pending--;
746f53da564S[email protected]         int i;
747f53da564S[email protected]         for (i=0; i < signaling_responses_pending; i++){
748f53da564S[email protected]             memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t));
749f53da564S[email protected]         }
750f53da564S[email protected] 
751f53da564S[email protected]         switch (response_code){
75209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
7532b360848Smatthias.ringwald             case CONNECTION_REQUEST:
754e74c5f58SMatthias Ringwald                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
7552bd8b7e7S[email protected]                 // also disconnect if result is 0x0003 - security blocked
7564d816277S[email protected]                 if (result == 0x0003){
7572bd8b7e7S[email protected]                     hci_disconnect_security_block(handle);
7584d816277S[email protected]                 }
7592b360848Smatthias.ringwald                 break;
7602b83fb7dSmatthias.ringwald             case ECHO_REQUEST:
7612b83fb7dSmatthias.ringwald                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
7622b83fb7dSmatthias.ringwald                 break;
7632b83fb7dSmatthias.ringwald             case INFORMATION_REQUEST:
7643b0484b3S[email protected]                 switch (infoType){
7653b0484b3S[email protected]                     case 1: { // Connectionless MTU
7663b0484b3S[email protected]                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
7673b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(connectionless_mtu), &connectionless_mtu);
7683b0484b3S[email protected]                         }
769202c8a4cSMatthias Ringwald                         break;
7703b0484b3S[email protected]                     case 2: {  // Extended Features Supported
7711b9cb13dSMatthias Ringwald                             uint32_t features = l2cap_extended_features_mask();
7723b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(features), &features);
7733b0484b3S[email protected]                         }
774202c8a4cSMatthias Ringwald                         break;
7753b0484b3S[email protected]                     case 3: { // Fixed Channels Supported
7763b0484b3S[email protected]                             uint8_t map[8];
7773b0484b3S[email protected]                             memset(map, 0, 8);
778288636a2SMatthias Ringwald                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
7793b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(map), &map);
7803b0484b3S[email protected]                         }
781202c8a4cSMatthias Ringwald                         break;
7823b0484b3S[email protected]                     default:
7832b83fb7dSmatthias.ringwald                         // all other types are not supported
7842b83fb7dSmatthias.ringwald                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
7853b0484b3S[email protected]                         break;
7862b83fb7dSmatthias.ringwald                 }
7872b83fb7dSmatthias.ringwald                 break;
78863a7246aSmatthias.ringwald             case COMMAND_REJECT:
7895ca8d57bS[email protected]                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
79063f0ac45SMatthias Ringwald                 break;
79109e9d05bSMatthias Ringwald #endif
792a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
79363f0ac45SMatthias Ringwald             case LE_CREDIT_BASED_CONNECTION_REQUEST:
79463f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
79563f0ac45SMatthias Ringwald                 break;
79670efece1S[email protected]             case COMMAND_REJECT_LE:
79770efece1S[email protected]                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
79863a7246aSmatthias.ringwald                 break;
79970efece1S[email protected] #endif
8002b83fb7dSmatthias.ringwald             default:
8012b83fb7dSmatthias.ringwald                 // should not happen
8022b83fb7dSmatthias.ringwald                 break;
8032b83fb7dSmatthias.ringwald         }
8042b83fb7dSmatthias.ringwald     }
8052b83fb7dSmatthias.ringwald 
806665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
807f3963406SMatthias Ringwald     UNUSED(it);
80809e9d05bSMatthias Ringwald 
8091b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
8101b9cb13dSMatthias Ringwald     // send l2cap information request if neccessary
8111b9cb13dSMatthias Ringwald     hci_connections_get_iterator(&it);
8121b9cb13dSMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
8131b9cb13dSMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
8141b9cb13dSMatthias Ringwald         if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST){
8151b9cb13dSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
8161b9cb13dSMatthias Ringwald             // send information request for extended features
8171b9cb13dSMatthias Ringwald             uint8_t sig_id = l2cap_next_sig_id();
8181b9cb13dSMatthias Ringwald             uint8_t info_type = 2;
8191b9cb13dSMatthias Ringwald             l2cap_send_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
8201b9cb13dSMatthias Ringwald             return;
8211b9cb13dSMatthias Ringwald         }
8221b9cb13dSMatthias Ringwald     }
8231b9cb13dSMatthias Ringwald #endif
8241b9cb13dSMatthias Ringwald 
82509e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
82643ec931dSMatthias Ringwald     uint8_t  config_options[10];
827665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
828665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
829baf94f06S[email protected] 
830665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
83122c29ab4SMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
8322cd0be45Smatthias.ringwald         switch (channel->state){
8332cd0be45Smatthias.ringwald 
834df3354fcS[email protected]             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
835ad671560S[email protected]             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
836fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
837a00031e2S[email protected]                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
838ad671560S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
839fc64f94aSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
840ad671560S[email protected]                 }
841ad671560S[email protected]                 break;
842ad671560S[email protected] 
84302b22dc4Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
844baf94f06S[email protected]                 if (!hci_can_send_command_packet_now()) break;
84564472d52Smatthias.ringwald                 // send connection request - set state first
84664472d52Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
84702b22dc4Smatthias.ringwald                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
8488f8108aaSmatthias.ringwald                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
84902b22dc4Smatthias.ringwald                 break;
85002b22dc4Smatthias.ringwald 
851e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
852fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
85322c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
854fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
855e7ff783cSmatthias.ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
8569dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
857665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
858d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
859e7ff783cSmatthias.ringwald                 break;
860e7ff783cSmatthias.ringwald 
861552d92a1Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
862fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
863fa8473a4Smatthias.ringwald                 channel->state = L2CAP_STATE_CONFIG;
86428ca2b46S[email protected]                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
865fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
866552d92a1Smatthias.ringwald                 break;
867552d92a1Smatthias.ringwald 
8686fdcc387Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
869fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
8706fdcc387Smatthias.ringwald                 // success, start l2cap handshake
871b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
8726fdcc387Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
873fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
8745932bd7cS[email protected]                 l2cap_start_rtx(channel);
8756fdcc387Smatthias.ringwald                 break;
8766fdcc387Smatthias.ringwald 
877fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
878fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
87973cf2b3dSmatthias.ringwald                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
88063a7246aSmatthias.ringwald                     uint16_t flags = 0;
88128ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
88263a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
88363a7246aSmatthias.ringwald                         flags = 1;
88463a7246aSmatthias.ringwald                     } else {
88528ca2b46S[email protected]                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
88663a7246aSmatthias.ringwald                     }
88763a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
888ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
889fc64f94aSMatthias 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);
890ac8f1300SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
891ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
892ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
893ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
8946dca2a0cSMatthias Ringwald                         uint16_t options_size = l2cap_setup_options(channel, config_options);
895ac8f1300SMatthias 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);
896ac8f1300SMatthias Ringwald #endif
897ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
89863a7246aSmatthias.ringwald                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
899ac8f1300SMatthias Ringwald                         uint16_t options_size = l2cap_setup_options(channel, config_options);
900ac8f1300SMatthias 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);
90163a7246aSmatthias.ringwald                     } else {
902ac8f1300SMatthias Ringwald                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
90363a7246aSmatthias.ringwald                     }
90463a7246aSmatthias.ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
905fa8473a4Smatthias.ringwald                 }
90673cf2b3dSmatthias.ringwald                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
90728ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
90828ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
909b1988dceSmatthias.ringwald                     channel->local_sig_id = l2cap_next_sig_id();
9106dca2a0cSMatthias Ringwald                     uint16_t options_size = l2cap_setup_options(channel, config_options);
9116dca2a0cSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options);
9125932bd7cS[email protected]                     l2cap_start_rtx(channel);
913fa8473a4Smatthias.ringwald                 }
914fa8473a4Smatthias.ringwald                 if (l2cap_channel_ready_for_open(channel)){
915552d92a1Smatthias.ringwald                     channel->state = L2CAP_STATE_OPEN;
916552d92a1Smatthias.ringwald                     l2cap_emit_channel_opened(channel, 0);  // success
917fa8473a4Smatthias.ringwald                 }
918552d92a1Smatthias.ringwald                 break;
919552d92a1Smatthias.ringwald 
920e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
921fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
92222c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
923fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
9245932bd7cS[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 :)
925756102d3Smatthias.ringwald                 l2cap_finialize_channel_close(channel);  // -- remove from list
926e7ff783cSmatthias.ringwald                 break;
927e7ff783cSmatthias.ringwald 
928e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
929fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
930b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
9312cd0be45Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
932fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
9332cd0be45Smatthias.ringwald                 break;
9342cd0be45Smatthias.ringwald             default:
9352cd0be45Smatthias.ringwald                 break;
9362cd0be45Smatthias.ringwald         }
93738f62777SMatthias Ringwald 
93838f62777SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
93938f62777SMatthias Ringwald         // send s-frame to acknowledge received packets
94038f62777SMatthias Ringwald         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
941d84e866fSMatthias Ringwald         if (channel->send_supervisor_frame_receiver_ready){
942d84e866fSMatthias Ringwald             channel->send_supervisor_frame_receiver_ready = 0;;
943d84e866fSMatthias Ringwald             log_info("Send S-Frame: RR %u", channel->req_seq);
94438f62777SMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 0, 0, channel->req_seq);
94538f62777SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
94638f62777SMatthias Ringwald         }
94738f62777SMatthias Ringwald #endif
94838f62777SMatthias Ringwald 
9492cd0be45Smatthias.ringwald     }
95009e9d05bSMatthias Ringwald #endif
951da886c03S[email protected] 
952cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
953efedfb4cSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
954efedfb4cSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
9557f107edaSMatthias Ringwald         uint8_t  * acl_buffer;
9567f107edaSMatthias Ringwald         uint8_t  * l2cap_payload;
9577f107edaSMatthias Ringwald         uint16_t pos;
9587f107edaSMatthias Ringwald         uint16_t payload_size;
959efedfb4cSMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
960efedfb4cSMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
961efedfb4cSMatthias Ringwald         switch (channel->state){
9625cb87675SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
9635cb87675SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
9645cb87675SMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
9655cb87675SMatthias Ringwald                 // le psm, source cid, mtu, mps, initial credits
9661b8b8d05SMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
96763f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
96863f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
96963f0ac45SMatthias 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);
9705cb87675SMatthias Ringwald                 break;
97123017473SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
97223017473SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
97323017473SMatthias Ringwald                 // TODO: support larger MPS
97423017473SMatthias Ringwald                 channel->state = L2CAP_STATE_OPEN;
97563f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
97663f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
97763f0ac45SMatthias 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);
97864e11ca9SMatthias Ringwald                 // notify client
97944276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0);
98023017473SMatthias Ringwald                 break;
981e7d0c9aaSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
982e7d0c9aaSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
983e7d0c9aaSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
98463f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
985e7d0c9aaSMatthias Ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
986e7d0c9aaSMatthias Ringwald                 l2cap_stop_rtx(channel);
987e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
988e7d0c9aaSMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
989e7d0c9aaSMatthias Ringwald                 break;
9907f107edaSMatthias Ringwald             case L2CAP_STATE_OPEN:
99185aeef60SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
99285aeef60SMatthias Ringwald 
99385aeef60SMatthias Ringwald                 // send credits
99485aeef60SMatthias Ringwald                 if (channel->new_credits_incoming){
99585aeef60SMatthias Ringwald                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
99685aeef60SMatthias Ringwald                     channel->local_sig_id = l2cap_next_sig_id();
99785aeef60SMatthias Ringwald                     uint16_t new_credits = channel->new_credits_incoming;
99885aeef60SMatthias Ringwald                     channel->new_credits_incoming = 0;
99985aeef60SMatthias Ringwald                     channel->credits_incoming += new_credits;
100085aeef60SMatthias Ringwald                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
100185aeef60SMatthias Ringwald                     break;
100285aeef60SMatthias Ringwald                 }
100385aeef60SMatthias Ringwald 
100485aeef60SMatthias Ringwald                 // send data
10057f107edaSMatthias Ringwald                 if (!channel->send_sdu_buffer) break;
10067f107edaSMatthias Ringwald                 if (!channel->credits_outgoing) break;
100785aeef60SMatthias Ringwald 
10087f107edaSMatthias Ringwald                 // send part of SDU
10097f107edaSMatthias Ringwald                 hci_reserve_packet_buffer();
10107f107edaSMatthias Ringwald                 acl_buffer = hci_get_outgoing_packet_buffer();
10117f107edaSMatthias Ringwald                 l2cap_payload = acl_buffer + 8;
10127f107edaSMatthias Ringwald                 pos = 0;
10137f107edaSMatthias Ringwald                 if (!channel->send_sdu_pos){
10147f107edaSMatthias Ringwald                     // store SDU len
10157f107edaSMatthias Ringwald                     channel->send_sdu_pos += 2;
10167f107edaSMatthias Ringwald                     little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
10177f107edaSMatthias Ringwald                     pos += 2;
10187f107edaSMatthias Ringwald                 }
10197f107edaSMatthias Ringwald                 payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
102085aeef60SMatthias Ringwald                 log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
10217f107edaSMatthias Ringwald                 memcpy(&l2cap_payload[pos], &channel->send_sdu_buffer[channel->send_sdu_pos-2], payload_size); // -2 for virtual SDU len
10227f107edaSMatthias Ringwald                 pos += payload_size;
10237f107edaSMatthias Ringwald                 channel->send_sdu_pos += payload_size;
1024f511cefaSMatthias Ringwald                 l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
10257f107edaSMatthias Ringwald                 // done
10267f107edaSMatthias Ringwald 
102785aeef60SMatthias Ringwald                 channel->credits_outgoing--;
10287f107edaSMatthias Ringwald 
10297f107edaSMatthias Ringwald                 if (channel->send_sdu_pos >= channel->send_sdu_len + 2){
10307f107edaSMatthias Ringwald                     channel->send_sdu_buffer = NULL;
103144276248SMatthias Ringwald                     // send done event
103244276248SMatthias Ringwald                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
103344276248SMatthias Ringwald                     // inform about can send now
103444276248SMatthias Ringwald                     l2cap_le_notify_channel_can_send(channel);
10357f107edaSMatthias Ringwald                 }
10367f107edaSMatthias Ringwald                 hci_send_acl_packet_buffer(8 + pos);
10377f107edaSMatthias Ringwald                 break;
1038828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1039828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1040828a7f7aSMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
1041828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1042828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1043828a7f7aSMatthias Ringwald                 break;
1044828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1045828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1046828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1047828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1048828a7f7aSMatthias Ringwald                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
1049828a7f7aSMatthias Ringwald                 break;
1050efedfb4cSMatthias Ringwald             default:
1051efedfb4cSMatthias Ringwald                 break;
1052efedfb4cSMatthias Ringwald         }
1053efedfb4cSMatthias Ringwald     }
105409e9d05bSMatthias Ringwald #endif
1055efedfb4cSMatthias Ringwald 
105609e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
1057da886c03S[email protected]     // send l2cap con paramter update if necessary
1058da886c03S[email protected]     hci_connections_get_iterator(&it);
1059665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
1060665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
10615d14fa8fSMatthias Ringwald         if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue;
1062b68d7bc3SMatthias Ringwald         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
1063da886c03S[email protected]         switch (connection->le_con_parameter_update_state){
1064b68d7bc3SMatthias Ringwald             case CON_PARAMETER_UPDATE_SEND_REQUEST:
1065b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1066b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier,
1067b68d7bc3SMatthias Ringwald                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
1068b68d7bc3SMatthias Ringwald                 break;
1069da886c03S[email protected]             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
1070b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
1071b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
1072da886c03S[email protected]                 break;
1073da886c03S[email protected]             case CON_PARAMETER_UPDATE_DENY:
1074b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1075b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
1076da886c03S[email protected]                 break;
1077da886c03S[email protected]             default:
1078da886c03S[email protected]                 break;
1079da886c03S[email protected]         }
1080da886c03S[email protected]     }
10814d7157c3S[email protected] #endif
1082da886c03S[email protected] 
108322c29ab4SMatthias Ringwald     // log_info("l2cap_run: exit");
10842cd0be45Smatthias.ringwald }
10852cd0be45Smatthias.ringwald 
108609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1087fc64f94aSMatthias Ringwald static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
10882df5dadcS[email protected]     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
10895533f01eS[email protected]         log_info("l2cap_handle_connection_complete expected state");
10902df5dadcS[email protected]         // success, start l2cap handshake
1091fc64f94aSMatthias Ringwald         channel->con_handle = con_handle;
10922df5dadcS[email protected]         // check remote SSP feature first
10932df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
10942df5dadcS[email protected]     }
10952df5dadcS[email protected] }
10962df5dadcS[email protected] 
10971b9cb13dSMatthias Ringwald static void l2cap_ready_to_connect(l2cap_channel_t * channel){
10981b9cb13dSMatthias Ringwald 
10991b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
110027e0774aSMatthias Ringwald     // assumption: outgoing connection
11011b9cb13dSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
11021b9cb13dSMatthias Ringwald     if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
11031b9cb13dSMatthias Ringwald         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
11041b9cb13dSMatthias Ringwald         channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
11051b9cb13dSMatthias Ringwald         return;
11061b9cb13dSMatthias Ringwald     }
11071b9cb13dSMatthias Ringwald #endif
11081b9cb13dSMatthias Ringwald 
11091b9cb13dSMatthias Ringwald     // fine, go ahead
11101b9cb13dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
11111b9cb13dSMatthias Ringwald }
11121b9cb13dSMatthias Ringwald 
11132df5dadcS[email protected] static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
11142df5dadcS[email protected]     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
11152df5dadcS[email protected] 
11162df5dadcS[email protected]     // we have been waiting for remote supported features, if both support SSP,
1117ac301f95S[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));
1118fc64f94aSMatthias Ringwald     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
11192df5dadcS[email protected]         // request security level 2
11202df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
1121fc64f94aSMatthias Ringwald         gap_request_security_level(channel->con_handle, LEVEL_2);
11222df5dadcS[email protected]         return;
11232df5dadcS[email protected]     }
11241b9cb13dSMatthias Ringwald 
11251b9cb13dSMatthias Ringwald     l2cap_ready_to_connect(channel);
11262df5dadcS[email protected] }
112709e9d05bSMatthias Ringwald #endif
11282df5dadcS[email protected] 
112909e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
1130da144af5SMatthias 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,
1131da144af5SMatthias Ringwald     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
1132da144af5SMatthias Ringwald 
1133da144af5SMatthias Ringwald     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1134da144af5SMatthias Ringwald     if (!channel) {
1135da144af5SMatthias Ringwald         return NULL;
1136da144af5SMatthias Ringwald     }
1137da144af5SMatthias Ringwald 
1138da144af5SMatthias Ringwald      // Init memory (make valgrind happy)
1139da144af5SMatthias Ringwald     memset(channel, 0, sizeof(l2cap_channel_t));
1140da144af5SMatthias Ringwald 
1141da144af5SMatthias Ringwald     // fill in
1142da144af5SMatthias Ringwald     channel->packet_handler = packet_handler;
1143da144af5SMatthias Ringwald     bd_addr_copy(channel->address, address);
1144da144af5SMatthias Ringwald     channel->address_type = address_type;
1145da144af5SMatthias Ringwald     channel->psm = psm;
1146da144af5SMatthias Ringwald     channel->local_mtu  = local_mtu;
1147da144af5SMatthias Ringwald     channel->remote_mtu = L2CAP_MINIMAL_MTU;
1148da144af5SMatthias Ringwald     channel->required_security_level = security_level;
1149da144af5SMatthias Ringwald 
1150da144af5SMatthias Ringwald     //
1151da144af5SMatthias Ringwald     channel->local_cid = l2cap_next_local_cid();
1152da144af5SMatthias Ringwald     channel->con_handle = 0;
1153da144af5SMatthias Ringwald 
1154da144af5SMatthias Ringwald     // set initial state
1155da144af5SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
1156da144af5SMatthias Ringwald     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
1157da144af5SMatthias Ringwald     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
1158da144af5SMatthias Ringwald     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
115938f62777SMatthias Ringwald 
1160da144af5SMatthias Ringwald     return channel;
1161da144af5SMatthias Ringwald }
116209e9d05bSMatthias Ringwald #endif
116309e9d05bSMatthias Ringwald 
116409e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1165da144af5SMatthias Ringwald 
11669077cb15SMatthias Ringwald /**
11679077cb15SMatthias Ringwald  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
11689077cb15SMatthias Ringwald  * @param packet_handler
11699077cb15SMatthias Ringwald  * @param address
11709077cb15SMatthias Ringwald  * @param psm
11719077cb15SMatthias Ringwald  * @param mtu
11729077cb15SMatthias Ringwald  * @param local_cid
11739077cb15SMatthias Ringwald  */
11749077cb15SMatthias Ringwald 
11759d139fbaSMatthias 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){
11769d139fbaSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
11779d139fbaSMatthias Ringwald     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1178da144af5SMatthias Ringwald 
11799d139fbaSMatthias 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);
1180da144af5SMatthias Ringwald 
1181da144af5SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
1182fc64f94aSMatthias Ringwald     if (!channel) {
11839077cb15SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
11849077cb15SMatthias Ringwald     }
11859077cb15SMatthias Ringwald 
11861b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
11871b9cb13dSMatthias Ringwald     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
11881b9cb13dSMatthias Ringwald #endif
11891b9cb13dSMatthias Ringwald 
11909077cb15SMatthias Ringwald     // add to connections list
1191fc64f94aSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
11929077cb15SMatthias Ringwald 
11939077cb15SMatthias Ringwald     // store local_cid
11949077cb15SMatthias Ringwald     if (out_local_cid){
1195fc64f94aSMatthias Ringwald        *out_local_cid = channel->local_cid;
11969077cb15SMatthias Ringwald     }
11979077cb15SMatthias Ringwald 
11989077cb15SMatthias Ringwald     // check if hci connection is already usable
11999077cb15SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
12009077cb15SMatthias Ringwald     if (conn){
1201add0254bSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
1202fc64f94aSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
12039077cb15SMatthias Ringwald         // check if remote supported fearures are already received
12049077cb15SMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
1205fc64f94aSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
12069077cb15SMatthias Ringwald         }
12079077cb15SMatthias Ringwald     }
12089077cb15SMatthias Ringwald 
12099077cb15SMatthias Ringwald     l2cap_run();
12109077cb15SMatthias Ringwald 
12119077cb15SMatthias Ringwald     return 0;
12129077cb15SMatthias Ringwald }
12139077cb15SMatthias Ringwald 
12141b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
12157b181629SMatthias Ringwald 
12162b70d705SMatthias Ringwald static uint8_t l2cap_ertm_validate_local_config(uint8_t max_transmit, uint16_t retransmission_timeout_ms,
12172b70d705SMatthias Ringwald     uint16_t monitor_timeout_ms, uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size){
12182b70d705SMatthias Ringwald     UNUSED(buffer);
12192b70d705SMatthias Ringwald     UNUSED(size);
12202b70d705SMatthias Ringwald 
12212b70d705SMatthias Ringwald     uint8_t result = ERROR_CODE_SUCCESS;
12222b70d705SMatthias Ringwald     if (max_transmit < 1){
12232b70d705SMatthias Ringwald         log_error("max_transmit must be >= 1");
12242b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
12252b70d705SMatthias Ringwald     }
12262b70d705SMatthias Ringwald     if (retransmission_timeout_ms < 2000){
12272b70d705SMatthias Ringwald         log_error("retransmission_timeout_ms must be >= 2000 ms");
12282b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
12292b70d705SMatthias Ringwald     }
12302b70d705SMatthias Ringwald     if (monitor_timeout_ms < 12000){
12312b70d705SMatthias Ringwald         log_error("monitor_timeout_ms must be >= 12000 ms");
12322b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
12332b70d705SMatthias Ringwald     }
12342b70d705SMatthias Ringwald     if (num_rx_buffers < 1){
12352b70d705SMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
12362b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
12372b70d705SMatthias Ringwald     }
12382b70d705SMatthias Ringwald     if (num_tx_buffers < 1){
12392b70d705SMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
12402b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
12412b70d705SMatthias Ringwald     }
12422b70d705SMatthias Ringwald     return result;
12432b70d705SMatthias Ringwald }
12442b70d705SMatthias Ringwald 
12457b181629SMatthias Ringwald static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, int ertm_mandatory, uint8_t max_transmit,
12467b181629SMatthias 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){
12477b181629SMatthias Ringwald 
12487b181629SMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
12497b181629SMatthias Ringwald     channel->ertm_mandatory = ertm_mandatory;
1250bbc0a9e7SMatthias Ringwald     channel->local_max_transmit = max_transmit;
1251bbc0a9e7SMatthias Ringwald     channel->local_retransmission_timeout_ms = retransmission_timeout_ms;
1252bbc0a9e7SMatthias Ringwald     channel->local_monitor_timeout_ms = monitor_timeout_ms;
12537b181629SMatthias Ringwald     channel->num_rx_buffers = num_rx_buffers;
12547b181629SMatthias Ringwald     channel->num_tx_buffers = num_tx_buffers;
12557b181629SMatthias Ringwald 
12567b181629SMatthias Ringwald     // TODO: align buffer pointer
12577b181629SMatthias Ringwald     uint32_t pos = 0;
12587b181629SMatthias Ringwald     channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) &buffer[pos];
12597b181629SMatthias Ringwald     pos += num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
12607b181629SMatthias Ringwald     channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) &buffer[pos];
12617b181629SMatthias Ringwald     pos += num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
12627b181629SMatthias Ringwald     // calculate MTU
12637b181629SMatthias Ringwald     channel->local_mtu = (size - pos) / (num_rx_buffers + num_tx_buffers);
12647b181629SMatthias Ringwald     log_info("Local ERTM MTU: %u", channel->local_mtu);
12657b181629SMatthias Ringwald     channel->rx_packets_data = &buffer[pos];
12667b181629SMatthias Ringwald     pos += num_rx_buffers * channel->local_mtu;
12677b181629SMatthias Ringwald     channel->tx_packets_data = &buffer[pos];
12687b181629SMatthias Ringwald     log_info("RX packets %p, TX packets %p", channel->rx_packets_data, channel->tx_packets_data);
12697b181629SMatthias Ringwald }
12707b181629SMatthias Ringwald 
1271501329faSMatthias Ringwald uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
1272501329faSMatthias Ringwald     int ertm_mandatory, uint8_t max_transmit, uint16_t retransmission_timeout_ms, uint16_t monitor_timeout_ms,
1273501329faSMatthias Ringwald     uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
1274501329faSMatthias Ringwald 
12751b9cb13dSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
1276501329faSMatthias Ringwald     uint16_t local_mtu = l2cap_max_mtu();
12771b9cb13dSMatthias Ringwald 
1278501329faSMatthias Ringwald     log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x -> local mtu %u", bd_addr_to_str(address), psm, local_mtu);
12791b9cb13dSMatthias Ringwald 
12802b70d705SMatthias Ringwald     // validate local config
12812b70d705SMatthias 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);
12822b70d705SMatthias Ringwald     if (result) return result;
12832b70d705SMatthias Ringwald 
1284501329faSMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
12851b9cb13dSMatthias Ringwald     if (!channel) {
12861b9cb13dSMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
12871b9cb13dSMatthias Ringwald     }
12881b9cb13dSMatthias Ringwald 
12897b181629SMatthias Ringwald     // configure ERTM
12907b181629SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_mandatory, max_transmit, retransmission_timeout_ms,
12917b181629SMatthias Ringwald         monitor_timeout_ms, num_tx_buffers, num_rx_buffers, buffer, size);
12921b9cb13dSMatthias Ringwald 
12931b9cb13dSMatthias Ringwald     // add to connections list
12941b9cb13dSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
12951b9cb13dSMatthias Ringwald 
12961b9cb13dSMatthias Ringwald     // store local_cid
12971b9cb13dSMatthias Ringwald     if (out_local_cid){
12981b9cb13dSMatthias Ringwald        *out_local_cid = channel->local_cid;
12991b9cb13dSMatthias Ringwald     }
13001b9cb13dSMatthias Ringwald 
13011b9cb13dSMatthias Ringwald     // check if hci connection is already usable
13021b9cb13dSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
13031b9cb13dSMatthias Ringwald     if (conn){
13041b9cb13dSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
13051b9cb13dSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
13061b9cb13dSMatthias Ringwald         // check if remote supported fearures are already received
13071b9cb13dSMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
13081b9cb13dSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
13091b9cb13dSMatthias Ringwald         }
13101b9cb13dSMatthias Ringwald     }
13111b9cb13dSMatthias Ringwald 
13121b9cb13dSMatthias Ringwald     l2cap_run();
13131b9cb13dSMatthias Ringwald 
13141b9cb13dSMatthias Ringwald     return 0;
13151b9cb13dSMatthias Ringwald }
13161b9cb13dSMatthias Ringwald #endif
13171b9cb13dSMatthias Ringwald 
1318ce8f182eSMatthias Ringwald void
1319ce8f182eSMatthias Ringwald l2cap_disconnect(uint16_t local_cid, uint8_t reason){
1320e0abb8e7S[email protected]     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
1321b35f641cSmatthias.ringwald     // find channel for local_cid
1322b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1323f62db1e3Smatthias.ringwald     if (channel) {
1324e7ff783cSmatthias.ringwald         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1325f62db1e3Smatthias.ringwald     }
13262cd0be45Smatthias.ringwald     // process
13272cd0be45Smatthias.ringwald     l2cap_run();
132843625864Smatthias.ringwald }
13291e6aba47Smatthias.ringwald 
1330afde0c52Smatthias.ringwald static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
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) != 0) continue;
1336c22aecc9S[email protected]         // channel for this address found
1337c22aecc9S[email protected]         switch (channel->state){
1338c22aecc9S[email protected]             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
1339c22aecc9S[email protected]             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1340afde0c52Smatthias.ringwald                 // failure, forward error code
1341afde0c52Smatthias.ringwald                 l2cap_emit_channel_opened(channel, status);
1342afde0c52Smatthias.ringwald                 // discard channel
13439dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
1344665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1345d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
1346c22aecc9S[email protected]                 break;
1347c22aecc9S[email protected]             default:
1348c22aecc9S[email protected]                 break;
1349afde0c52Smatthias.ringwald         }
1350afde0c52Smatthias.ringwald     }
1351afde0c52Smatthias.ringwald }
1352afde0c52Smatthias.ringwald 
1353afde0c52Smatthias.ringwald static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
1354665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1355665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1356665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1357665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1358058e3d6bSMatthias Ringwald         if ( ! bd_addr_cmp( channel->address, address) ){
13592df5dadcS[email protected]             l2cap_handle_connection_complete(handle, channel);
1360afde0c52Smatthias.ringwald         }
1361afde0c52Smatthias.ringwald     }
13626fdcc387Smatthias.ringwald     // process
13636fdcc387Smatthias.ringwald     l2cap_run();
1364afde0c52Smatthias.ringwald }
136509e9d05bSMatthias Ringwald #endif
1366b448a0e7Smatthias.ringwald 
136733c40538SMatthias Ringwald static void l2cap_notify_channel_can_send(void){
136809e9d05bSMatthias Ringwald 
136909e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
137033c40538SMatthias Ringwald     btstack_linked_list_iterator_t it;
137133c40538SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
137233c40538SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
137333c40538SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
137433c40538SMatthias Ringwald         if (!channel->waiting_for_can_send_now) continue;
1375fc64f94aSMatthias Ringwald         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
137633c40538SMatthias Ringwald         channel->waiting_for_can_send_now = 0;
137734e7e577SMatthias Ringwald         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
137833c40538SMatthias Ringwald     }
137909e9d05bSMatthias Ringwald #endif
138044276248SMatthias Ringwald 
13812125de09SMatthias Ringwald     int i;
13822125de09SMatthias Ringwald     for (i=0;i<L2CAP_FIXED_CHANNEL_TABLE_SIZE;i++){
1383773c4106SMatthias Ringwald         if (!fixed_channels[i].callback) continue;
13842125de09SMatthias Ringwald         if (!fixed_channels[i].waiting_for_can_send_now) continue;
138535454696SMatthias Ringwald         int can_send = 0;
138634e7e577SMatthias Ringwald         if (l2cap_fixed_channel_table_index_is_le(i)){
138735454696SMatthias Ringwald #ifdef ENABLE_BLE
138834e7e577SMatthias Ringwald             can_send = hci_can_send_acl_le_packet_now();
138935454696SMatthias Ringwald #endif
139034e7e577SMatthias Ringwald         } else {
139135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
139234e7e577SMatthias Ringwald             can_send = hci_can_send_acl_classic_packet_now();
139335454696SMatthias Ringwald #endif
139434e7e577SMatthias Ringwald         }
139534e7e577SMatthias Ringwald         if (!can_send) continue;
139634e7e577SMatthias Ringwald         fixed_channels[i].waiting_for_can_send_now = 0;
139734e7e577SMatthias Ringwald         l2cap_emit_can_send_now(fixed_channels[i].callback, l2cap_fixed_channel_table_channel_id_for_index(i));
13982125de09SMatthias Ringwald     }
139933c40538SMatthias Ringwald }
140033c40538SMatthias Ringwald 
1401d9a7306aSMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
1402afde0c52Smatthias.ringwald 
14039ec2630cSMatthias Ringwald     UNUSED(packet_type);
14049ec2630cSMatthias Ringwald     UNUSED(cid);
14059ec2630cSMatthias Ringwald     UNUSED(size);
14069ec2630cSMatthias Ringwald 
1407afde0c52Smatthias.ringwald     bd_addr_t address;
1408afde0c52Smatthias.ringwald     hci_con_handle_t handle;
14092d00edd4Smatthias.ringwald     int hci_con_used;
141009e9d05bSMatthias Ringwald     btstack_linked_list_iterator_t it;
141109e9d05bSMatthias Ringwald 
141209e9d05bSMatthias Ringwald     // avoid unused warnings
1413f3963406SMatthias Ringwald     UNUSED(address);
1414f3963406SMatthias Ringwald     UNUSED(hci_con_used);
1415f3963406SMatthias Ringwald     UNUSED(it);
1416f22209dfSMatthias Ringwald     UNUSED(handle);
1417afde0c52Smatthias.ringwald 
14180e2df43fSMatthias Ringwald     switch(hci_event_packet_get_type(packet)){
1419afde0c52Smatthias.ringwald 
142009e9d05bSMatthias Ringwald         // Notify channel packet handler if they can send now
142109e9d05bSMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
142209e9d05bSMatthias Ringwald         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
142309e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
142409e9d05bSMatthias Ringwald             l2cap_notify_channel_can_send();
142509e9d05bSMatthias Ringwald             break;
142609e9d05bSMatthias Ringwald 
142709e9d05bSMatthias Ringwald         case HCI_EVENT_COMMAND_STATUS:
142809e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
142909e9d05bSMatthias Ringwald             break;
143009e9d05bSMatthias Ringwald 
143109e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1432afde0c52Smatthias.ringwald         // handle connection complete events
1433afde0c52Smatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
1434724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], address);
1435afde0c52Smatthias.ringwald             if (packet[2] == 0){
1436f8fbdce0SMatthias Ringwald                 handle = little_endian_read_16(packet, 3);
1437afde0c52Smatthias.ringwald                 l2cap_handle_connection_success_for_addr(address, handle);
1438afde0c52Smatthias.ringwald             } else {
1439afde0c52Smatthias.ringwald                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
1440afde0c52Smatthias.ringwald             }
1441afde0c52Smatthias.ringwald             break;
1442afde0c52Smatthias.ringwald 
1443afde0c52Smatthias.ringwald         // handle successful create connection cancel command
1444afde0c52Smatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
1445073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
1446afde0c52Smatthias.ringwald                 if (packet[5] == 0){
1447724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[6], address);
1448afde0c52Smatthias.ringwald                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
1449afde0c52Smatthias.ringwald                     l2cap_handle_connection_failed_for_addr(address, 0x16);
145003cfbabcSmatthias.ringwald                 }
14511e6aba47Smatthias.ringwald             }
145239d59809Smatthias.ringwald             l2cap_run();    // try sending signaling packets first
145339d59809Smatthias.ringwald             break;
145409e9d05bSMatthias Ringwald #endif
145527a923d0Smatthias.ringwald 
14561e6aba47Smatthias.ringwald         // handle disconnection complete events
1457afde0c52Smatthias.ringwald         case HCI_EVENT_DISCONNECTION_COMPLETE:
1458c22aecc9S[email protected]             // send l2cap disconnect events for all channels on this handle and free them
145909e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1460d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1461665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1462665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1463665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1464fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
146515ec09bbSmatthias.ringwald                 l2cap_emit_channel_closed(channel);
14669dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
1467665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1468d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
146927a923d0Smatthias.ringwald             }
147009e9d05bSMatthias Ringwald #endif
1471a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1472d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1473991fea48SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1474991fea48SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1475991fea48SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1476991fea48SMatthias Ringwald                 if (channel->con_handle != handle) continue;
1477991fea48SMatthias Ringwald                 l2cap_emit_channel_closed(channel);
1478991fea48SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1479991fea48SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
1480991fea48SMatthias Ringwald             }
1481991fea48SMatthias Ringwald #endif
1482afde0c52Smatthias.ringwald             break;
1483fcadd0caSmatthias.ringwald 
1484ee091cf1Smatthias.ringwald         // HCI Connection Timeouts
148509e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1486afde0c52Smatthias.ringwald         case L2CAP_EVENT_TIMEOUT_CHECK:
1487f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
1488bd04d84aSMatthias Ringwald             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
148980ca58a0Smatthias.ringwald             if (hci_authentication_active_for_handle(handle)) break;
14902d00edd4Smatthias.ringwald             hci_con_used = 0;
1491665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1492665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1493665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1494fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
14952d00edd4Smatthias.ringwald                 hci_con_used = 1;
1496c22aecc9S[email protected]                 break;
1497ee091cf1Smatthias.ringwald             }
14982d00edd4Smatthias.ringwald             if (hci_con_used) break;
1499d94d3cafS[email protected]             if (!hci_can_send_command_packet_now()) break;
15009edc8742Smatthias.ringwald             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
1501afde0c52Smatthias.ringwald             break;
1502ee091cf1Smatthias.ringwald 
1503df3354fcS[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1504f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1505665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1506665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1507665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1508fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
15092df5dadcS[email protected]                 l2cap_handle_remote_supported_features_received(channel);
1510df3354fcS[email protected]                 break;
1511df3354fcS[email protected]             }
1512c22aecc9S[email protected]             break;
1513df3354fcS[email protected] 
15145611a760SMatthias Ringwald         case GAP_EVENT_SECURITY_LEVEL:
1515f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
1516bd63148eS[email protected]             log_info("l2cap - security level update");
1517665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1518665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1519665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1520fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
15215533f01eS[email protected] 
1522bd63148eS[email protected]                 log_info("l2cap - state %u", channel->state);
1523bd63148eS[email protected] 
1524e569dfd9SMatthias Ringwald                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
15255533f01eS[email protected]                 gap_security_level_t required_level = channel->required_security_level;
15265533f01eS[email protected] 
1527df3354fcS[email protected]                 switch (channel->state){
1528df3354fcS[email protected]                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
15295533f01eS[email protected]                         if (actual_level >= required_level){
153052606043SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
153152606043SMatthias Ringwald                             // we need to know if ERTM is supported before sending a config response
153252606043SMatthias Ringwald                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
153352606043SMatthias Ringwald                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
153452606043SMatthias Ringwald                             channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
153552606043SMatthias Ringwald #else
1536f85a9399S[email protected]                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
153744276248SMatthias Ringwald                             l2cap_emit_incoming_connection(channel);
153852606043SMatthias Ringwald #endif
15391eb2563eS[email protected]                         } else {
1540775ecc36SMatthias Ringwald                             channel->reason = 0x0003; // security block
15411eb2563eS[email protected]                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
15421eb2563eS[email protected]                         }
1543df3354fcS[email protected]                         break;
1544df3354fcS[email protected] 
1545df3354fcS[email protected]                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
15465533f01eS[email protected]                         if (actual_level >= required_level){
15471b9cb13dSMatthias Ringwald                             l2cap_ready_to_connect(channel);
1548df3354fcS[email protected]                         } else {
1549df3354fcS[email protected]                             // disconnnect, authentication not good enough
1550df3354fcS[email protected]                             hci_disconnect_security_block(handle);
1551df3354fcS[email protected]                         }
1552df3354fcS[email protected]                         break;
1553df3354fcS[email protected] 
1554df3354fcS[email protected]                     default:
1555df3354fcS[email protected]                         break;
1556df3354fcS[email protected]                 }
1557f85a9399S[email protected]             }
1558f85a9399S[email protected]             break;
155909e9d05bSMatthias Ringwald #endif
1560f85a9399S[email protected] 
1561afde0c52Smatthias.ringwald         default:
1562afde0c52Smatthias.ringwald             break;
1563afde0c52Smatthias.ringwald     }
1564afde0c52Smatthias.ringwald 
1565bd63148eS[email protected]     l2cap_run();
15661e6aba47Smatthias.ringwald }
15671e6aba47Smatthias.ringwald 
1568e74c5f58SMatthias 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){
15694cf56b4aSmatthias.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."
15702b360848Smatthias.ringwald     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
15712b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].handle = handle;
15722b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].code = code;
15732b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].sig_id = sig_id;
1574e74c5f58SMatthias Ringwald         signaling_responses[signaling_responses_pending].cid = cid;
15752b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].data = data;
15762b360848Smatthias.ringwald         signaling_responses_pending++;
15772b360848Smatthias.ringwald         l2cap_run();
15782b360848Smatthias.ringwald     }
15792b360848Smatthias.ringwald }
15802b360848Smatthias.ringwald 
158109e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
158209e9d05bSMatthias Ringwald static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
158309e9d05bSMatthias Ringwald     channel->remote_sig_id = identifier;
158409e9d05bSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
158509e9d05bSMatthias Ringwald     l2cap_run();
158609e9d05bSMatthias Ringwald }
158709e9d05bSMatthias Ringwald 
1588b35f641cSmatthias.ringwald static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
1589645658c9Smatthias.ringwald 
15909da54300S[email protected]     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
1591645658c9Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
1592645658c9Smatthias.ringwald     if (!service) {
1593645658c9Smatthias.ringwald         // 0x0002 PSM not supported
1594e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
1595645658c9Smatthias.ringwald         return;
1596645658c9Smatthias.ringwald     }
1597645658c9Smatthias.ringwald 
15985061f3afS[email protected]     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
1599645658c9Smatthias.ringwald     if (!hci_connection) {
16002b360848Smatthias.ringwald         //
16019da54300S[email protected]         log_error("no hci_connection for handle %u", handle);
1602645658c9Smatthias.ringwald         return;
1603645658c9Smatthias.ringwald     }
16042bd8b7e7S[email protected] 
1605645658c9Smatthias.ringwald     // alloc structure
16069da54300S[email protected]     // log_info("l2cap_handle_connection_request register channel");
1607da144af5SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, hci_connection->address, BD_ADDR_TYPE_CLASSIC,
1608da144af5SMatthias Ringwald     psm, service->mtu, service->required_security_level);
16092b360848Smatthias.ringwald     if (!channel){
16102b360848Smatthias.ringwald         // 0x0004 No resources available
1611e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
16122b360848Smatthias.ringwald         return;
16132b360848Smatthias.ringwald     }
1614da144af5SMatthias Ringwald 
1615fc64f94aSMatthias Ringwald     channel->con_handle = handle;
1616b35f641cSmatthias.ringwald     channel->remote_cid = source_cid;
1617b1988dceSmatthias.ringwald     channel->remote_sig_id = sig_id;
1618645658c9Smatthias.ringwald 
1619f53da564S[email protected]     // limit local mtu to max acl packet length - l2cap header
16202985cb84Smatthias.ringwald     if (channel->local_mtu > l2cap_max_mtu()) {
16212985cb84Smatthias.ringwald         channel->local_mtu = l2cap_max_mtu();
16229775e25bSmatthias.ringwald     }
16239775e25bSmatthias.ringwald 
1624645658c9Smatthias.ringwald     // set initial state
1625df3354fcS[email protected]     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
1626a24785d0SMatthias Ringwald     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
1627e405ae81Smatthias.ringwald 
1628645658c9Smatthias.ringwald     // add to connections list
1629665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1630645658c9Smatthias.ringwald 
1631f85a9399S[email protected]     // assert security requirements
16321eb2563eS[email protected]     gap_request_security_level(handle, channel->required_security_level);
1633e405ae81Smatthias.ringwald }
1634645658c9Smatthias.ringwald 
1635ce8f182eSMatthias Ringwald void l2cap_accept_connection(uint16_t local_cid){
1636e0abb8e7S[email protected]     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
1637b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1638e405ae81Smatthias.ringwald     if (!channel) {
1639ce8f182eSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
1640e405ae81Smatthias.ringwald         return;
1641e405ae81Smatthias.ringwald     }
1642e405ae81Smatthias.ringwald 
164343ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
164443ec931dSMatthias Ringwald     // configure L2CAP Basic mode
164543ec931dSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
164643ec931dSMatthias Ringwald #endif
164743ec931dSMatthias Ringwald 
1648552d92a1Smatthias.ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
1649e405ae81Smatthias.ringwald 
1650552d92a1Smatthias.ringwald     // process
1651552d92a1Smatthias.ringwald     l2cap_run();
1652e405ae81Smatthias.ringwald }
1653645658c9Smatthias.ringwald 
165443ec931dSMatthias Ringwald 
165543ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
16562b70d705SMatthias Ringwald uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, int ertm_mandatory, uint8_t max_transmit,
1657501329faSMatthias 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){
1658501329faSMatthias Ringwald 
165943ec931dSMatthias Ringwald     log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
166043ec931dSMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
166143ec931dSMatthias Ringwald     if (!channel) {
166243ec931dSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
16632b70d705SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
166443ec931dSMatthias Ringwald     }
166543ec931dSMatthias Ringwald 
16662b70d705SMatthias Ringwald     // validate local config
16672b70d705SMatthias 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);
16682b70d705SMatthias Ringwald     if (result) return result;
16692b70d705SMatthias Ringwald 
167043ec931dSMatthias Ringwald     // configure L2CAP ERTM
16717b181629SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_mandatory, max_transmit, retransmission_timeout_ms, monitor_timeout_ms, num_tx_buffers, num_rx_buffers, buffer, size);
167243ec931dSMatthias Ringwald 
16737b181629SMatthias Ringwald     // continue
167443ec931dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
167543ec931dSMatthias Ringwald 
167643ec931dSMatthias Ringwald     // process
167743ec931dSMatthias Ringwald     l2cap_run();
16782b70d705SMatthias Ringwald 
16792b70d705SMatthias Ringwald     return ERROR_CODE_SUCCESS;
168043ec931dSMatthias Ringwald }
168143ec931dSMatthias Ringwald #endif
168243ec931dSMatthias Ringwald 
168343ec931dSMatthias Ringwald 
16847ef6a7bbSMatthias Ringwald void l2cap_decline_connection(uint16_t local_cid){
16857ef6a7bbSMatthias Ringwald     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
1686b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
1687e405ae81Smatthias.ringwald     if (!channel) {
1688ce8f182eSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
1689e405ae81Smatthias.ringwald         return;
1690e405ae81Smatthias.ringwald     }
1691e7ff783cSmatthias.ringwald     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
16927ef6a7bbSMatthias Ringwald     channel->reason = 0x04; // no resources available
1693e7ff783cSmatthias.ringwald     l2cap_run();
1694645658c9Smatthias.ringwald }
1695645658c9Smatthias.ringwald 
16967f02f414SMatthias Ringwald static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
1697b1988dceSmatthias.ringwald 
1698b1988dceSmatthias.ringwald     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1699b1988dceSmatthias.ringwald 
1700f8fbdce0SMatthias Ringwald     uint16_t flags = little_endian_read_16(command, 6);
170163a7246aSmatthias.ringwald     if (flags & 1) {
170263a7246aSmatthias.ringwald         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
170363a7246aSmatthias.ringwald     }
170463a7246aSmatthias.ringwald 
17052784b77dSmatthias.ringwald     // accept the other's configuration options
1706f8fbdce0SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
17073de7c0caSmatthias.ringwald     uint16_t pos     = 8;
17083de7c0caSmatthias.ringwald     while (pos < end_pos){
170963a7246aSmatthias.ringwald         uint8_t option_hint = command[pos] >> 7;
171063a7246aSmatthias.ringwald         uint8_t option_type = command[pos] & 0x7f;
171163a7246aSmatthias.ringwald         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
171263a7246aSmatthias.ringwald         pos++;
17131dc511deSmatthias.ringwald         uint8_t length = command[pos++];
17141dc511deSmatthias.ringwald         // MTU { type(8): 1, len(8):2, MTU(16) }
171563a7246aSmatthias.ringwald         if (option_type == 1 && length == 2){
1716f8fbdce0SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, pos);
17179d139fbaSMatthias Ringwald             if (channel->remote_mtu > l2cap_max_mtu()){
17189d139fbaSMatthias Ringwald                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
17199d139fbaSMatthias Ringwald                 channel->remote_mtu = l2cap_max_mtu();
17209d139fbaSMatthias Ringwald             }
172163a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
172263a7246aSmatthias.ringwald         }
17230fe7a9d0S[email protected]         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
17240fe7a9d0S[email protected]         if (option_type == 2 && length == 2){
1725f8fbdce0SMatthias Ringwald             channel->flush_timeout = little_endian_read_16(command, pos);
17260fe7a9d0S[email protected]         }
1727f2fa388dSMatthias Ringwald 
17286dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
17296dca2a0cSMatthias Ringwald         // Retransmission and Flow Control Option
17306dca2a0cSMatthias Ringwald         if (option_type == 4 && length == 9){
17313232a1c6SMatthias Ringwald             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
1732ac8f1300SMatthias Ringwald             switch(channel->mode){
1733ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
173425cd60d3SMatthias Ringwald                     // Store remote config
1735bbc0a9e7SMatthias Ringwald                     channel->remote_tx_window_size = command[pos+1];
1736bbc0a9e7SMatthias Ringwald                     channel->remote_max_transmit   = command[pos+2];
1737bbc0a9e7SMatthias Ringwald                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
1738bbc0a9e7SMatthias Ringwald                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
1739bbc0a9e7SMatthias Ringwald                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u",
1740bbc0a9e7SMatthias Ringwald                         channel->remote_tx_window_size,
1741bbc0a9e7SMatthias Ringwald                         channel->remote_max_transmit,
1742bbc0a9e7SMatthias Ringwald                         channel->remote_retransmission_timeout_ms,
1743bbc0a9e7SMatthias Ringwald                         channel->remote_monitor_timeout_ms);
1744bbc0a9e7SMatthias Ringwald                     // we store remote MPS in remote_mtu, might need to get re-evaluated
1745bbc0a9e7SMatthias Ringwald                     channel->remote_mtu = little_endian_read_16(command, pos + 7);
174625cd60d3SMatthias Ringwald                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
174725cd60d3SMatthias Ringwald                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
174825cd60d3SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1749ac8f1300SMatthias Ringwald                     } else {
1750ac8f1300SMatthias Ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1751ac8f1300SMatthias Ringwald                     }
1752ac8f1300SMatthias Ringwald                     break;
1753ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
1754ac8f1300SMatthias Ringwald                     switch (mode){
1755ac8f1300SMatthias Ringwald                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
1756ac8f1300SMatthias Ringwald                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
1757ac8f1300SMatthias Ringwald                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
1758ac8f1300SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1759ac8f1300SMatthias Ringwald                             }
1760ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
1761ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1762ac8f1300SMatthias Ringwald                             break;
1763ac8f1300SMatthias Ringwald                         default: // case L2CAP_CHANNEL_MODE_BASIC:
1764ac8f1300SMatthias Ringwald                             // TODO store and evaluate configuration
1765ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1766ac8f1300SMatthias Ringwald                             break;
1767ac8f1300SMatthias Ringwald                     }
1768ac8f1300SMatthias Ringwald                     break;
1769ac8f1300SMatthias Ringwald                 default:
1770ac8f1300SMatthias Ringwald                     break;
1771ac8f1300SMatthias Ringwald             }
17723232a1c6SMatthias Ringwald         }
17736dca2a0cSMatthias Ringwald #endif
177463a7246aSmatthias.ringwald         // check for unknown options
177563a7246aSmatthias.ringwald         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
1776c177a91cS[email protected]             log_info("l2cap cid %u, unknown options", channel->local_cid);
177763a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
17781dc511deSmatthias.ringwald         }
17791dc511deSmatthias.ringwald         pos += length;
17801dc511deSmatthias.ringwald     }
17812784b77dSmatthias.ringwald }
17822784b77dSmatthias.ringwald 
1783f2fa388dSMatthias Ringwald static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
1784f2fa388dSMatthias Ringwald     log_info("l2cap_signaling_handle_configure_response");
17853232a1c6SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
17863232a1c6SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1787f2fa388dSMatthias Ringwald     uint16_t pos     = 10;
17883232a1c6SMatthias Ringwald     while (pos < end_pos){
17893232a1c6SMatthias Ringwald         uint8_t option_hint = command[pos] >> 7;
17903232a1c6SMatthias Ringwald         uint8_t option_type = command[pos] & 0x7f;
17913232a1c6SMatthias Ringwald         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
17923232a1c6SMatthias Ringwald         pos++;
17933232a1c6SMatthias Ringwald         uint8_t length = command[pos++];
17943232a1c6SMatthias Ringwald 
17953232a1c6SMatthias Ringwald         // Retransmission and Flow Control Option
17963232a1c6SMatthias Ringwald         if (option_type == 4 && length == 9){
1797ac8f1300SMatthias Ringwald             switch (channel->mode){
1798ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
1799f2fa388dSMatthias Ringwald                     if (channel->ertm_mandatory){
1800ac8f1300SMatthias Ringwald                         // ??
1801f2fa388dSMatthias Ringwald                     } else {
1802ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
1803ac8f1300SMatthias Ringwald                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
1804f2fa388dSMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
18053232a1c6SMatthias Ringwald                         }
18063232a1c6SMatthias Ringwald                     }
1807ac8f1300SMatthias Ringwald                     break;
1808ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
1809ac8f1300SMatthias Ringwald                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
1810ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
1811ac8f1300SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1812ac8f1300SMatthias Ringwald                     }
1813ac8f1300SMatthias Ringwald                     break;
1814ac8f1300SMatthias Ringwald                 default:
1815ac8f1300SMatthias Ringwald                     break;
18163232a1c6SMatthias Ringwald             }
1817f2fa388dSMatthias Ringwald         }
18183232a1c6SMatthias Ringwald 
18193232a1c6SMatthias Ringwald         // check for unknown options
18203232a1c6SMatthias Ringwald         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
18213232a1c6SMatthias Ringwald             log_info("l2cap cid %u, unknown options", channel->local_cid);
18223232a1c6SMatthias Ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
18233232a1c6SMatthias Ringwald         }
18243232a1c6SMatthias Ringwald 
18253232a1c6SMatthias Ringwald         pos += length;
18263232a1c6SMatthias Ringwald     }
18273232a1c6SMatthias Ringwald #endif
18283232a1c6SMatthias Ringwald }
18293232a1c6SMatthias Ringwald 
1830fa8473a4Smatthias.ringwald static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
18319da54300S[email protected]     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
183273cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
183373cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
1834019f9b43SMatthias Ringwald     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
1835019f9b43SMatthias Ringwald     if (channel->state == L2CAP_STATE_OPEN) return 0;
1836fa8473a4Smatthias.ringwald     return 1;
1837fa8473a4Smatthias.ringwald }
1838fa8473a4Smatthias.ringwald 
1839fa8473a4Smatthias.ringwald 
18407f02f414SMatthias Ringwald static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
18411e6aba47Smatthias.ringwald 
184200d93d79Smatthias.ringwald     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
184300d93d79Smatthias.ringwald     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
184438e5900eSmatthias.ringwald     uint16_t result = 0;
18451e6aba47Smatthias.ringwald 
18469da54300S[email protected]     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
1847b35f641cSmatthias.ringwald 
18489a011532Smatthias.ringwald     // handle DISCONNECT REQUESTS seperately
18499a011532Smatthias.ringwald     if (code == DISCONNECTION_REQUEST){
18509a011532Smatthias.ringwald         switch (channel->state){
1851fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
18529a011532Smatthias.ringwald             case L2CAP_STATE_OPEN:
18532b83fb7dSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
18549a011532Smatthias.ringwald             case L2CAP_STATE_WAIT_DISCONNECT:
18559a011532Smatthias.ringwald                 l2cap_handle_disconnect_request(channel, identifier);
18569a011532Smatthias.ringwald                 break;
18579a011532Smatthias.ringwald 
18589a011532Smatthias.ringwald             default:
18599a011532Smatthias.ringwald                 // ignore in other states
18609a011532Smatthias.ringwald                 break;
18619a011532Smatthias.ringwald         }
18629a011532Smatthias.ringwald         return;
18639a011532Smatthias.ringwald     }
18649a011532Smatthias.ringwald 
186556081214Smatthias.ringwald     // @STATEMACHINE(l2cap)
18661e6aba47Smatthias.ringwald     switch (channel->state) {
18671e6aba47Smatthias.ringwald 
18681e6aba47Smatthias.ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
18691e6aba47Smatthias.ringwald             switch (code){
18701e6aba47Smatthias.ringwald                 case CONNECTION_RESPONSE:
18715932bd7cS[email protected]                     l2cap_stop_rtx(channel);
1872f8fbdce0SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
187338e5900eSmatthias.ringwald                     switch (result) {
187438e5900eSmatthias.ringwald                         case 0:
1875169f8b28Smatthias.ringwald                             // successful connection
1876f8fbdce0SMatthias Ringwald                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1877fa8473a4Smatthias.ringwald                             channel->state = L2CAP_STATE_CONFIG;
187828ca2b46S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
187938e5900eSmatthias.ringwald                             break;
188038e5900eSmatthias.ringwald                         case 1:
18815932bd7cS[email protected]                             // connection pending. get some coffee, but start the ERTX
18825932bd7cS[email protected]                             l2cap_start_ertx(channel);
188338e5900eSmatthias.ringwald                             break;
188438e5900eSmatthias.ringwald                         default:
1885eb920dbeSmatthias.ringwald                             // channel closed
1886eb920dbeSmatthias.ringwald                             channel->state = L2CAP_STATE_CLOSED;
1887f32b992eSmatthias.ringwald                             // map l2cap connection response result to BTstack status enumeration
188838e5900eSmatthias.ringwald                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
1889eb920dbeSmatthias.ringwald 
1890eb920dbeSmatthias.ringwald                             // drop link key if security block
1891eb920dbeSmatthias.ringwald                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
189215a95bd5SMatthias Ringwald                                 gap_drop_link_key_for_bd_addr(channel->address);
1893eb920dbeSmatthias.ringwald                             }
1894eb920dbeSmatthias.ringwald 
1895eb920dbeSmatthias.ringwald                             // discard channel
1896665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1897d3a9df87Smatthias.ringwald                             btstack_memory_l2cap_channel_free(channel);
189838e5900eSmatthias.ringwald                             break;
18991e6aba47Smatthias.ringwald                     }
19001e6aba47Smatthias.ringwald                     break;
190138e5900eSmatthias.ringwald 
190238e5900eSmatthias.ringwald                 default:
19031e6aba47Smatthias.ringwald                     //@TODO: implement other signaling packets
190438e5900eSmatthias.ringwald                     break;
19051e6aba47Smatthias.ringwald             }
19061e6aba47Smatthias.ringwald             break;
19071e6aba47Smatthias.ringwald 
1908fa8473a4Smatthias.ringwald         case L2CAP_STATE_CONFIG:
1909f8fbdce0SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
1910ae280e73Smatthias.ringwald             switch (code) {
1911ae280e73Smatthias.ringwald                 case CONFIGURE_REQUEST:
191228ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1913ae280e73Smatthias.ringwald                     l2cap_signaling_handle_configure_request(channel, command);
191463a7246aSmatthias.ringwald                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
191563a7246aSmatthias.ringwald                         // only done if continuation not set
191663a7246aSmatthias.ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
191763a7246aSmatthias.ringwald                     }
1918ae280e73Smatthias.ringwald                     break;
19191e6aba47Smatthias.ringwald                 case CONFIGURE_RESPONSE:
19205932bd7cS[email protected]                     l2cap_stop_rtx(channel);
1921f2fa388dSMatthias Ringwald                     l2cap_signaling_handle_configure_response(channel, result, command);
19225932bd7cS[email protected]                     switch (result){
19235932bd7cS[email protected]                         case 0: // success
19245932bd7cS[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
19255932bd7cS[email protected]                             break;
19265932bd7cS[email protected]                         case 4: // pending
19275932bd7cS[email protected]                             l2cap_start_ertx(channel);
19285932bd7cS[email protected]                             break;
19295932bd7cS[email protected]                         default:
1930a32d6a03SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1931a32d6a03SMatthias Ringwald                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
1932a32d6a03SMatthias Ringwald                                 // remote does not offer ertm but it's required
1933a32d6a03SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1934a32d6a03SMatthias Ringwald                                 break;
1935a32d6a03SMatthias Ringwald                             }
1936a32d6a03SMatthias Ringwald #endif
1937fe9d8984S[email protected]                             // retry on negative result
1938fe9d8984S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1939fe9d8984S[email protected]                             break;
1940fe9d8984S[email protected]                     }
19415a67bd4aSmatthias.ringwald                     break;
19425a67bd4aSmatthias.ringwald                 default:
19435a67bd4aSmatthias.ringwald                     break;
19441e6aba47Smatthias.ringwald             }
1945fa8473a4Smatthias.ringwald             if (l2cap_channel_ready_for_open(channel)){
1946fa8473a4Smatthias.ringwald                 // for open:
19475a67bd4aSmatthias.ringwald                 channel->state = L2CAP_STATE_OPEN;
1948fa8473a4Smatthias.ringwald                 l2cap_emit_channel_opened(channel, 0);
1949c8e4258aSmatthias.ringwald             }
1950c8e4258aSmatthias.ringwald             break;
1951f62db1e3Smatthias.ringwald 
1952f62db1e3Smatthias.ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
1953f62db1e3Smatthias.ringwald             switch (code) {
1954f62db1e3Smatthias.ringwald                 case DISCONNECTION_RESPONSE:
195527a923d0Smatthias.ringwald                     l2cap_finialize_channel_close(channel);
195627a923d0Smatthias.ringwald                     break;
19575a67bd4aSmatthias.ringwald                 default:
19585a67bd4aSmatthias.ringwald                     //@TODO: implement other signaling packets
19595a67bd4aSmatthias.ringwald                     break;
196027a923d0Smatthias.ringwald             }
196127a923d0Smatthias.ringwald             break;
196284836b65Smatthias.ringwald 
196384836b65Smatthias.ringwald         case L2CAP_STATE_CLOSED:
196484836b65Smatthias.ringwald             // @TODO handle incoming requests
196584836b65Smatthias.ringwald             break;
196684836b65Smatthias.ringwald 
196784836b65Smatthias.ringwald         case L2CAP_STATE_OPEN:
196884836b65Smatthias.ringwald             //@TODO: implement other signaling packets, e.g. re-configure
196984836b65Smatthias.ringwald             break;
197010642e45Smatthias.ringwald         default:
197110642e45Smatthias.ringwald             break;
197227a923d0Smatthias.ringwald     }
19739da54300S[email protected]     // log_info("new state %u", channel->state);
197427a923d0Smatthias.ringwald }
197527a923d0Smatthias.ringwald 
197600d93d79Smatthias.ringwald 
19777f02f414SMatthias Ringwald static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
197800d93d79Smatthias.ringwald 
19791b9cb13dSMatthias Ringwald     btstack_linked_list_iterator_t it;
19801b9cb13dSMatthias Ringwald 
198100d93d79Smatthias.ringwald     // get code, signalind identifier and command len
198200d93d79Smatthias.ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
198300d93d79Smatthias.ringwald     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
198400d93d79Smatthias.ringwald 
19851b9cb13dSMatthias Ringwald     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
19861b9cb13dSMatthias Ringwald     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_RESPONSE){
1987e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
198800d93d79Smatthias.ringwald         return;
198900d93d79Smatthias.ringwald     }
199000d93d79Smatthias.ringwald 
199100d93d79Smatthias.ringwald     // general commands without an assigned channel
199200d93d79Smatthias.ringwald     switch(code) {
199300d93d79Smatthias.ringwald 
199400d93d79Smatthias.ringwald         case CONNECTION_REQUEST: {
1995f8fbdce0SMatthias Ringwald             uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1996f8fbdce0SMatthias Ringwald             uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
199700d93d79Smatthias.ringwald             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
19982b83fb7dSmatthias.ringwald             return;
199900d93d79Smatthias.ringwald         }
200000d93d79Smatthias.ringwald 
20012b360848Smatthias.ringwald         case ECHO_REQUEST:
2002e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
20032b83fb7dSmatthias.ringwald             return;
200400d93d79Smatthias.ringwald 
200500d93d79Smatthias.ringwald         case INFORMATION_REQUEST: {
2006f8fbdce0SMatthias Ringwald             uint16_t infoType = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2007e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, infoType);
20082b83fb7dSmatthias.ringwald             return;
200900d93d79Smatthias.ringwald         }
201000d93d79Smatthias.ringwald 
20111b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
20121b9cb13dSMatthias Ringwald         case INFORMATION_RESPONSE: {
20131b9cb13dSMatthias Ringwald             hci_connection_t * connection = hci_connection_for_handle(handle);
20141b9cb13dSMatthias Ringwald             if (!connection) return;
20151b9cb13dSMatthias Ringwald             uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
20161b9cb13dSMatthias Ringwald             uint16_t result =  little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
20171b9cb13dSMatthias Ringwald             if (result != 0) return;
2018543b84e4SMatthias Ringwald             if (info_type != 0x02) return;
20191b9cb13dSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
20201b9cb13dSMatthias Ringwald             connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2021543b84e4SMatthias Ringwald             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
20221b9cb13dSMatthias Ringwald             // trigger connection request
20231b9cb13dSMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
20241b9cb13dSMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
20251b9cb13dSMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2026543b84e4SMatthias Ringwald                 if (channel->con_handle != handle) continue;
2027543b84e4SMatthias Ringwald                 // bail if ERTM was requested but is not supported
2028543b84e4SMatthias Ringwald                 if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2029f073f086SMatthias Ringwald                     if (channel->ertm_mandatory){
2030543b84e4SMatthias Ringwald                         // channel closed
2031543b84e4SMatthias Ringwald                         channel->state = L2CAP_STATE_CLOSED;
2032543b84e4SMatthias Ringwald                         // map l2cap connection response result to BTstack status enumeration
2033543b84e4SMatthias Ringwald                         l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTD);
2034543b84e4SMatthias Ringwald                         // discard channel
2035543b84e4SMatthias Ringwald                         btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2036543b84e4SMatthias Ringwald                         btstack_memory_l2cap_channel_free(channel);
2037543b84e4SMatthias Ringwald                         continue;
2038f073f086SMatthias Ringwald                     } else {
2039f073f086SMatthias Ringwald                         // fallback to Basic mode
2040f073f086SMatthias Ringwald                         channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2041f073f086SMatthias Ringwald                     }
2042543b84e4SMatthias Ringwald                 }
2043543b84e4SMatthias Ringwald                 // start connecting
20441b9cb13dSMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
20451b9cb13dSMatthias Ringwald                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
20461b9cb13dSMatthias Ringwald                 }
204752606043SMatthias Ringwald                 // respond to connection request
204852606043SMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
204952606043SMatthias Ringwald                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
205052606043SMatthias Ringwald                     l2cap_emit_incoming_connection(channel);
205152606043SMatthias Ringwald                 }
20521b9cb13dSMatthias Ringwald             }
20531b9cb13dSMatthias Ringwald             return;
20541b9cb13dSMatthias Ringwald         }
20551b9cb13dSMatthias Ringwald #endif
20561b9cb13dSMatthias Ringwald 
205700d93d79Smatthias.ringwald         default:
205800d93d79Smatthias.ringwald             break;
205900d93d79Smatthias.ringwald     }
206000d93d79Smatthias.ringwald 
206100d93d79Smatthias.ringwald 
206200d93d79Smatthias.ringwald     // Get potential destination CID
2063f8fbdce0SMatthias Ringwald     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
206400d93d79Smatthias.ringwald 
206500d93d79Smatthias.ringwald     // Find channel for this sig_id and connection handle
2066665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2067665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2068665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2069fc64f94aSMatthias Ringwald         if (channel->con_handle != handle) continue;
207000d93d79Smatthias.ringwald         if (code & 1) {
2071b1988dceSmatthias.ringwald             // match odd commands (responses) by previous signaling identifier
2072b1988dceSmatthias.ringwald             if (channel->local_sig_id == sig_id) {
207300d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
20744e32727eSmatthias.ringwald                 break;
207500d93d79Smatthias.ringwald             }
207600d93d79Smatthias.ringwald         } else {
2077b1988dceSmatthias.ringwald             // match even commands (requests) by local channel id
207800d93d79Smatthias.ringwald             if (channel->local_cid == dest_cid) {
207900d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
20804e32727eSmatthias.ringwald                 break;
208100d93d79Smatthias.ringwald             }
208200d93d79Smatthias.ringwald         }
208300d93d79Smatthias.ringwald     }
208400d93d79Smatthias.ringwald }
208509e9d05bSMatthias Ringwald #endif
208600d93d79Smatthias.ringwald 
2087e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
208809e9d05bSMatthias Ringwald 
208909e9d05bSMatthias Ringwald static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
209009e9d05bSMatthias Ringwald     uint8_t event[6];
209109e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
209209e9d05bSMatthias Ringwald     event[1] = 4;
209309e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
209409e9d05bSMatthias Ringwald     little_endian_store_16(event, 4, result);
209509e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
209609e9d05bSMatthias Ringwald     if (!l2cap_event_packet_handler) return;
209709e9d05bSMatthias Ringwald     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
209809e9d05bSMatthias Ringwald }
209909e9d05bSMatthias Ringwald 
2100c48b2a2cSMatthias Ringwald // @returns valid
2101c48b2a2cSMatthias Ringwald static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
2102e7d0c9aaSMatthias Ringwald     hci_connection_t * connection;
2103c48b2a2cSMatthias Ringwald     uint16_t result;
2104c48b2a2cSMatthias Ringwald     uint8_t  event[10];
210583fd9c76SMatthias Ringwald 
2106cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2107a3dc965aSMatthias Ringwald     btstack_linked_list_iterator_t it;
2108a3dc965aSMatthias Ringwald     l2cap_channel_t * channel;
2109a3dc965aSMatthias Ringwald     uint16_t local_cid;
211083fd9c76SMatthias Ringwald     uint16_t le_psm;
211163f0ac45SMatthias Ringwald     uint16_t new_credits;
211263f0ac45SMatthias Ringwald     uint16_t credits_before;
2113e7d0c9aaSMatthias Ringwald     l2cap_service_t * service;
211411cae19eSMilanka Ringwald     uint16_t source_cid;
211583fd9c76SMatthias Ringwald #endif
211600d93d79Smatthias.ringwald 
21171b8b8d05SMatthias Ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
211823017473SMatthias Ringwald     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u", code, sig_id);
21191b8b8d05SMatthias Ringwald 
21201b8b8d05SMatthias Ringwald     switch (code){
212100d93d79Smatthias.ringwald 
2122c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
2123c48b2a2cSMatthias Ringwald             result = little_endian_read_16(command, 4);
2124ccf076adS[email protected]             l2cap_emit_connection_parameter_update_response(handle, result);
2125ccf076adS[email protected]             break;
2126da886c03S[email protected] 
2127c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_REQUEST:
2128e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
2129da886c03S[email protected]             if (connection){
21306d91fb6cSMatthias Ringwald                 if (connection->role != HCI_ROLE_MASTER){
21316d91fb6cSMatthias Ringwald                     // reject command without notifying upper layer when not in master role
2132c48b2a2cSMatthias Ringwald                     return 0;
21336d91fb6cSMatthias Ringwald                 }
2134da886c03S[email protected]                 int update_parameter = 1;
2135a4c06b28SMatthias Ringwald                 le_connection_parameter_range_t existing_range;
21364ced4e8cSMatthias Ringwald                 gap_get_connection_parameter_range(&existing_range);
2137c48b2a2cSMatthias Ringwald                 uint16_t le_conn_interval_min = little_endian_read_16(command,8);
2138c48b2a2cSMatthias Ringwald                 uint16_t le_conn_interval_max = little_endian_read_16(command,10);
2139c48b2a2cSMatthias Ringwald                 uint16_t le_conn_latency = little_endian_read_16(command,12);
2140c48b2a2cSMatthias Ringwald                 uint16_t le_supervision_timeout = little_endian_read_16(command,14);
2141da886c03S[email protected] 
2142da886c03S[email protected]                 if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
2143da886c03S[email protected]                 if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
2144da886c03S[email protected] 
2145da886c03S[email protected]                 if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
2146da886c03S[email protected]                 if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
2147da886c03S[email protected] 
2148da886c03S[email protected]                 if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
2149da886c03S[email protected]                 if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
2150da886c03S[email protected] 
2151da886c03S[email protected]                 if (update_parameter){
2152da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
2153da886c03S[email protected]                     connection->le_conn_interval_min = le_conn_interval_min;
2154da886c03S[email protected]                     connection->le_conn_interval_max = le_conn_interval_max;
2155da886c03S[email protected]                     connection->le_conn_latency = le_conn_latency;
2156da886c03S[email protected]                     connection->le_supervision_timeout = le_supervision_timeout;
2157da886c03S[email protected]                 } else {
2158da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
2159da886c03S[email protected]                 }
2160c48b2a2cSMatthias Ringwald                 connection->le_con_param_update_identifier = sig_id;
2161da886c03S[email protected]             }
2162da886c03S[email protected] 
216333c40538SMatthias Ringwald             if (!l2cap_event_packet_handler) break;
2164c48b2a2cSMatthias Ringwald 
2165c48b2a2cSMatthias Ringwald             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
2166c48b2a2cSMatthias Ringwald             event[1] = 8;
2167c48b2a2cSMatthias Ringwald             memcpy(&event[2], &command[4], 8);
2168c48b2a2cSMatthias Ringwald             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
216933c40538SMatthias Ringwald             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
2170ccf076adS[email protected]             break;
2171c48b2a2cSMatthias Ringwald 
2172a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2173a3dc965aSMatthias Ringwald 
217463f0ac45SMatthias Ringwald         case COMMAND_REJECT:
217563f0ac45SMatthias Ringwald             // Find channel for this sig_id and connection handle
217663f0ac45SMatthias Ringwald             channel = NULL;
217763f0ac45SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
217863f0ac45SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
217963f0ac45SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
218063f0ac45SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
218163f0ac45SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
218263f0ac45SMatthias Ringwald                 channel = a_channel;
218363f0ac45SMatthias Ringwald                 break;
218463f0ac45SMatthias Ringwald             }
218563f0ac45SMatthias Ringwald             if (!channel) break;
218663f0ac45SMatthias Ringwald 
218763f0ac45SMatthias Ringwald             // if received while waiting for le connection response, assume legacy device
218863f0ac45SMatthias Ringwald             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
218963f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
219063f0ac45SMatthias Ringwald                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
219144276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0x0002);
219263f0ac45SMatthias Ringwald 
219363f0ac45SMatthias Ringwald                 // discard channel
219463f0ac45SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
219563f0ac45SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
219663f0ac45SMatthias Ringwald                 break;
219763f0ac45SMatthias Ringwald             }
219863f0ac45SMatthias Ringwald             break;
219963f0ac45SMatthias Ringwald 
2200e7d0c9aaSMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_REQUEST:
2201e7d0c9aaSMatthias Ringwald 
2202e7d0c9aaSMatthias Ringwald             // get hci connection, bail if not found (must not happen)
2203e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
2204e7d0c9aaSMatthias Ringwald             if (!connection) return 0;
2205e7d0c9aaSMatthias Ringwald 
2206e7d0c9aaSMatthias Ringwald             // check if service registered
2207e7d0c9aaSMatthias Ringwald             le_psm  = little_endian_read_16(command, 4);
2208e7d0c9aaSMatthias Ringwald             service = l2cap_le_get_service(le_psm);
220911cae19eSMilanka Ringwald             source_cid = little_endian_read_16(command, 6);
2210e7d0c9aaSMatthias Ringwald 
2211e7d0c9aaSMatthias Ringwald             if (service){
2212e7d0c9aaSMatthias Ringwald                 if (source_cid < 0x40){
2213e7d0c9aaSMatthias Ringwald                     // 0x0009 Connection refused - Invalid Source CID
2214e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
2215e7d0c9aaSMatthias Ringwald                     return 1;
2216e7d0c9aaSMatthias Ringwald                 }
2217e7d0c9aaSMatthias Ringwald 
2218e7d0c9aaSMatthias Ringwald                 // go through list of channels for this ACL connection and check if we get a match
2219e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2220e7d0c9aaSMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&it)){
22211b8b8d05SMatthias Ringwald                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
22221b8b8d05SMatthias Ringwald                     if (a_channel->con_handle != handle) continue;
22231b8b8d05SMatthias Ringwald                     if (a_channel->remote_cid != source_cid) continue;
2224e7d0c9aaSMatthias Ringwald                     // 0x000a Connection refused - Source CID already allocated
2225e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
2226e7d0c9aaSMatthias Ringwald                     return 1;
2227e7d0c9aaSMatthias Ringwald                 }
2228e7d0c9aaSMatthias Ringwald 
222983fd9c76SMatthias Ringwald                 // security: check encryption
223083fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_2){
223183fd9c76SMatthias Ringwald                     if (sm_encryption_key_size(handle) == 0){
223283fd9c76SMatthias Ringwald                         // 0x0008 Connection refused - insufficient encryption
2233e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
223483fd9c76SMatthias Ringwald                         return 1;
223583fd9c76SMatthias Ringwald                     }
223683fd9c76SMatthias Ringwald                     // anything less than 16 byte key size is insufficient
223783fd9c76SMatthias Ringwald                     if (sm_encryption_key_size(handle) < 16){
223883fd9c76SMatthias Ringwald                         // 0x0007 Connection refused – insufficient encryption key size
2239e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
224083fd9c76SMatthias Ringwald                         return 1;
224183fd9c76SMatthias Ringwald                     }
224283fd9c76SMatthias Ringwald                 }
224383fd9c76SMatthias Ringwald 
224483fd9c76SMatthias Ringwald                 // security: check authencation
224583fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_3){
224683fd9c76SMatthias Ringwald                     if (!sm_authenticated(handle)){
224783fd9c76SMatthias Ringwald                         // 0x0005 Connection refused – insufficient authentication
2248e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
224983fd9c76SMatthias Ringwald                         return 1;
225083fd9c76SMatthias Ringwald                     }
225183fd9c76SMatthias Ringwald                 }
225283fd9c76SMatthias Ringwald 
225383fd9c76SMatthias Ringwald                 // security: check authorization
225483fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_4){
225583fd9c76SMatthias Ringwald                     if (sm_authorization_state(handle) != AUTHORIZATION_GRANTED){
225683fd9c76SMatthias Ringwald                         // 0x0006 Connection refused – insufficient authorization
2257e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
225883fd9c76SMatthias Ringwald                         return 1;
225983fd9c76SMatthias Ringwald                     }
226083fd9c76SMatthias Ringwald                 }
2261e7d0c9aaSMatthias Ringwald 
2262e7d0c9aaSMatthias Ringwald                 // allocate channel
22631b8b8d05SMatthias Ringwald                 channel = l2cap_create_channel_entry(service->packet_handler, connection->address,
2264e7d0c9aaSMatthias Ringwald                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
2265e7d0c9aaSMatthias Ringwald                 if (!channel){
2266e7d0c9aaSMatthias Ringwald                     // 0x0004 Connection refused – no resources available
2267e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2268e7d0c9aaSMatthias Ringwald                     return 1;
2269e7d0c9aaSMatthias Ringwald                 }
2270e7d0c9aaSMatthias Ringwald 
2271e7d0c9aaSMatthias Ringwald                 channel->con_handle = handle;
2272e7d0c9aaSMatthias Ringwald                 channel->remote_cid = source_cid;
2273e7d0c9aaSMatthias Ringwald                 channel->remote_sig_id = sig_id;
22747f107edaSMatthias Ringwald                 channel->remote_mtu = little_endian_read_16(command, 8);
22757f107edaSMatthias Ringwald                 channel->remote_mps = little_endian_read_16(command, 10);
22767f107edaSMatthias Ringwald                 channel->credits_outgoing = little_endian_read_16(command, 12);
2277e7d0c9aaSMatthias Ringwald 
2278e7d0c9aaSMatthias Ringwald                 // set initial state
2279e7d0c9aaSMatthias Ringwald                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2280c99bb618SMatthias Ringwald                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
2281e7d0c9aaSMatthias Ringwald 
2282e7d0c9aaSMatthias Ringwald                 // add to connections list
2283e7d0c9aaSMatthias Ringwald                 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2284e7d0c9aaSMatthias Ringwald 
2285e7d0c9aaSMatthias Ringwald                 // post connection request event
228644276248SMatthias Ringwald                 l2cap_emit_le_incoming_connection(channel);
2287e7d0c9aaSMatthias Ringwald 
2288e7d0c9aaSMatthias Ringwald             } else {
2289e7d0c9aaSMatthias Ringwald                 // Connection refused – LE_PSM not supported
2290e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2291e7d0c9aaSMatthias Ringwald             }
2292e7d0c9aaSMatthias Ringwald             break;
22931b8b8d05SMatthias Ringwald 
22941b8b8d05SMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
22951b8b8d05SMatthias Ringwald             // Find channel for this sig_id and connection handle
22961b8b8d05SMatthias Ringwald             channel = NULL;
22971b8b8d05SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
22981b8b8d05SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
22991b8b8d05SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
23001b8b8d05SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
23011b8b8d05SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
23021b8b8d05SMatthias Ringwald                 channel = a_channel;
23031b8b8d05SMatthias Ringwald                 break;
23041b8b8d05SMatthias Ringwald             }
23051b8b8d05SMatthias Ringwald             if (!channel) break;
23061b8b8d05SMatthias Ringwald 
23071b8b8d05SMatthias Ringwald             // cid + 0
23081b8b8d05SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
23091b8b8d05SMatthias Ringwald             if (result){
23101b8b8d05SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
23111b8b8d05SMatthias Ringwald                 // map l2cap connection response result to BTstack status enumeration
231244276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, result);
23131b8b8d05SMatthias Ringwald 
23141b8b8d05SMatthias Ringwald                 // discard channel
231563f0ac45SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
23161b8b8d05SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
23171b8b8d05SMatthias Ringwald                 break;
23181b8b8d05SMatthias Ringwald             }
23191b8b8d05SMatthias Ringwald 
23201b8b8d05SMatthias Ringwald             // success
23211b8b8d05SMatthias Ringwald             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
23221b8b8d05SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
23231b8b8d05SMatthias Ringwald             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
23241b8b8d05SMatthias Ringwald             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
23251b8b8d05SMatthias Ringwald             channel->state = L2CAP_STATE_OPEN;
232644276248SMatthias Ringwald             l2cap_emit_le_channel_opened(channel, result);
23271b8b8d05SMatthias Ringwald             break;
23281b8b8d05SMatthias Ringwald 
232985aeef60SMatthias Ringwald         case LE_FLOW_CONTROL_CREDIT:
233085aeef60SMatthias Ringwald             // find channel
233185aeef60SMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
233285aeef60SMatthias Ringwald             channel = l2cap_le_get_channel_for_local_cid(local_cid);
233363f0ac45SMatthias Ringwald             if (!channel) {
233463f0ac45SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
233563f0ac45SMatthias Ringwald                 break;
233663f0ac45SMatthias Ringwald             }
233763f0ac45SMatthias Ringwald             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
233863f0ac45SMatthias Ringwald             credits_before = channel->credits_outgoing;
233963f0ac45SMatthias Ringwald             channel->credits_outgoing += new_credits;
234063f0ac45SMatthias Ringwald             // check for credit overrun
234163f0ac45SMatthias Ringwald             if (credits_before > channel->credits_outgoing){
234263f0ac45SMatthias Ringwald                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
234363f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
234463f0ac45SMatthias Ringwald                 break;
234563f0ac45SMatthias Ringwald             }
234663f0ac45SMatthias Ringwald             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
234785aeef60SMatthias Ringwald             break;
234885aeef60SMatthias Ringwald 
2349828a7f7aSMatthias Ringwald         case DISCONNECTION_REQUEST:
2350828a7f7aSMatthias Ringwald             // find channel
2351828a7f7aSMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
2352828a7f7aSMatthias Ringwald             channel = l2cap_le_get_channel_for_local_cid(local_cid);
235363f34e00SMatthias Ringwald             if (!channel) {
235463f34e00SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
235563f34e00SMatthias Ringwald                 break;
235663f34e00SMatthias Ringwald             }
2357828a7f7aSMatthias Ringwald             channel->remote_sig_id = sig_id;
2358828a7f7aSMatthias Ringwald             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
2359828a7f7aSMatthias Ringwald             break;
2360828a7f7aSMatthias Ringwald 
2361a3dc965aSMatthias Ringwald #endif
2362a3dc965aSMatthias Ringwald 
236363f0ac45SMatthias Ringwald         case DISCONNECTION_RESPONSE:
236463f0ac45SMatthias Ringwald             break;
236563f0ac45SMatthias Ringwald 
2366c48b2a2cSMatthias Ringwald         default:
2367c48b2a2cSMatthias Ringwald             // command unknown -> reject command
2368c48b2a2cSMatthias Ringwald             return 0;
2369ccf076adS[email protected]     }
2370c48b2a2cSMatthias Ringwald     return 1;
2371c48b2a2cSMatthias Ringwald }
2372e7d0c9aaSMatthias Ringwald #endif
2373c48b2a2cSMatthias Ringwald 
2374c48b2a2cSMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size ){
23759ec2630cSMatthias Ringwald     UNUSED(packet_type);
23769ec2630cSMatthias Ringwald     UNUSED(channel);
2377c48b2a2cSMatthias Ringwald 
237809e9d05bSMatthias Ringwald     l2cap_channel_t * l2cap_channel;
2379f3963406SMatthias Ringwald     UNUSED(l2cap_channel);
238009e9d05bSMatthias Ringwald 
2381c48b2a2cSMatthias Ringwald     // Get Channel ID
2382c48b2a2cSMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
2383c48b2a2cSMatthias Ringwald     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
2384c48b2a2cSMatthias Ringwald 
2385c48b2a2cSMatthias Ringwald     switch (channel_id) {
2386c48b2a2cSMatthias Ringwald 
238709e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2388c48b2a2cSMatthias Ringwald         case L2CAP_CID_SIGNALING: {
2389c48b2a2cSMatthias Ringwald             uint16_t command_offset = 8;
2390c48b2a2cSMatthias Ringwald             while (command_offset < size) {
2391c48b2a2cSMatthias Ringwald                 // handle signaling commands
2392c48b2a2cSMatthias Ringwald                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
2393c48b2a2cSMatthias Ringwald 
2394c48b2a2cSMatthias Ringwald                 // increment command_offset
2395c48b2a2cSMatthias Ringwald                 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2396c48b2a2cSMatthias Ringwald             }
2397c48b2a2cSMatthias Ringwald             break;
2398c48b2a2cSMatthias Ringwald         }
239909e9d05bSMatthias Ringwald #endif
2400c48b2a2cSMatthias Ringwald 
2401e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
2402e7d0c9aaSMatthias Ringwald         case L2CAP_CID_SIGNALING_LE: {
2403e7d0c9aaSMatthias Ringwald             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
2404e7d0c9aaSMatthias Ringwald             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
2405c48b2a2cSMatthias Ringwald             if (!valid){
2406e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2407ccf076adS[email protected]             }
2408ccf076adS[email protected]             break;
2409e7d0c9aaSMatthias Ringwald         }
2410e7d0c9aaSMatthias Ringwald #endif
2411c48b2a2cSMatthias Ringwald 
2412c48b2a2cSMatthias Ringwald         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
2413c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback) {
2414c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2415ccf076adS[email protected]             }
2416c48b2a2cSMatthias Ringwald             break;
2417c48b2a2cSMatthias Ringwald 
2418c48b2a2cSMatthias Ringwald         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
2419c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback) {
2420c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2421c48b2a2cSMatthias Ringwald             }
2422c48b2a2cSMatthias Ringwald             break;
2423c48b2a2cSMatthias Ringwald 
2424c48b2a2cSMatthias Ringwald         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
2425c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback) {
2426c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2427c48b2a2cSMatthias Ringwald             }
2428c48b2a2cSMatthias Ringwald             break;
24291bbc0b23S[email protected] 
243009e9d05bSMatthias Ringwald         default:
243109e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
243200d93d79Smatthias.ringwald             // Find channel for this channel_id and connection handle
243364e11ca9SMatthias Ringwald             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
2434d1fd2a88SMatthias Ringwald             if (l2cap_channel) {
243527e0774aSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
243627e0774aSMatthias Ringwald                 if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
243727e0774aSMatthias Ringwald 
243827e0774aSMatthias Ringwald                     // verify FCS
243927e0774aSMatthias Ringwald                     uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
244027e0774aSMatthias Ringwald                     uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
244127e0774aSMatthias Ringwald                     log_info("Packet FCS 0x%04x, calculated FCS 0x%04x", fcs_packet, fcs_calculated);
244227e0774aSMatthias Ringwald                     if (fcs_calculated != fcs_packet){
244327e0774aSMatthias Ringwald                         log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
244427e0774aSMatthias Ringwald                         // TODO: trigger retransmission or something like that
244527e0774aSMatthias Ringwald                         break;
244627e0774aSMatthias Ringwald                     }
244727e0774aSMatthias Ringwald 
244827e0774aSMatthias Ringwald                     // switch on packet type
244927e0774aSMatthias Ringwald                     uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
245038f62777SMatthias Ringwald                     uint8_t  req_seq = (control >> 8) & 0x3f;
245127e0774aSMatthias Ringwald                     if (control & 1){
245238f62777SMatthias Ringwald                         // int poll = (control >> 7) & 0x01;
245327e0774aSMatthias Ringwald                         log_info("S-Frame not not implemented yet");
245427e0774aSMatthias Ringwald                         // S-Frame
245527e0774aSMatthias Ringwald                         break;
245627e0774aSMatthias Ringwald                     } else {
245727e0774aSMatthias Ringwald                         // I-Frame
245827e0774aSMatthias Ringwald                         // get control
245927e0774aSMatthias Ringwald                         l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
246038f62777SMatthias Ringwald                         uint8_t tx_seq = (control >> 1) & 0x3f;
246138f62777SMatthias Ringwald                         log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
246238f62777SMatthias Ringwald                         log_info("SAR: pos %u", l2cap_channel->rx_packets_state->pos);
246338f62777SMatthias Ringwald                         log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
246438f62777SMatthias Ringwald                         // check ordering
246538f62777SMatthias Ringwald                         if (l2cap_channel->expected_tx_seq == tx_seq){
246638f62777SMatthias Ringwald                             log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
246738f62777SMatthias Ringwald                             l2cap_channel->req_seq = tx_seq;
2468d84e866fSMatthias Ringwald                             l2cap_channel->send_supervisor_frame_receiver_ready = 1;
246938f62777SMatthias Ringwald                             l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
2470ed971c5aSMatthias Ringwald                             uint16_t sdu_length;
2471ed971c5aSMatthias Ringwald                             uint16_t segment_length;
2472ed971c5aSMatthias Ringwald                             uint16_t payload_offset;
247327e0774aSMatthias Ringwald                             switch (sar){
247427e0774aSMatthias Ringwald                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
2475ed971c5aSMatthias Ringwald                                     payload_offset = COMPLETE_L2CAP_HEADER+2;
2476ed971c5aSMatthias Ringwald                                     segment_length = payload_offset-2;
2477ed971c5aSMatthias Ringwald                                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER+2], segment_length);
247827e0774aSMatthias Ringwald                                     break;
247927e0774aSMatthias Ringwald                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
2480ed971c5aSMatthias Ringwald                                     // TODO: use current packet
2481ed971c5aSMatthias Ringwald                                     // TODO: check if reassembly started
2482ed971c5aSMatthias Ringwald                                     // TODO: check len against local mtu
2483ed971c5aSMatthias Ringwald                                     sdu_length = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER+2);
2484ed971c5aSMatthias Ringwald                                     payload_offset = COMPLETE_L2CAP_HEADER+4;
2485ed971c5aSMatthias Ringwald                                     segment_length = size - payload_offset-2;
2486ed971c5aSMatthias Ringwald                                     memcpy(&l2cap_channel->rx_packets_data[0], &packet[payload_offset], segment_length);
2487ed971c5aSMatthias Ringwald                                     l2cap_channel->rx_packets_state->sdu_length = sdu_length;
2488ed971c5aSMatthias Ringwald                                     l2cap_channel->rx_packets_state->pos = segment_length;
2489ed971c5aSMatthias Ringwald                                     break;
249027e0774aSMatthias Ringwald                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
2491ed971c5aSMatthias Ringwald                                     payload_offset = COMPLETE_L2CAP_HEADER+2;
2492ed971c5aSMatthias Ringwald                                     segment_length = size - payload_offset-2;
2493ed971c5aSMatthias Ringwald                                     memcpy(&l2cap_channel->rx_packets_data[l2cap_channel->rx_packets_state->pos], &packet[payload_offset], segment_length);
2494ed971c5aSMatthias Ringwald                                     l2cap_channel->rx_packets_state->pos += segment_length;
2495ed971c5aSMatthias Ringwald                                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->rx_packets_data, l2cap_channel->rx_packets_state[0].pos);
2496ed971c5aSMatthias Ringwald                                     break;
249727e0774aSMatthias Ringwald                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
2498ed971c5aSMatthias Ringwald                                     payload_offset = COMPLETE_L2CAP_HEADER+2;
2499ed971c5aSMatthias Ringwald                                     segment_length = size - payload_offset-2;
2500ed971c5aSMatthias Ringwald                                     memcpy(&l2cap_channel->rx_packets_data[l2cap_channel->rx_packets_state->pos], &packet[payload_offset], segment_length);
2501ed971c5aSMatthias Ringwald                                     l2cap_channel->rx_packets_state->pos += segment_length;
250227e0774aSMatthias Ringwald                                     break;
250327e0774aSMatthias Ringwald                                 }
250427e0774aSMatthias Ringwald                             }
250538f62777SMatthias Ringwald                         }
250627e0774aSMatthias Ringwald                     break;
250727e0774aSMatthias Ringwald                 }
250827e0774aSMatthias Ringwald #endif
25093d50b4baSMatthias Ringwald                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
251000d93d79Smatthias.ringwald             }
251109e9d05bSMatthias Ringwald #endif
2512a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
251364e11ca9SMatthias Ringwald             l2cap_channel = l2cap_le_get_channel_for_local_cid(channel_id);
251464e11ca9SMatthias Ringwald             if (l2cap_channel) {
251585aeef60SMatthias Ringwald                 // credit counting
251685aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming == 0){
251785aeef60SMatthias Ringwald                     log_error("LE Data Channel packet received but no incoming credits");
251885aeef60SMatthias Ringwald                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
251985aeef60SMatthias Ringwald                     break;
252085aeef60SMatthias Ringwald                 }
252185aeef60SMatthias Ringwald                 l2cap_channel->credits_incoming--;
252285aeef60SMatthias Ringwald 
252385aeef60SMatthias Ringwald                 // automatic credits
252485aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){
252585aeef60SMatthias Ringwald                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
252685aeef60SMatthias Ringwald                 }
252785aeef60SMatthias Ringwald 
2528cd529728SMatthias Ringwald                 // first fragment
2529cd529728SMatthias Ringwald                 uint16_t pos = 0;
2530cd529728SMatthias Ringwald                 if (!l2cap_channel->receive_sdu_len){
2531cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
2532cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_pos = 0;
2533cd529728SMatthias Ringwald                     pos  += 2;
2534cd529728SMatthias Ringwald                     size -= 2;
2535cd529728SMatthias Ringwald                 }
2536cd529728SMatthias Ringwald                 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], size-COMPLETE_L2CAP_HEADER);
2537cd529728SMatthias Ringwald                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
2538cd529728SMatthias Ringwald                 // done?
253963f0ac45SMatthias Ringwald                 log_info("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
2540cd529728SMatthias Ringwald                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
2541cd529728SMatthias Ringwald                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
2542cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = 0;
2543cd529728SMatthias Ringwald                 }
254463f0ac45SMatthias Ringwald             } else {
254563f0ac45SMatthias Ringwald                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
254664e11ca9SMatthias Ringwald             }
254764e11ca9SMatthias Ringwald #endif
25485652b5ffS[email protected]             break;
25495652b5ffS[email protected]     }
255000d93d79Smatthias.ringwald 
25511eb2563eS[email protected]     l2cap_run();
25522718e2e7Smatthias.ringwald }
255300d93d79Smatthias.ringwald 
255409e9d05bSMatthias Ringwald // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
255509e9d05bSMatthias Ringwald void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
255609e9d05bSMatthias Ringwald     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
255709e9d05bSMatthias Ringwald     if (index < 0) return;
255809e9d05bSMatthias Ringwald     fixed_channels[index].callback = the_packet_handler;
255909e9d05bSMatthias Ringwald }
256009e9d05bSMatthias Ringwald 
256109e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
256215ec09bbSmatthias.ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
256327a923d0Smatthias.ringwald void l2cap_finialize_channel_close(l2cap_channel_t * channel){
2564f62db1e3Smatthias.ringwald     channel->state = L2CAP_STATE_CLOSED;
2565f62db1e3Smatthias.ringwald     l2cap_emit_channel_closed(channel);
2566f62db1e3Smatthias.ringwald     // discard channel
25679dcb2fb2S[email protected]     l2cap_stop_rtx(channel);
2568665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2569d3a9df87Smatthias.ringwald     btstack_memory_l2cap_channel_free(channel);
2570c8e4258aSmatthias.ringwald }
25711e6aba47Smatthias.ringwald 
25728f2a52f4SMatthias Ringwald static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
2573665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
2574665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, services);
2575665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2576665d90f2SMatthias Ringwald         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
25779d9bbc01Smatthias.ringwald         if ( service->psm == psm){
25789d9bbc01Smatthias.ringwald             return service;
25799d9bbc01Smatthias.ringwald         };
25809d9bbc01Smatthias.ringwald     }
25819d9bbc01Smatthias.ringwald     return NULL;
25829d9bbc01Smatthias.ringwald }
25839d9bbc01Smatthias.ringwald 
25847192e786SMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
25857192e786SMatthias Ringwald     return l2cap_get_service_internal(&l2cap_services, psm);
25867192e786SMatthias Ringwald }
25877192e786SMatthias Ringwald 
2588e0abb8e7S[email protected] 
2589be2053a6SMatthias 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){
2590be2053a6SMatthias Ringwald 
2591be2053a6SMatthias Ringwald     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
2592e0abb8e7S[email protected] 
25934bb582b6Smatthias.ringwald     // check for alread registered psm
25949d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
2595277abc2cSmatthias.ringwald     if (service) {
2596be2053a6SMatthias Ringwald         log_error("l2cap_register_service: PSM %u already registered", psm);
2597be2053a6SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
2598277abc2cSmatthias.ringwald     }
25999d9bbc01Smatthias.ringwald 
26004bb582b6Smatthias.ringwald     // alloc structure
2601bb69aaaeS[email protected]     service = btstack_memory_l2cap_service_get();
2602277abc2cSmatthias.ringwald     if (!service) {
2603be2053a6SMatthias Ringwald         log_error("l2cap_register_service: no memory for l2cap_service_t");
2604be2053a6SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
2605277abc2cSmatthias.ringwald     }
26069d9bbc01Smatthias.ringwald 
26079d9bbc01Smatthias.ringwald     // fill in
26089d9bbc01Smatthias.ringwald     service->psm = psm;
26099d9bbc01Smatthias.ringwald     service->mtu = mtu;
261005ae8de3SMatthias Ringwald     service->packet_handler = service_packet_handler;
2611df3354fcS[email protected]     service->required_security_level = security_level;
26129d9bbc01Smatthias.ringwald 
26139d9bbc01Smatthias.ringwald     // add to services list
2614665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
2615c0e866bfSmatthias.ringwald 
2616c0e866bfSmatthias.ringwald     // enable page scan
261715a95bd5SMatthias Ringwald     gap_connectable_control(1);
26185842b6d9Smatthias.ringwald 
2619be2053a6SMatthias Ringwald     return 0;
26209d9bbc01Smatthias.ringwald }
26219d9bbc01Smatthias.ringwald 
26227e8856ebSMatthias Ringwald uint8_t l2cap_unregister_service(uint16_t psm){
2623e0abb8e7S[email protected] 
2624e0abb8e7S[email protected]     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
2625e0abb8e7S[email protected] 
26269d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
26277e8856ebSMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2628665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
2629d3a9df87Smatthias.ringwald     btstack_memory_l2cap_service_free(service);
2630c0e866bfSmatthias.ringwald 
2631c0e866bfSmatthias.ringwald     // disable page scan when no services registered
26327e8856ebSMatthias Ringwald     if (btstack_linked_list_empty(&l2cap_services)) {
263315a95bd5SMatthias Ringwald         gap_connectable_control(0);
26349d9bbc01Smatthias.ringwald     }
26357e8856ebSMatthias Ringwald     return 0;
26367e8856ebSMatthias Ringwald }
263709e9d05bSMatthias Ringwald #endif
26389d9bbc01Smatthias.ringwald 
26397192e786SMatthias Ringwald 
2640cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
264183fd9c76SMatthias Ringwald 
264257be49d6SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
264357be49d6SMatthias Ringwald     if (!channel->waiting_for_can_send_now) return;
264457be49d6SMatthias Ringwald     if (channel->send_sdu_buffer) return;
264557be49d6SMatthias Ringwald     channel->waiting_for_can_send_now = 0;
264657be49d6SMatthias Ringwald     log_info("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
264757be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
264857be49d6SMatthias Ringwald }
264957be49d6SMatthias Ringwald 
265057be49d6SMatthias Ringwald // 1BH2222
265157be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
265257be49d6SMatthias 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",
265357be49d6SMatthias Ringwald              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
265457be49d6SMatthias Ringwald     uint8_t event[19];
265557be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
265657be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
265757be49d6SMatthias Ringwald     event[2] = channel->address_type;
265857be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
265957be49d6SMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
266057be49d6SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
266157be49d6SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
266257be49d6SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
266357be49d6SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_mtu);
266457be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
266557be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
266657be49d6SMatthias Ringwald }
266757be49d6SMatthias Ringwald // 11BH22222
266857be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
266957be49d6SMatthias 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",
267057be49d6SMatthias Ringwald              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
267157be49d6SMatthias Ringwald              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
2672c99bb618SMatthias Ringwald     uint8_t event[23];
267357be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
267457be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
267557be49d6SMatthias Ringwald     event[2] = status;
267657be49d6SMatthias Ringwald     event[3] = channel->address_type;
267757be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[4]);
267857be49d6SMatthias Ringwald     little_endian_store_16(event, 10, channel->con_handle);
2679c99bb618SMatthias Ringwald     event[12] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
2680c99bb618SMatthias Ringwald     little_endian_store_16(event, 13, channel->psm);
2681c99bb618SMatthias Ringwald     little_endian_store_16(event, 15, channel->local_cid);
2682c99bb618SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_cid);
2683c99bb618SMatthias Ringwald     little_endian_store_16(event, 19, channel->local_mtu);
2684c99bb618SMatthias Ringwald     little_endian_store_16(event, 21, channel->remote_mtu);
268557be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
268657be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
268757be49d6SMatthias Ringwald }
268857be49d6SMatthias Ringwald 
268957be49d6SMatthias Ringwald static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid){
269057be49d6SMatthias Ringwald     btstack_linked_list_iterator_t it;
269157be49d6SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
269257be49d6SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
269357be49d6SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
269457be49d6SMatthias Ringwald         if ( channel->local_cid == local_cid) {
269557be49d6SMatthias Ringwald             return channel;
269657be49d6SMatthias Ringwald         }
269757be49d6SMatthias Ringwald     }
269857be49d6SMatthias Ringwald     return NULL;
269957be49d6SMatthias Ringwald }
270057be49d6SMatthias Ringwald 
270157be49d6SMatthias Ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
270257be49d6SMatthias Ringwald void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
270357be49d6SMatthias Ringwald     channel->state = L2CAP_STATE_CLOSED;
270457be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
270557be49d6SMatthias Ringwald     // discard channel
270657be49d6SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
270757be49d6SMatthias Ringwald     btstack_memory_l2cap_channel_free(channel);
270857be49d6SMatthias Ringwald }
270957be49d6SMatthias Ringwald 
2710e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
2711e7d0c9aaSMatthias Ringwald     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
27127192e786SMatthias Ringwald }
2713efedfb4cSMatthias Ringwald 
2714da144af5SMatthias Ringwald uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
27157192e786SMatthias Ringwald 
2716da144af5SMatthias Ringwald     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
27177192e786SMatthias Ringwald 
27187192e786SMatthias Ringwald     // check for alread registered psm
27197192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
27207192e786SMatthias Ringwald     if (service) {
2721da144af5SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
27227192e786SMatthias Ringwald     }
27237192e786SMatthias Ringwald 
27247192e786SMatthias Ringwald     // alloc structure
27257192e786SMatthias Ringwald     service = btstack_memory_l2cap_service_get();
27267192e786SMatthias Ringwald     if (!service) {
27277192e786SMatthias Ringwald         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
2728da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
27297192e786SMatthias Ringwald     }
27307192e786SMatthias Ringwald 
27317192e786SMatthias Ringwald     // fill in
27327192e786SMatthias Ringwald     service->psm = psm;
2733da144af5SMatthias Ringwald     service->mtu = 0;
27347192e786SMatthias Ringwald     service->packet_handler = packet_handler;
27357192e786SMatthias Ringwald     service->required_security_level = security_level;
27367192e786SMatthias Ringwald 
27377192e786SMatthias Ringwald     // add to services list
2738665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
27397192e786SMatthias Ringwald 
27407192e786SMatthias Ringwald     // done
2741da144af5SMatthias Ringwald     return 0;
27427192e786SMatthias Ringwald }
27437192e786SMatthias Ringwald 
2744da144af5SMatthias Ringwald uint8_t l2cap_le_unregister_service(uint16_t psm) {
27457192e786SMatthias Ringwald     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
27467192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
27479367f9b0SMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2748da144af5SMatthias Ringwald 
2749665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
27507192e786SMatthias Ringwald     btstack_memory_l2cap_service_free(service);
2751da144af5SMatthias Ringwald     return 0;
27527192e786SMatthias Ringwald }
2753da144af5SMatthias Ringwald 
2754da144af5SMatthias Ringwald uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
2755e7d0c9aaSMatthias Ringwald     // get channel
2756e7d0c9aaSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2757e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2758e7d0c9aaSMatthias Ringwald 
2759e7d0c9aaSMatthias Ringwald     // validate state
2760e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2761e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
2762e7d0c9aaSMatthias Ringwald     }
2763e7d0c9aaSMatthias Ringwald 
2764efedfb4cSMatthias Ringwald     // set state accept connection
276523017473SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
276623017473SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
276723017473SMatthias Ringwald     channel->local_mtu = mtu;
276885aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
276985aeef60SMatthias Ringwald     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
277085aeef60SMatthias Ringwald 
277185aeef60SMatthias Ringwald     // test
277263f0ac45SMatthias Ringwald     // channel->new_credits_incoming = 1;
2773e7d0c9aaSMatthias Ringwald 
2774e7d0c9aaSMatthias Ringwald     // go
2775e7d0c9aaSMatthias Ringwald     l2cap_run();
2776da144af5SMatthias Ringwald     return 0;
2777da144af5SMatthias Ringwald }
2778da144af5SMatthias Ringwald 
2779da144af5SMatthias Ringwald /**
2780da144af5SMatthias Ringwald  * @brief Deny incoming LE Data Channel connection due to resource constraints
2781da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2782da144af5SMatthias Ringwald  */
2783da144af5SMatthias Ringwald 
2784da144af5SMatthias Ringwald uint8_t l2cap_le_decline_connection(uint16_t local_cid){
2785e7d0c9aaSMatthias Ringwald     // get channel
2786e7d0c9aaSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2787e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2788e7d0c9aaSMatthias Ringwald 
2789e7d0c9aaSMatthias Ringwald     // validate state
2790e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2791e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
2792e7d0c9aaSMatthias Ringwald     }
2793e7d0c9aaSMatthias Ringwald 
2794efedfb4cSMatthias Ringwald     // set state decline connection
2795e7d0c9aaSMatthias Ringwald     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
2796e7d0c9aaSMatthias Ringwald     channel->reason = 0x04; // no resources available
2797e7d0c9aaSMatthias Ringwald     l2cap_run();
2798da144af5SMatthias Ringwald     return 0;
2799da144af5SMatthias Ringwald }
2800da144af5SMatthias Ringwald 
28017dafa750SMatthias Ringwald uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
2802da144af5SMatthias Ringwald     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
2803efedfb4cSMatthias Ringwald     uint16_t * out_local_cid) {
2804efedfb4cSMatthias Ringwald 
28057dafa750SMatthias Ringwald     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
2806da144af5SMatthias Ringwald 
28077dafa750SMatthias Ringwald 
28087dafa750SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
28097dafa750SMatthias Ringwald     if (!connection) {
28107dafa750SMatthias Ringwald         log_error("no hci_connection for handle 0x%04x", con_handle);
28117dafa750SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
28127dafa750SMatthias Ringwald     }
28137dafa750SMatthias Ringwald 
28147dafa750SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, connection->address, connection->address_type, psm, mtu, security_level);
2815da144af5SMatthias Ringwald     if (!channel) {
2816da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
2817da144af5SMatthias Ringwald     }
2818e7d0c9aaSMatthias Ringwald     log_info("l2cap_le_create_channel %p", channel);
2819da144af5SMatthias Ringwald 
2820da144af5SMatthias Ringwald     // store local_cid
2821da144af5SMatthias Ringwald     if (out_local_cid){
2822da144af5SMatthias Ringwald        *out_local_cid = channel->local_cid;
2823da144af5SMatthias Ringwald     }
2824da144af5SMatthias Ringwald 
28257dafa750SMatthias Ringwald     // provide buffer
28267dafa750SMatthias Ringwald     channel->con_handle = con_handle;
2827cd529728SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
28287dafa750SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
282985aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
283085aeef60SMatthias Ringwald     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
283185aeef60SMatthias Ringwald 
2832efedfb4cSMatthias Ringwald     // add to connections list
2833efedfb4cSMatthias Ringwald     btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2834efedfb4cSMatthias Ringwald 
28357dafa750SMatthias Ringwald     // go
283663f0ac45SMatthias Ringwald     l2cap_run();
2837da144af5SMatthias Ringwald     return 0;
2838da144af5SMatthias Ringwald }
2839da144af5SMatthias Ringwald 
2840da144af5SMatthias Ringwald /**
2841da144af5SMatthias Ringwald  * @brief Provide credtis for LE Data Channel
2842da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2843da144af5SMatthias Ringwald  * @param credits               Number additional credits for peer
2844da144af5SMatthias Ringwald  */
284564e11ca9SMatthias Ringwald uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
284663f0ac45SMatthias Ringwald 
284763f0ac45SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
284863f0ac45SMatthias Ringwald     if (!channel) {
284963f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
285063f0ac45SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
285163f0ac45SMatthias Ringwald     }
285263f0ac45SMatthias Ringwald 
2853efedfb4cSMatthias Ringwald     // check state
285463f0ac45SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN){
285563f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
285663f0ac45SMatthias Ringwald     }
285763f0ac45SMatthias Ringwald 
285863f0ac45SMatthias Ringwald     // assert incoming credits + credits <= 0xffff
285963f0ac45SMatthias Ringwald     uint32_t total_credits = channel->credits_incoming;
286063f0ac45SMatthias Ringwald     total_credits += channel->new_credits_incoming;
286163f0ac45SMatthias Ringwald     total_credits += credits;
286263f0ac45SMatthias Ringwald     if (total_credits > 0xffff){
286363f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
286463f0ac45SMatthias Ringwald             channel->new_credits_incoming, credits);
286563f0ac45SMatthias Ringwald     }
286663f0ac45SMatthias Ringwald 
2867efedfb4cSMatthias Ringwald     // set credits_granted
286863f0ac45SMatthias Ringwald     channel->new_credits_incoming += credits;
286963f0ac45SMatthias Ringwald 
287063f0ac45SMatthias Ringwald     // go
287163f0ac45SMatthias Ringwald     l2cap_run();
2872da144af5SMatthias Ringwald     return 0;
2873da144af5SMatthias Ringwald }
2874da144af5SMatthias Ringwald 
2875da144af5SMatthias Ringwald /**
2876da144af5SMatthias Ringwald  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
2877da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2878da144af5SMatthias Ringwald  */
287964e11ca9SMatthias Ringwald int l2cap_le_can_send_now(uint16_t local_cid){
288044276248SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
288144276248SMatthias Ringwald     if (!channel) {
288244276248SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
2883da144af5SMatthias Ringwald         return 0;
2884da144af5SMatthias Ringwald     }
2885da144af5SMatthias Ringwald 
288644276248SMatthias Ringwald     // check state
288744276248SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN) return 0;
288844276248SMatthias Ringwald 
288944276248SMatthias Ringwald     // check queue
289044276248SMatthias Ringwald     if (channel->send_sdu_buffer) return 0;
289144276248SMatthias Ringwald 
289244276248SMatthias Ringwald     // fine, go ahead
289344276248SMatthias Ringwald     return 1;
289444276248SMatthias Ringwald }
289544276248SMatthias Ringwald 
2896da144af5SMatthias Ringwald /**
2897da144af5SMatthias Ringwald  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
2898da144af5SMatthias Ringwald  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
2899da144af5SMatthias Ringwald  *       so packet handler should be ready to handle it
2900da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2901da144af5SMatthias Ringwald  */
290264e11ca9SMatthias Ringwald uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
290344276248SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
290444276248SMatthias Ringwald     if (!channel) {
290544276248SMatthias Ringwald         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
290644276248SMatthias Ringwald         return 0;
290744276248SMatthias Ringwald     }
290844276248SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
290944276248SMatthias Ringwald     l2cap_le_notify_channel_can_send(channel);
2910da144af5SMatthias Ringwald     return 0;
2911da144af5SMatthias Ringwald }
2912da144af5SMatthias Ringwald 
2913da144af5SMatthias Ringwald /**
2914da144af5SMatthias Ringwald  * @brief Send data via LE Data Channel
2915da144af5SMatthias Ringwald  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
2916da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2917da144af5SMatthias Ringwald  * @param data                  data to send
2918da144af5SMatthias Ringwald  * @param size                  data size
2919da144af5SMatthias Ringwald  */
292064e11ca9SMatthias Ringwald uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
292164e11ca9SMatthias Ringwald 
292264e11ca9SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
292364e11ca9SMatthias Ringwald     if (!channel) {
292464e11ca9SMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
2925828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
292664e11ca9SMatthias Ringwald     }
292764e11ca9SMatthias Ringwald 
292864e11ca9SMatthias Ringwald     if (len > channel->remote_mtu){
292964e11ca9SMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
293064e11ca9SMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
293164e11ca9SMatthias Ringwald     }
293264e11ca9SMatthias Ringwald 
29337f107edaSMatthias Ringwald     if (channel->send_sdu_buffer){
293464e11ca9SMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
293564e11ca9SMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
293664e11ca9SMatthias Ringwald     }
293764e11ca9SMatthias Ringwald 
29387f107edaSMatthias Ringwald     channel->send_sdu_buffer = data;
29397f107edaSMatthias Ringwald     channel->send_sdu_len    = len;
29407f107edaSMatthias Ringwald     channel->send_sdu_pos    = 0;
294164e11ca9SMatthias Ringwald 
29427f107edaSMatthias Ringwald     l2cap_run();
29437f107edaSMatthias Ringwald     return 0;
2944da144af5SMatthias Ringwald }
2945da144af5SMatthias Ringwald 
2946da144af5SMatthias Ringwald /**
2947da144af5SMatthias Ringwald  * @brief Disconnect from LE Data Channel
2948da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2949da144af5SMatthias Ringwald  */
2950828a7f7aSMatthias Ringwald uint8_t l2cap_le_disconnect(uint16_t local_cid)
2951da144af5SMatthias Ringwald {
2952828a7f7aSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2953828a7f7aSMatthias Ringwald     if (!channel) {
2954828a7f7aSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
2955828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2956828a7f7aSMatthias Ringwald     }
2957828a7f7aSMatthias Ringwald 
2958828a7f7aSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2959828a7f7aSMatthias Ringwald     l2cap_run();
2960da144af5SMatthias Ringwald     return 0;
2961da144af5SMatthias Ringwald }
2962da144af5SMatthias Ringwald 
29637f02f414SMatthias Ringwald #endif
2964