xref: /btstack/src/l2cap.c (revision 96646001605a70a7d063b9e63262a6180ca75786)
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
92675e6881SMatthias Ringwald static void l2cap_run(void);
9333c40538SMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
943d50b4baSMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size );
9530725612SMatthias Ringwald static void l2cap_notify_channel_can_send(void);
9609e9d05bSMatthias Ringwald static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel);
9709e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
9809e9d05bSMatthias Ringwald static void l2cap_finialize_channel_close(l2cap_channel_t *channel);
9909e9d05bSMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm);
10009e9d05bSMatthias Ringwald static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
10109e9d05bSMatthias Ringwald static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
10209e9d05bSMatthias Ringwald static void l2cap_emit_incoming_connection(l2cap_channel_t *channel);
10309e9d05bSMatthias Ringwald static int  l2cap_channel_ready_for_open(l2cap_channel_t *channel);
10409e9d05bSMatthias Ringwald #endif
105cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
10657be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status);
10757be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel);
10857be49d6SMatthias Ringwald static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid);
10944276248SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel);
110828a7f7aSMatthias Ringwald static void l2cap_le_finialize_channel_close(l2cap_channel_t *channel);
111e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t psm);
112e7d0c9aaSMatthias Ringwald #endif
113212b6be2SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
114*96646001SMatthias Ringwald static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel);
115212b6be2SMatthias Ringwald static int l2cap_ertm_num_unacknowledged_tx_packets(l2cap_channel_t * channel);
116212b6be2SMatthias Ringwald #endif
11733c40538SMatthias Ringwald 
1185628cf69SMatthias Ringwald typedef struct l2cap_fixed_channel {
1195628cf69SMatthias Ringwald     btstack_packet_handler_t callback;
1202125de09SMatthias Ringwald     uint8_t waiting_for_can_send_now;
1215628cf69SMatthias Ringwald } l2cap_fixed_channel_t;
1225628cf69SMatthias Ringwald 
12309e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1245628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_channels;
1255628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_services;
12609e9d05bSMatthias Ringwald static uint8_t require_security_level2_for_outgoing_sdp;
12709e9d05bSMatthias Ringwald #endif
12857be49d6SMatthias Ringwald 
12957be49d6SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1305628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_le_channels;
1315628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_le_services;
13257be49d6SMatthias Ringwald #endif
13339bda6d5Smatthias.ringwald 
13439bda6d5Smatthias.ringwald // used to cache l2cap rejects, echo, and informational requests
1352b83fb7dSmatthias.ringwald static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
1362b83fb7dSmatthias.ringwald static int signaling_responses_pending;
1372b83fb7dSmatthias.ringwald 
138fb37a842SMatthias Ringwald static btstack_packet_callback_registration_t hci_event_callback_registration;
1395628cf69SMatthias Ringwald static l2cap_fixed_channel_t fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_SIZE];
14039bda6d5Smatthias.ringwald 
141d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
142d6ed9f9cSMatthias Ringwald // only used for connection parameter update events
143d6ed9f9cSMatthias Ringwald static btstack_packet_handler_t l2cap_event_packet_handler;
144d6ed9f9cSMatthias Ringwald #endif
145d6ed9f9cSMatthias Ringwald 
14685ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
14785ddcd84SMatthias Ringwald 
14885ddcd84SMatthias Ringwald /*
14985ddcd84SMatthias Ringwald  * CRC lookup table for generator polynom D^16 + D^15 + D^2 + 1
15085ddcd84SMatthias Ringwald  */
15185ddcd84SMatthias Ringwald static const uint16_t crc16_table[256] = {
15285ddcd84SMatthias Ringwald     0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
15385ddcd84SMatthias Ringwald     0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841,
15485ddcd84SMatthias Ringwald     0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41,
15585ddcd84SMatthias Ringwald     0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040,
15685ddcd84SMatthias Ringwald     0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441,
15785ddcd84SMatthias Ringwald     0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840,
15885ddcd84SMatthias Ringwald     0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40,
15985ddcd84SMatthias Ringwald     0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041,
16085ddcd84SMatthias Ringwald     0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
16185ddcd84SMatthias Ringwald     0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840,
16285ddcd84SMatthias Ringwald     0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
16385ddcd84SMatthias Ringwald     0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041,
16485ddcd84SMatthias Ringwald     0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440,
16585ddcd84SMatthias Ringwald     0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841,
16685ddcd84SMatthias Ringwald     0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41,
16785ddcd84SMatthias Ringwald     0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040,
16885ddcd84SMatthias Ringwald };
16985ddcd84SMatthias Ringwald 
17085ddcd84SMatthias Ringwald static uint16_t crc16_calc(uint8_t * data, uint16_t len){
17185ddcd84SMatthias Ringwald     uint16_t crc = 0;   // initial value = 0
17285ddcd84SMatthias Ringwald     while (len--){
17385ddcd84SMatthias Ringwald         crc = (crc >> 8) ^ crc16_table[ (crc ^ ((uint16_t) *data++)) & 0x00FF ];
17485ddcd84SMatthias Ringwald     }
17585ddcd84SMatthias Ringwald     return crc;
17685ddcd84SMatthias Ringwald }
17785ddcd84SMatthias Ringwald 
17885ddcd84SMatthias Ringwald #endif
17985ddcd84SMatthias Ringwald 
18085ddcd84SMatthias Ringwald 
18134e7e577SMatthias Ringwald static uint16_t l2cap_fixed_channel_table_channel_id_for_index(int index){
18234e7e577SMatthias Ringwald     switch (index){
18334e7e577SMatthias Ringwald         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL:
18434e7e577SMatthias Ringwald             return L2CAP_CID_ATTRIBUTE_PROTOCOL;
18534e7e577SMatthias Ringwald         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL:
18634e7e577SMatthias Ringwald             return L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
18734e7e577SMatthias Ringwald         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL:
18834e7e577SMatthias Ringwald             return L2CAP_CID_CONNECTIONLESS_CHANNEL;
18934e7e577SMatthias Ringwald         default:
19034e7e577SMatthias Ringwald             return 0;
19134e7e577SMatthias Ringwald     }
19234e7e577SMatthias Ringwald }
1935628cf69SMatthias Ringwald static int l2cap_fixed_channel_table_index_for_channel_id(uint16_t channel_id){
1945628cf69SMatthias Ringwald     switch (channel_id){
1955628cf69SMatthias Ringwald         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
1965628cf69SMatthias Ringwald             return L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL;
1975628cf69SMatthias Ringwald         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
1985628cf69SMatthias Ringwald             return  L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL;
1995628cf69SMatthias Ringwald         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
2005628cf69SMatthias Ringwald             return  L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL;
2015628cf69SMatthias Ringwald         default:
2025628cf69SMatthias Ringwald             return -1;
2035628cf69SMatthias Ringwald         }
2045628cf69SMatthias Ringwald }
20539bda6d5Smatthias.ringwald 
20634e7e577SMatthias Ringwald static int l2cap_fixed_channel_table_index_is_le(int index){
20734e7e577SMatthias Ringwald     if (index == L2CAP_CID_CONNECTIONLESS_CHANNEL) return 0;
20834e7e577SMatthias Ringwald     return 1;
20934e7e577SMatthias Ringwald }
21034e7e577SMatthias Ringwald 
21171de195eSMatthias Ringwald void l2cap_init(void){
2122b83fb7dSmatthias.ringwald     signaling_responses_pending = 0;
213808a48abSmatthias.ringwald 
21409e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
215f5454fc6Smatthias.ringwald     l2cap_channels = NULL;
216f5454fc6Smatthias.ringwald     l2cap_services = NULL;
21709e9d05bSMatthias Ringwald     require_security_level2_for_outgoing_sdp = 0;
21809e9d05bSMatthias Ringwald #endif
219a3dc965aSMatthias Ringwald 
220a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2217192e786SMatthias Ringwald     l2cap_le_services = NULL;
2227192e786SMatthias Ringwald     l2cap_le_channels = NULL;
223a3dc965aSMatthias Ringwald #endif
224f5454fc6Smatthias.ringwald 
225d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
22633c40538SMatthias Ringwald     l2cap_event_packet_handler = NULL;
227d6ed9f9cSMatthias Ringwald #endif
2285628cf69SMatthias Ringwald     memset(fixed_channels, 0, sizeof(fixed_channels));
229f5454fc6Smatthias.ringwald 
230fcadd0caSmatthias.ringwald     //
2312718e2e7Smatthias.ringwald     // register callback with HCI
232fcadd0caSmatthias.ringwald     //
233d9a7306aSMatthias Ringwald     hci_event_callback_registration.callback = &l2cap_hci_event_handler;
234fb37a842SMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
235fb37a842SMatthias Ringwald 
236d9a7306aSMatthias Ringwald     hci_register_acl_packet_handler(&l2cap_acl_handler);
237fb37a842SMatthias Ringwald 
238be005ed6SMatthias Ringwald #ifdef ENABLE_CLASSIC
23915a95bd5SMatthias Ringwald     gap_connectable_control(0); // no services yet
240be005ed6SMatthias Ringwald #endif
241fcadd0caSmatthias.ringwald }
242fcadd0caSmatthias.ringwald 
243ffbf8201SMatthias Ringwald void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
244d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
24533c40538SMatthias Ringwald     l2cap_event_packet_handler = handler;
246d6ed9f9cSMatthias Ringwald #else
247d6ed9f9cSMatthias Ringwald     UNUSED(handler);
248d6ed9f9cSMatthias Ringwald #endif
2491e6aba47Smatthias.ringwald }
2501e6aba47Smatthias.ringwald 
25109e9d05bSMatthias Ringwald void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
2529ec2630cSMatthias Ringwald     UNUSED(con_handle);
2539ec2630cSMatthias Ringwald 
25409e9d05bSMatthias Ringwald     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
25509e9d05bSMatthias Ringwald     if (index < 0) return;
25609e9d05bSMatthias Ringwald     fixed_channels[index].waiting_for_can_send_now = 1;
25709e9d05bSMatthias Ringwald     l2cap_notify_channel_can_send();
25809e9d05bSMatthias Ringwald }
25909e9d05bSMatthias Ringwald 
26009e9d05bSMatthias Ringwald int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
2619ec2630cSMatthias Ringwald     UNUSED(channel_id);
2629ec2630cSMatthias Ringwald 
26309e9d05bSMatthias Ringwald     return hci_can_send_acl_packet_now(con_handle);
26409e9d05bSMatthias Ringwald }
26509e9d05bSMatthias Ringwald 
26609e9d05bSMatthias Ringwald uint8_t *l2cap_get_outgoing_buffer(void){
26709e9d05bSMatthias Ringwald     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
26809e9d05bSMatthias Ringwald }
26909e9d05bSMatthias Ringwald 
27009e9d05bSMatthias Ringwald int l2cap_reserve_packet_buffer(void){
27109e9d05bSMatthias Ringwald     return hci_reserve_packet_buffer();
27209e9d05bSMatthias Ringwald }
27309e9d05bSMatthias Ringwald 
27409e9d05bSMatthias Ringwald void l2cap_release_packet_buffer(void){
27509e9d05bSMatthias Ringwald     hci_release_packet_buffer();
27609e9d05bSMatthias Ringwald }
27709e9d05bSMatthias Ringwald 
278f511cefaSMatthias 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){
27909e9d05bSMatthias Ringwald     // 0 - Connection handle : PB=pb : BC=00
280f511cefaSMatthias Ringwald     little_endian_store_16(acl_buffer, 0, con_handle | (packet_boundary << 12) | (0 << 14));
28109e9d05bSMatthias Ringwald     // 2 - ACL length
28209e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 2,  len + 4);
28309e9d05bSMatthias Ringwald     // 4 - L2CAP packet length
28409e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 4,  len + 0);
28509e9d05bSMatthias Ringwald     // 6 - L2CAP channel DEST
28609e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 6,  remote_cid);
28709e9d05bSMatthias Ringwald }
28809e9d05bSMatthias Ringwald 
289f511cefaSMatthias Ringwald // assumption - only on LE connections
29009e9d05bSMatthias Ringwald int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
29109e9d05bSMatthias Ringwald 
29209e9d05bSMatthias Ringwald     if (!hci_is_packet_buffer_reserved()){
29309e9d05bSMatthias Ringwald         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
29409e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
29509e9d05bSMatthias Ringwald     }
29609e9d05bSMatthias Ringwald 
29709e9d05bSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
29809e9d05bSMatthias Ringwald         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
29909e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
30009e9d05bSMatthias Ringwald     }
30109e9d05bSMatthias Ringwald 
30209e9d05bSMatthias Ringwald     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
30309e9d05bSMatthias Ringwald 
30409e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
305f511cefaSMatthias Ringwald     l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
30609e9d05bSMatthias Ringwald     // send
30709e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len+8);
30809e9d05bSMatthias Ringwald }
30909e9d05bSMatthias Ringwald 
310f511cefaSMatthias Ringwald // assumption - only on LE connections
31109e9d05bSMatthias Ringwald int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
31209e9d05bSMatthias Ringwald 
31309e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(con_handle)){
31409e9d05bSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", cid);
31509e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
31609e9d05bSMatthias Ringwald     }
31709e9d05bSMatthias Ringwald 
31809e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
31909e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
32009e9d05bSMatthias Ringwald 
32109e9d05bSMatthias Ringwald     memcpy(&acl_buffer[8], data, len);
32209e9d05bSMatthias Ringwald 
32309e9d05bSMatthias Ringwald     return l2cap_send_prepared_connectionless(con_handle, cid, len);
32409e9d05bSMatthias Ringwald }
32509e9d05bSMatthias Ringwald 
32609e9d05bSMatthias Ringwald static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
327d9d23054SMatthias Ringwald     log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
32809e9d05bSMatthias Ringwald     uint8_t event[4];
32909e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
33009e9d05bSMatthias Ringwald     event[1] = sizeof(event) - 2;
33109e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, channel);
33209e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
33309e9d05bSMatthias Ringwald     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
33409e9d05bSMatthias Ringwald }
33509e9d05bSMatthias Ringwald 
33609e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
33717a9b554SMatthias Ringwald static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
33858de5610Smatthias.ringwald     (* (channel->packet_handler))(type, channel->local_cid, data, size);
33958de5610Smatthias.ringwald }
34058de5610Smatthias.ringwald 
34144276248SMatthias Ringwald static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
34244276248SMatthias Ringwald     uint8_t event[4];
34344276248SMatthias Ringwald     event[0] = event_code;
34444276248SMatthias Ringwald     event[1] = sizeof(event) - 2;
34544276248SMatthias Ringwald     little_endian_store_16(event, 2, channel->local_cid);
34644276248SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
34744276248SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
34844276248SMatthias Ringwald }
34909e9d05bSMatthias Ringwald #endif
35044276248SMatthias Ringwald 
35109e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
35258de5610Smatthias.ringwald void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
353c9dc710bS[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",
354fc64f94aSMatthias Ringwald              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
355c9dc710bS[email protected]              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
356bab5f4f0SMatthias Ringwald     uint8_t event[24];
35758de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
35858de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
35958de5610Smatthias.ringwald     event[2] = status;
360724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
361fc64f94aSMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
362f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
363f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
364f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
365f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 17, channel->local_mtu);
366f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 19, channel->remote_mtu);
367f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 21, channel->flush_timeout);
368bab5f4f0SMatthias Ringwald     event[23] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
36958de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
37017a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
37158de5610Smatthias.ringwald }
37258de5610Smatthias.ringwald 
37344276248SMatthias Ringwald static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
374e0abb8e7S[email protected]     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
37544276248SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
37658de5610Smatthias.ringwald }
37758de5610Smatthias.ringwald 
37844276248SMatthias Ringwald static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
379e0abb8e7S[email protected]     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
380fc64f94aSMatthias Ringwald              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
38158de5610Smatthias.ringwald     uint8_t event[16];
38258de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
38358de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
384724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[2]);
385fc64f94aSMatthias Ringwald     little_endian_store_16(event,  8, channel->con_handle);
386f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 10, channel->psm);
387f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 12, channel->local_cid);
388f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 14, channel->remote_cid);
38958de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
39017a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3910af41d30Smatthias.ringwald }
392808a48abSmatthias.ringwald 
3937f02f414SMatthias Ringwald static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
394665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
395665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
396665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
397665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
398b35f641cSmatthias.ringwald         if ( channel->local_cid == local_cid) {
399f62db1e3Smatthias.ringwald             return channel;
400f62db1e3Smatthias.ringwald         }
401f62db1e3Smatthias.ringwald     }
402f62db1e3Smatthias.ringwald     return NULL;
403f62db1e3Smatthias.ringwald }
404f62db1e3Smatthias.ringwald 
4050b9d7e78SMatthias Ringwald ///
4060b9d7e78SMatthias Ringwald 
40730725612SMatthias Ringwald void l2cap_request_can_send_now_event(uint16_t local_cid){
40830725612SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
40930725612SMatthias Ringwald     if (!channel) return;
41030725612SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
411*96646001SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
412*96646001SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
413*96646001SMatthias Ringwald         l2cap_ertm_notify_channel_can_send(channel);
414*96646001SMatthias Ringwald         return;
415*96646001SMatthias Ringwald     }
416*96646001SMatthias Ringwald #endif
41730725612SMatthias Ringwald     l2cap_notify_channel_can_send();
41830725612SMatthias Ringwald }
41930725612SMatthias Ringwald 
4200b20b13bSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
421*96646001SMatthias Ringwald static int l2cap_ertm_can_store_packet_now(l2cap_channel_t * channel){
4220b20b13bSMatthias Ringwald      // get num free tx buffers
4230b20b13bSMatthias Ringwald     int num_tx_buffers_used = channel->tx_write_index - channel->tx_read_index;
4240b20b13bSMatthias Ringwald     if (num_tx_buffers_used < 0){
4250b20b13bSMatthias Ringwald         num_tx_buffers_used += channel->num_tx_buffers;
4260b20b13bSMatthias Ringwald     }
4270b20b13bSMatthias Ringwald     int num_free_tx_buffers = channel->num_tx_buffers - num_tx_buffers_used;
4280b20b13bSMatthias Ringwald     // calculate num tx buffers for remote MTU
4290b20b13bSMatthias Ringwald     int num_tx_buffers_for_max_remote_mtu;
4300b20b13bSMatthias Ringwald     if (channel->remote_mtu <= channel->remote_mps){
4310b20b13bSMatthias Ringwald         // MTU fits into single packet
4320b20b13bSMatthias Ringwald         num_tx_buffers_for_max_remote_mtu = 1;
4330b20b13bSMatthias Ringwald     } else {
4340b20b13bSMatthias Ringwald         // include SDU Length
4350b20b13bSMatthias Ringwald         num_tx_buffers_for_max_remote_mtu = (channel->remote_mtu + 2 + (channel->remote_mps - 1)) / channel->remote_mps;
4360b20b13bSMatthias Ringwald     }
4370b20b13bSMatthias Ringwald     return num_tx_buffers_for_max_remote_mtu <= num_free_tx_buffers;
4380b20b13bSMatthias Ringwald }
4390b20b13bSMatthias Ringwald #endif
440*96646001SMatthias Ringwald 
441*96646001SMatthias Ringwald int  l2cap_can_send_packet_now(uint16_t local_cid){
442*96646001SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
443*96646001SMatthias Ringwald     if (!channel) return 0;
444*96646001SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
445*96646001SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
446*96646001SMatthias Ringwald         return l2cap_ertm_can_store_packet_now(channel);
447*96646001SMatthias Ringwald     }
448*96646001SMatthias Ringwald #endif
4490b9d7e78SMatthias Ringwald     return hci_can_send_acl_packet_now(channel->con_handle);
4507856fb31S[email protected] }
4517856fb31S[email protected] 
45283e7cdd9SMatthias Ringwald int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
45383e7cdd9SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
45483e7cdd9SMatthias Ringwald     if (!channel) return 0;
4550b20b13bSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
4560b20b13bSMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
4570b20b13bSMatthias Ringwald         return 0;
4580b20b13bSMatthias Ringwald     }
4590b20b13bSMatthias Ringwald #endif
4600b9d7e78SMatthias Ringwald     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
46183e7cdd9SMatthias Ringwald }
4620b20b13bSMatthias Ringwald 
46396cbd662Smatthias.ringwald uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
46496cbd662Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
46596cbd662Smatthias.ringwald     if (channel) {
46696cbd662Smatthias.ringwald         return channel->remote_mtu;
46796cbd662Smatthias.ringwald     }
46896cbd662Smatthias.ringwald     return 0;
46996cbd662Smatthias.ringwald }
47096cbd662Smatthias.ringwald 
471ec820d77SMatthias Ringwald static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
472665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
473665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
474665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
475665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4765932bd7cS[email protected]         if ( &channel->rtx == ts) {
4775932bd7cS[email protected]             return channel;
4785932bd7cS[email protected]         }
4795932bd7cS[email protected]     }
4805932bd7cS[email protected]     return NULL;
4815932bd7cS[email protected] }
4825932bd7cS[email protected] 
483ec820d77SMatthias Ringwald static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
4845932bd7cS[email protected]     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
48595d2c8f4SMatthias Ringwald     if (!channel) return;
4865932bd7cS[email protected] 
4875932bd7cS[email protected]     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
4885932bd7cS[email protected] 
4895932bd7cS[email protected]     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
4905932bd7cS[email protected]     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
4915932bd7cS[email protected]     // notify client
4925932bd7cS[email protected]     l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
4935932bd7cS[email protected] 
4945932bd7cS[email protected]     // discard channel
4959dcb2fb2S[email protected]     // no need to stop timer here, it is removed from list during timer callback
496665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4975932bd7cS[email protected]     btstack_memory_l2cap_channel_free(channel);
4985932bd7cS[email protected] }
4995932bd7cS[email protected] 
5005932bd7cS[email protected] static void l2cap_stop_rtx(l2cap_channel_t * channel){
5015932bd7cS[email protected]     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
502528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->rtx);
5035932bd7cS[email protected] }
5045932bd7cS[email protected] 
5055932bd7cS[email protected] static void l2cap_start_rtx(l2cap_channel_t * channel){
5065932bd7cS[email protected]     l2cap_stop_rtx(channel);
507cb0ff06bS[email protected]     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
508528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
509528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
510528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
5115932bd7cS[email protected] }
5125932bd7cS[email protected] 
5135932bd7cS[email protected] static void l2cap_start_ertx(l2cap_channel_t * channel){
5145932bd7cS[email protected]     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
5155932bd7cS[email protected]     l2cap_stop_rtx(channel);
516528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
517528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
518528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
5195932bd7cS[email protected] }
5205932bd7cS[email protected] 
52171de195eSMatthias Ringwald void l2cap_require_security_level_2_for_outgoing_sdp(void){
522ac301f95S[email protected]     require_security_level2_for_outgoing_sdp = 1;
523ac301f95S[email protected] }
524ac301f95S[email protected] 
525df3354fcS[email protected] static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
526235946f1SMatthias Ringwald     return (psm == BLUETOOTH_PROTOCOL_SDP) && (!require_security_level2_for_outgoing_sdp);
527df3354fcS[email protected] }
5285932bd7cS[email protected] 
5297f02f414SMatthias Ringwald static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
530a35252c8S[email protected]     if (!hci_can_send_acl_packet_now(handle)){
5319da54300S[email protected]         log_info("l2cap_send_signaling_packet, cannot send");
532b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
533b1d43497Smatthias.ringwald     }
534b1d43497Smatthias.ringwald 
5359da54300S[email protected]     // log_info("l2cap_send_signaling_packet type %u", cmd);
5362a373862S[email protected]     hci_reserve_packet_buffer();
537facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
53858de5610Smatthias.ringwald     va_list argptr;
53958de5610Smatthias.ringwald     va_start(argptr, identifier);
54070efece1S[email protected]     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
54158de5610Smatthias.ringwald     va_end(argptr);
5429da54300S[email protected]     // log_info("l2cap_send_signaling_packet con %u!", handle);
543826f7347S[email protected]     return hci_send_acl_packet_buffer(len);
54458de5610Smatthias.ringwald }
54558de5610Smatthias.ringwald 
546f511cefaSMatthias Ringwald // assumption - only on Classic connections
547b1d43497Smatthias.ringwald int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
548b1d43497Smatthias.ringwald 
549c8b9416aS[email protected]     if (!hci_is_packet_buffer_reserved()){
550c8b9416aS[email protected]         log_error("l2cap_send_prepared called without reserving packet first");
551c8b9416aS[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
552c8b9416aS[email protected]     }
553c8b9416aS[email protected] 
55458de5610Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
555b1d43497Smatthias.ringwald     if (!channel) {
5569da54300S[email protected]         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
557b1d43497Smatthias.ringwald         return -1;   // TODO: define error
5586218e6f1Smatthias.ringwald     }
5596218e6f1Smatthias.ringwald 
560fc64f94aSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
5619da54300S[email protected]         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
562a35252c8S[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
563a35252c8S[email protected]     }
564a35252c8S[email protected] 
565fc64f94aSMatthias Ringwald     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
566b1d43497Smatthias.ringwald 
56785ddcd84SMatthias Ringwald     int fcs_size = 0;
56885ddcd84SMatthias Ringwald 
56985ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
57085ddcd84SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
57185ddcd84SMatthias Ringwald         fcs_size = 2;
57285ddcd84SMatthias Ringwald     }
57385ddcd84SMatthias Ringwald #endif
57485ddcd84SMatthias Ringwald 
575f511cefaSMatthias Ringwald     // set non-flushable packet boundary flag if supported on Controller
576facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
577f511cefaSMatthias Ringwald     uint8_t packet_boundary_flag = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
57885ddcd84SMatthias Ringwald     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
57985ddcd84SMatthias Ringwald 
58085ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
58185ddcd84SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
58285ddcd84SMatthias Ringwald         // calculate FCS over l2cap data
58385ddcd84SMatthias Ringwald         uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
58485ddcd84SMatthias Ringwald         log_info("I-Frame: fcs 0x%04x", fcs);
58585ddcd84SMatthias Ringwald         little_endian_store_16(acl_buffer, 8 + len, fcs);
58658de5610Smatthias.ringwald     }
58785ddcd84SMatthias Ringwald #endif
58885ddcd84SMatthias Ringwald 
58985ddcd84SMatthias Ringwald     // send
59085ddcd84SMatthias Ringwald     return hci_send_acl_packet_buffer(len+8+fcs_size);
59185ddcd84SMatthias Ringwald }
59285ddcd84SMatthias Ringwald 
59385ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
59485ddcd84SMatthias 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){
59585ddcd84SMatthias Ringwald     return (((uint16_t) sar) << 14) | (req_seq << 8) | (final << 7) | (tx_seq << 1) | 0;
59685ddcd84SMatthias Ringwald }
59785ddcd84SMatthias 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){
59838f62777SMatthias Ringwald     return (req_seq << 8) | (final << 7) | (poll << 4) | (((int) supervisory_function) << 2) | 1;
59985ddcd84SMatthias Ringwald }
60085ddcd84SMatthias Ringwald static int l2cap_next_ertm_seq_nr(int seq_nr){
60185ddcd84SMatthias Ringwald     return (seq_nr + 1) & 0x3f;
60285ddcd84SMatthias Ringwald }
603f0fb4cd7SMatthias Ringwald static void l2cap_ertm_next_tx_write_index(l2cap_channel_t * channel){
604f0fb4cd7SMatthias Ringwald     channel->tx_write_index++;
605f0fb4cd7SMatthias Ringwald     if (channel->tx_write_index < channel->num_tx_buffers) return;
606f0fb4cd7SMatthias Ringwald     channel->tx_write_index = 0;
607f0fb4cd7SMatthias Ringwald }
60820fa474dSMatthias Ringwald static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts){
60920fa474dSMatthias Ringwald     log_info("l2cap_ertm_monitor_timeout_callback");
610db55d2e9SMatthias Ringwald     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
611db55d2e9SMatthias Ringwald 
612db55d2e9SMatthias Ringwald     // TODO: we assume that it's the oldest packet
613db55d2e9SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
614db55d2e9SMatthias Ringwald     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
615db55d2e9SMatthias Ringwald 
616db55d2e9SMatthias Ringwald     // check retry count
617db55d2e9SMatthias Ringwald     if (tx_state->retry_count < l2cap_channel->remote_max_transmit){
618db55d2e9SMatthias Ringwald         // increment retry count
619db55d2e9SMatthias Ringwald         tx_state->retry_count++;
620db55d2e9SMatthias Ringwald 
621db55d2e9SMatthias Ringwald         // start monitor timer
622db55d2e9SMatthias Ringwald         btstack_run_loop_set_timer_handler(&tx_state->monitor_timer, &l2cap_ertm_monitor_timeout_callback);
623db55d2e9SMatthias Ringwald         btstack_run_loop_set_timer_context(&tx_state->monitor_timer, l2cap_channel);
624db55d2e9SMatthias Ringwald         btstack_run_loop_set_timer(&tx_state->monitor_timer, l2cap_channel->local_monitor_timeout_ms);
625db55d2e9SMatthias Ringwald         btstack_run_loop_add_timer(&tx_state->monitor_timer);
626db55d2e9SMatthias Ringwald 
627db55d2e9SMatthias Ringwald         // send RR/P=1
628db55d2e9SMatthias Ringwald         l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
629db55d2e9SMatthias Ringwald     } else {
630db55d2e9SMatthias Ringwald         log_info("Monitor timer expired & retry count >= max transmit -> disconnect");
631db55d2e9SMatthias Ringwald         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
632db55d2e9SMatthias Ringwald     }
633db55d2e9SMatthias Ringwald     l2cap_run();
634db55d2e9SMatthias Ringwald }
635db55d2e9SMatthias Ringwald static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts){
636db55d2e9SMatthias Ringwald     log_info("l2cap_ertm_retransmission_timeout_callback");
637db55d2e9SMatthias Ringwald     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
638db55d2e9SMatthias Ringwald 
639db55d2e9SMatthias Ringwald     // TODO: we assume that it's the oldest packet
640db55d2e9SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
641db55d2e9SMatthias Ringwald     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
642db55d2e9SMatthias Ringwald 
643db55d2e9SMatthias Ringwald     // set retry count = 1
644db55d2e9SMatthias Ringwald     tx_state->retry_count = 1;
645db55d2e9SMatthias Ringwald 
646db55d2e9SMatthias Ringwald     // start monitor timer
647db55d2e9SMatthias Ringwald     btstack_run_loop_set_timer_handler(&tx_state->monitor_timer, &l2cap_ertm_monitor_timeout_callback);
648db55d2e9SMatthias Ringwald     btstack_run_loop_set_timer_context(&tx_state->monitor_timer, l2cap_channel);
649db55d2e9SMatthias Ringwald     btstack_run_loop_set_timer(&tx_state->monitor_timer, l2cap_channel->local_monitor_timeout_ms);
650db55d2e9SMatthias Ringwald     btstack_run_loop_add_timer(&tx_state->monitor_timer);
651db55d2e9SMatthias Ringwald 
652db55d2e9SMatthias Ringwald     // send RR/P=1
653db55d2e9SMatthias Ringwald     l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
65420fa474dSMatthias Ringwald     l2cap_run();
65520fa474dSMatthias Ringwald }
6567b7901d8SMatthias Ringwald static int l2cap_ertm_send_information_frame(l2cap_channel_t * channel, int index, int final){
657f0fb4cd7SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
658f0fb4cd7SMatthias Ringwald     hci_reserve_packet_buffer();
659f0fb4cd7SMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
66082bb0e22SMatthias Ringwald     uint16_t control = l2cap_encanced_control_field_for_information_frame(tx_state->tx_seq, final, channel->req_seq, tx_state->sar);
661f0fb4cd7SMatthias Ringwald     log_info("I-Frame: control 0x%04x", control);
662f0fb4cd7SMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
663f0fb4cd7SMatthias Ringwald     memcpy(&acl_buffer[8+2], &channel->tx_packets_data[index * channel->local_mtu], tx_state->len);
664f0fb4cd7SMatthias Ringwald     // send
665f0fb4cd7SMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2 + tx_state->len);
666f0fb4cd7SMatthias Ringwald }
66782bb0e22SMatthias Ringwald 
6687bebc11cSMatthias Ringwald static void l2cap_ertm_store_fragment(l2cap_channel_t * channel, l2cap_segmentation_and_reassembly_t sar, uint16_t sdu_length, uint8_t * data, uint16_t len){
6697bebc11cSMatthias Ringwald     // get next index for storing packets
670f0fb4cd7SMatthias Ringwald     int index = channel->tx_write_index;
67182bb0e22SMatthias Ringwald 
672f0fb4cd7SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
673f0fb4cd7SMatthias Ringwald     tx_state->tx_seq = channel->next_tx_seq;
674f0fb4cd7SMatthias Ringwald     tx_state->len = len;
6757bebc11cSMatthias Ringwald     tx_state->sar = sar;
676db55d2e9SMatthias Ringwald     tx_state->retry_count = 0;
67782bb0e22SMatthias Ringwald 
67882bb0e22SMatthias Ringwald     uint8_t * tx_packet = &channel->tx_packets_data[index * channel->local_mtu];
6797bebc11cSMatthias Ringwald     int pos = 0;
6807bebc11cSMatthias Ringwald     if (sar == L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU){
6817bebc11cSMatthias Ringwald         little_endian_store_16(tx_packet, 0, sdu_length);
6827bebc11cSMatthias Ringwald         pos += 2;
6837bebc11cSMatthias Ringwald     }
6847bebc11cSMatthias Ringwald     memcpy(&tx_packet[pos], data, len);
68582bb0e22SMatthias Ringwald 
686f0fb4cd7SMatthias Ringwald     // update
687f0fb4cd7SMatthias Ringwald     channel->next_tx_seq = l2cap_next_ertm_seq_nr(channel->next_tx_seq);
688f0fb4cd7SMatthias Ringwald     l2cap_ertm_next_tx_write_index(channel);
68982bb0e22SMatthias Ringwald 
69062041d70SMatthias Ringwald     // set retransmission timer
69162041d70SMatthias Ringwald     btstack_run_loop_set_timer_handler(&tx_state->retransmission_timer, &l2cap_ertm_retransmission_timeout_callback);
69262041d70SMatthias Ringwald     btstack_run_loop_set_timer_context(&tx_state->retransmission_timer, channel);
69362041d70SMatthias Ringwald     btstack_run_loop_set_timer(&tx_state->retransmission_timer, channel->local_retransmission_timeout_ms);
69462041d70SMatthias Ringwald     btstack_run_loop_add_timer(&tx_state->retransmission_timer);
6957bebc11cSMatthias Ringwald }
6967bebc11cSMatthias Ringwald 
6977bebc11cSMatthias Ringwald static int l2cap_ertm_send(l2cap_channel_t * channel, uint8_t * data, uint16_t len){
6987bebc11cSMatthias Ringwald     if (len > channel->remote_mtu){
6997bebc11cSMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
7007bebc11cSMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
7017bebc11cSMatthias Ringwald     }
7027bebc11cSMatthias Ringwald 
7037bebc11cSMatthias Ringwald     // check if it needs to get fragmented
7047bebc11cSMatthias Ringwald     if (len > channel->remote_mps){
7057bebc11cSMatthias Ringwald         // fragmentation needed.
7067bebc11cSMatthias Ringwald         l2cap_segmentation_and_reassembly_t sar =  L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU;
7077bebc11cSMatthias Ringwald         int chunk_len;
7087bebc11cSMatthias Ringwald         while (len){
7097bebc11cSMatthias Ringwald             switch (sar){
7107bebc11cSMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
7117bebc11cSMatthias Ringwald                     chunk_len = channel->remote_mps - 2;    // sdu_length
7127bebc11cSMatthias Ringwald                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
7137bebc11cSMatthias Ringwald                     len -= chunk_len;
7147bebc11cSMatthias Ringwald                     sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU;
7157bebc11cSMatthias Ringwald                     break;
7167bebc11cSMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
7177bebc11cSMatthias Ringwald                     chunk_len = channel->remote_mps;
7187bebc11cSMatthias Ringwald                     if (chunk_len >= len){
7197bebc11cSMatthias Ringwald                         sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU;
7207bebc11cSMatthias Ringwald                         chunk_len = len;
7217bebc11cSMatthias Ringwald                     }
7227bebc11cSMatthias Ringwald                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
7237bebc11cSMatthias Ringwald                     len -= chunk_len;
7247bebc11cSMatthias Ringwald                     break;
7257bebc11cSMatthias Ringwald                 default:
7267bebc11cSMatthias Ringwald                     break;
7277bebc11cSMatthias Ringwald             }
7287bebc11cSMatthias Ringwald         }
7297bebc11cSMatthias Ringwald 
7307bebc11cSMatthias Ringwald     } else {
7317bebc11cSMatthias Ringwald         l2cap_ertm_store_fragment(channel, L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU, 0, data, len);
7327bebc11cSMatthias Ringwald     }
73382bb0e22SMatthias Ringwald 
734675e6881SMatthias Ringwald     // try to send
735675e6881SMatthias Ringwald     l2cap_run();
736f0fb4cd7SMatthias Ringwald     return 0;
737f0fb4cd7SMatthias Ringwald }
73885ddcd84SMatthias Ringwald #endif
73958de5610Smatthias.ringwald 
740f511cefaSMatthias Ringwald // assumption - only on Classic connections
741ce8f182eSMatthias Ringwald int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
742a35252c8S[email protected]     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
743a35252c8S[email protected]     if (!channel) {
744ce8f182eSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
745a35252c8S[email protected]         return -1;   // TODO: define error
746a35252c8S[email protected]     }
747a35252c8S[email protected] 
748f0fb4cd7SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
749f0fb4cd7SMatthias Ringwald     // send in ERTM
750f0fb4cd7SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
751f0fb4cd7SMatthias Ringwald         return l2cap_ertm_send(channel, data, len);
752f0fb4cd7SMatthias Ringwald     }
753f0fb4cd7SMatthias Ringwald #endif
754f0fb4cd7SMatthias Ringwald 
755f0efaa57S[email protected]     if (len > channel->remote_mtu){
756ce8f182eSMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
757f0efaa57S[email protected]         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
758f0efaa57S[email protected]     }
759f0efaa57S[email protected] 
760fc64f94aSMatthias Ringwald     if (!hci_can_send_acl_packet_now(channel->con_handle)){
761ce8f182eSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
762b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
763b1d43497Smatthias.ringwald     }
764b1d43497Smatthias.ringwald 
7652a373862S[email protected]     hci_reserve_packet_buffer();
766facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
767f0fb4cd7SMatthias Ringwald     memcpy(&acl_buffer[8], data, len);
768f0fb4cd7SMatthias Ringwald     return l2cap_send_prepared(local_cid, len);
769b1d43497Smatthias.ringwald }
770b1d43497Smatthias.ringwald 
771fc64f94aSMatthias Ringwald int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
772fc64f94aSMatthias Ringwald     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
7730e37e417S[email protected] }
7740e37e417S[email protected] 
77528ca2b46S[email protected] static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
77628ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
77728ca2b46S[email protected] }
77828ca2b46S[email protected] 
77928ca2b46S[email protected] static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
78028ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
78128ca2b46S[email protected] }
78209e9d05bSMatthias Ringwald #endif
78328ca2b46S[email protected] 
78428ca2b46S[email protected] 
78509e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
78609e9d05bSMatthias Ringwald static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
78709e9d05bSMatthias Ringwald 
78809e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(handle)){
78909e9d05bSMatthias Ringwald         log_info("l2cap_send_le_signaling_packet, cannot send");
79009e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
79109e9d05bSMatthias Ringwald     }
79209e9d05bSMatthias Ringwald 
79309e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
79409e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
79509e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
79609e9d05bSMatthias Ringwald     va_list argptr;
79709e9d05bSMatthias Ringwald     va_start(argptr, identifier);
79809e9d05bSMatthias Ringwald     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
79909e9d05bSMatthias Ringwald     va_end(argptr);
80009e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
80109e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len);
80209e9d05bSMatthias Ringwald }
80309e9d05bSMatthias Ringwald #endif
80409e9d05bSMatthias Ringwald 
80509e9d05bSMatthias Ringwald uint16_t l2cap_max_mtu(void){
80609e9d05bSMatthias Ringwald     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
80709e9d05bSMatthias Ringwald }
80809e9d05bSMatthias Ringwald 
80909e9d05bSMatthias Ringwald uint16_t l2cap_max_le_mtu(void){
81009e9d05bSMatthias Ringwald     return l2cap_max_mtu();
81109e9d05bSMatthias Ringwald }
812b1d43497Smatthias.ringwald 
8136dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
814450ad7ecSMatthias Ringwald static uint16_t l2cap_setup_options_ertm(l2cap_channel_t * channel, uint8_t * config_options){
8156dca2a0cSMatthias Ringwald     config_options[0] = 0x04;   // RETRANSMISSION AND FLOW CONTROL OPTION
8166dca2a0cSMatthias Ringwald     config_options[1] = 9;      // length
8176dca2a0cSMatthias Ringwald     config_options[2] = (uint8_t) channel->mode;
8187b181629SMatthias Ringwald     config_options[3] = channel->num_rx_buffers;    // == TxWindows size
819bbc0a9e7SMatthias Ringwald     config_options[4] = channel->local_max_transmit;
820bbc0a9e7SMatthias Ringwald     little_endian_store_16( config_options, 5, channel->local_retransmission_timeout_ms);
821bbc0a9e7SMatthias Ringwald     little_endian_store_16( config_options, 7, channel->local_monitor_timeout_ms);
822843bae5dSMatthias Ringwald     little_endian_store_16( config_options, 9, channel->local_mps);
823450ad7ecSMatthias Ringwald     return 11;
8246dca2a0cSMatthias Ringwald }
82538f62777SMatthias Ringwald static int l2cap_ertm_send_supervisor_frame(l2cap_channel_t * channel, uint16_t control){
82638f62777SMatthias Ringwald     hci_reserve_packet_buffer();
82738f62777SMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
82838f62777SMatthias Ringwald     log_info("S-Frame: control 0x%04x", control);
82938f62777SMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
83038f62777SMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2);
83138f62777SMatthias Ringwald }
832212b6be2SMatthias Ringwald static int l2cap_ertm_num_unacknowledged_tx_packets(l2cap_channel_t * channel){
833212b6be2SMatthias Ringwald     int unacknowledged_packets = channel->tx_send_index - channel->tx_read_index;
834212b6be2SMatthias Ringwald     if (unacknowledged_packets < 0){
835212b6be2SMatthias Ringwald         unacknowledged_packets += channel->num_tx_buffers;
836212b6be2SMatthias Ringwald     }
837212b6be2SMatthias Ringwald     return unacknowledged_packets;
838212b6be2SMatthias Ringwald }
839450ad7ecSMatthias Ringwald #endif
840450ad7ecSMatthias Ringwald 
841d2afdd38SMatthias Ringwald #ifdef ENABLE_CLASSIC
842d2afdd38SMatthias Ringwald 
843d2afdd38SMatthias Ringwald static uint16_t l2cap_setup_options_mtu(l2cap_channel_t * channel, uint8_t * config_options){
844d2afdd38SMatthias Ringwald     config_options[0] = 1; // MTU
845d2afdd38SMatthias Ringwald     config_options[1] = 2; // len param
846d2afdd38SMatthias Ringwald     little_endian_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
847d2afdd38SMatthias Ringwald     return 4;
848d2afdd38SMatthias Ringwald }
849d2afdd38SMatthias Ringwald 
850450ad7ecSMatthias Ringwald static uint16_t l2cap_setup_options(l2cap_channel_t * channel, uint8_t * config_options){
851450ad7ecSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
852450ad7ecSMatthias Ringwald     // use ERTM options if supported
853450ad7ecSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
854450ad7ecSMatthias Ringwald     if ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE) && (connection->l2cap_state.extended_feature_mask & 0x08)){
855450ad7ecSMatthias Ringwald         return l2cap_setup_options_ertm(channel, config_options);
856450ad7ecSMatthias Ringwald 
857450ad7ecSMatthias Ringwald     }
858450ad7ecSMatthias Ringwald #endif
859450ad7ecSMatthias Ringwald     return l2cap_setup_options_mtu(channel, config_options);
8606dca2a0cSMatthias Ringwald }
8616dca2a0cSMatthias Ringwald 
8621b9cb13dSMatthias Ringwald static uint32_t l2cap_extended_features_mask(void){
8631b9cb13dSMatthias Ringwald     // extended features request supported, features: fixed channels, unicast connectionless data reception
8641b9cb13dSMatthias Ringwald     uint32_t features = 0x280;
8651b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
8661b9cb13dSMatthias Ringwald     features |= 0x0008;
8671b9cb13dSMatthias Ringwald #endif
8681b9cb13dSMatthias Ringwald     return features;
8691b9cb13dSMatthias Ringwald }
870d2afdd38SMatthias Ringwald #endif
8711b9cb13dSMatthias Ringwald 
8728158c421Smatthias.ringwald // MARK: L2CAP_RUN
8732cd0be45Smatthias.ringwald // process outstanding signaling tasks
8747f02f414SMatthias Ringwald static void l2cap_run(void){
8752b83fb7dSmatthias.ringwald 
87622c29ab4SMatthias Ringwald     // log_info("l2cap_run: entered");
87722c29ab4SMatthias Ringwald 
8782b83fb7dSmatthias.ringwald     // check pending signaling responses
8792b83fb7dSmatthias.ringwald     while (signaling_responses_pending){
8802b83fb7dSmatthias.ringwald 
8812b83fb7dSmatthias.ringwald         hci_con_handle_t handle = signaling_responses[0].handle;
882a35252c8S[email protected] 
883a35252c8S[email protected]         if (!hci_can_send_acl_packet_now(handle)) break;
884a35252c8S[email protected] 
8852b83fb7dSmatthias.ringwald         uint8_t  sig_id        = signaling_responses[0].sig_id;
886e74c5f58SMatthias Ringwald         uint8_t  response_code = signaling_responses[0].code;
8872b360848Smatthias.ringwald         uint16_t infoType      = signaling_responses[0].data;  // INFORMATION_REQUEST
88863a7246aSmatthias.ringwald         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
889b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
890b3264428SMatthias Ringwald         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
891b3264428SMatthias Ringwald #endif
892f3963406SMatthias Ringwald         UNUSED(infoType);
89309e9d05bSMatthias Ringwald 
894f53da564S[email protected]         // remove first item before sending (to avoid sending response mutliple times)
895f53da564S[email protected]         signaling_responses_pending--;
896f53da564S[email protected]         int i;
897f53da564S[email protected]         for (i=0; i < signaling_responses_pending; i++){
898f53da564S[email protected]             memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t));
899f53da564S[email protected]         }
900f53da564S[email protected] 
901f53da564S[email protected]         switch (response_code){
90209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
9032b360848Smatthias.ringwald             case CONNECTION_REQUEST:
904e74c5f58SMatthias Ringwald                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
9052bd8b7e7S[email protected]                 // also disconnect if result is 0x0003 - security blocked
9064d816277S[email protected]                 if (result == 0x0003){
9072bd8b7e7S[email protected]                     hci_disconnect_security_block(handle);
9084d816277S[email protected]                 }
9092b360848Smatthias.ringwald                 break;
9102b83fb7dSmatthias.ringwald             case ECHO_REQUEST:
9112b83fb7dSmatthias.ringwald                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
9122b83fb7dSmatthias.ringwald                 break;
9132b83fb7dSmatthias.ringwald             case INFORMATION_REQUEST:
9143b0484b3S[email protected]                 switch (infoType){
9153b0484b3S[email protected]                     case 1: { // Connectionless MTU
9163b0484b3S[email protected]                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
9173b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(connectionless_mtu), &connectionless_mtu);
9183b0484b3S[email protected]                         }
919202c8a4cSMatthias Ringwald                         break;
9203b0484b3S[email protected]                     case 2: {  // Extended Features Supported
9211b9cb13dSMatthias Ringwald                             uint32_t features = l2cap_extended_features_mask();
9223b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(features), &features);
9233b0484b3S[email protected]                         }
924202c8a4cSMatthias Ringwald                         break;
9253b0484b3S[email protected]                     case 3: { // Fixed Channels Supported
9263b0484b3S[email protected]                             uint8_t map[8];
9273b0484b3S[email protected]                             memset(map, 0, 8);
928288636a2SMatthias Ringwald                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
9293b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(map), &map);
9303b0484b3S[email protected]                         }
931202c8a4cSMatthias Ringwald                         break;
9323b0484b3S[email protected]                     default:
9332b83fb7dSmatthias.ringwald                         // all other types are not supported
9342b83fb7dSmatthias.ringwald                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
9353b0484b3S[email protected]                         break;
9362b83fb7dSmatthias.ringwald                 }
9372b83fb7dSmatthias.ringwald                 break;
93863a7246aSmatthias.ringwald             case COMMAND_REJECT:
9395ca8d57bS[email protected]                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
94063f0ac45SMatthias Ringwald                 break;
94109e9d05bSMatthias Ringwald #endif
942a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
94363f0ac45SMatthias Ringwald             case LE_CREDIT_BASED_CONNECTION_REQUEST:
94463f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
94563f0ac45SMatthias Ringwald                 break;
94670efece1S[email protected]             case COMMAND_REJECT_LE:
94770efece1S[email protected]                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
94863a7246aSmatthias.ringwald                 break;
94970efece1S[email protected] #endif
9502b83fb7dSmatthias.ringwald             default:
9512b83fb7dSmatthias.ringwald                 // should not happen
9522b83fb7dSmatthias.ringwald                 break;
9532b83fb7dSmatthias.ringwald         }
9542b83fb7dSmatthias.ringwald     }
9552b83fb7dSmatthias.ringwald 
956665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
957f3963406SMatthias Ringwald     UNUSED(it);
95809e9d05bSMatthias Ringwald 
9591b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
9601b9cb13dSMatthias Ringwald     // send l2cap information request if neccessary
9611b9cb13dSMatthias Ringwald     hci_connections_get_iterator(&it);
9621b9cb13dSMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
9631b9cb13dSMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
9641b9cb13dSMatthias Ringwald         if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST){
9651b9cb13dSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
9661b9cb13dSMatthias Ringwald             // send information request for extended features
9671b9cb13dSMatthias Ringwald             uint8_t sig_id = l2cap_next_sig_id();
9681b9cb13dSMatthias Ringwald             uint8_t info_type = 2;
9691b9cb13dSMatthias Ringwald             l2cap_send_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
9701b9cb13dSMatthias Ringwald             return;
9711b9cb13dSMatthias Ringwald         }
9721b9cb13dSMatthias Ringwald     }
9731b9cb13dSMatthias Ringwald #endif
9741b9cb13dSMatthias Ringwald 
97509e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
97643ec931dSMatthias Ringwald     uint8_t  config_options[10];
977665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
978665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
979baf94f06S[email protected] 
980665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
98122c29ab4SMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
9822cd0be45Smatthias.ringwald         switch (channel->state){
9832cd0be45Smatthias.ringwald 
984df3354fcS[email protected]             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
985ad671560S[email protected]             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
986fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
987a00031e2S[email protected]                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
988ad671560S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
989fc64f94aSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
990ad671560S[email protected]                 }
991ad671560S[email protected]                 break;
992ad671560S[email protected] 
99302b22dc4Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
994baf94f06S[email protected]                 if (!hci_can_send_command_packet_now()) break;
99564472d52Smatthias.ringwald                 // send connection request - set state first
99664472d52Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
99702b22dc4Smatthias.ringwald                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
9988f8108aaSmatthias.ringwald                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
99902b22dc4Smatthias.ringwald                 break;
100002b22dc4Smatthias.ringwald 
1001e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
1002fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
100322c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1004fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
1005e7ff783cSmatthias.ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
10069dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
1007665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1008d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
1009e7ff783cSmatthias.ringwald                 break;
1010e7ff783cSmatthias.ringwald 
1011552d92a1Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
1012fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1013fa8473a4Smatthias.ringwald                 channel->state = L2CAP_STATE_CONFIG;
101428ca2b46S[email protected]                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1015fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
1016552d92a1Smatthias.ringwald                 break;
1017552d92a1Smatthias.ringwald 
10186fdcc387Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
1019fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
10206fdcc387Smatthias.ringwald                 // success, start l2cap handshake
1021b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
10226fdcc387Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
1023fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
10245932bd7cS[email protected]                 l2cap_start_rtx(channel);
10256fdcc387Smatthias.ringwald                 break;
10266fdcc387Smatthias.ringwald 
1027fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
1028fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
102973cf2b3dSmatthias.ringwald                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
103063a7246aSmatthias.ringwald                     uint16_t flags = 0;
103128ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
103263a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
103363a7246aSmatthias.ringwald                         flags = 1;
103463a7246aSmatthias.ringwald                     } else {
103528ca2b46S[email protected]                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
103663a7246aSmatthias.ringwald                     }
103763a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
1038ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1039fc64f94aSMatthias 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);
1040ac8f1300SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1041ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
1042ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1043ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
10446dca2a0cSMatthias Ringwald                         uint16_t options_size = l2cap_setup_options(channel, config_options);
1045ac8f1300SMatthias 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);
1046ac8f1300SMatthias Ringwald #endif
1047ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
104863a7246aSmatthias.ringwald                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1049ac8f1300SMatthias Ringwald                         uint16_t options_size = l2cap_setup_options(channel, config_options);
1050ac8f1300SMatthias 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);
105163a7246aSmatthias.ringwald                     } else {
1052ac8f1300SMatthias Ringwald                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
105363a7246aSmatthias.ringwald                     }
105463a7246aSmatthias.ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1055fa8473a4Smatthias.ringwald                 }
105673cf2b3dSmatthias.ringwald                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
105728ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
105828ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
1059b1988dceSmatthias.ringwald                     channel->local_sig_id = l2cap_next_sig_id();
10606dca2a0cSMatthias Ringwald                     uint16_t options_size = l2cap_setup_options(channel, config_options);
10616dca2a0cSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options);
10625932bd7cS[email protected]                     l2cap_start_rtx(channel);
1063fa8473a4Smatthias.ringwald                 }
1064fa8473a4Smatthias.ringwald                 if (l2cap_channel_ready_for_open(channel)){
1065552d92a1Smatthias.ringwald                     channel->state = L2CAP_STATE_OPEN;
1066552d92a1Smatthias.ringwald                     l2cap_emit_channel_opened(channel, 0);  // success
1067fa8473a4Smatthias.ringwald                 }
1068552d92a1Smatthias.ringwald                 break;
1069552d92a1Smatthias.ringwald 
1070e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1071fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
107222c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1073fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
10745932bd7cS[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 :)
1075756102d3Smatthias.ringwald                 l2cap_finialize_channel_close(channel);  // -- remove from list
1076e7ff783cSmatthias.ringwald                 break;
1077e7ff783cSmatthias.ringwald 
1078e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1079fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1080b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
10812cd0be45Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1082fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
10832cd0be45Smatthias.ringwald                 break;
10842cd0be45Smatthias.ringwald             default:
10852cd0be45Smatthias.ringwald                 break;
10862cd0be45Smatthias.ringwald         }
108738f62777SMatthias Ringwald 
108838f62777SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
108938f62777SMatthias Ringwald         // send s-frame to acknowledge received packets
109038f62777SMatthias Ringwald         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
1091675e6881SMatthias Ringwald 
1092675e6881SMatthias Ringwald         if (channel->tx_send_index != channel->tx_write_index){
1093212b6be2SMatthias Ringwald             int unacknowledged_packets = l2cap_ertm_num_unacknowledged_tx_packets(channel);
1094212b6be2SMatthias Ringwald             // check remote tx window
1095212b6be2SMatthias Ringwald             log_info("unacknowledged_packets %u, remote tx window size %u", unacknowledged_packets, channel->remote_tx_window_size);
1096212b6be2SMatthias Ringwald             if (unacknowledged_packets < channel->remote_tx_window_size){
1097675e6881SMatthias Ringwald                 int index = channel->tx_send_index;
1098675e6881SMatthias Ringwald                 channel->tx_send_index++;
1099675e6881SMatthias Ringwald                 if (channel->tx_send_index >= channel->num_tx_buffers){
1100675e6881SMatthias Ringwald                     channel->tx_send_index = 0;
1101675e6881SMatthias Ringwald                 }
11027b7901d8SMatthias Ringwald                 l2cap_ertm_send_information_frame(channel, index, 0);   // final = 0
1103675e6881SMatthias Ringwald                 continue;
1104675e6881SMatthias Ringwald             }
1105212b6be2SMatthias Ringwald         }
1106675e6881SMatthias Ringwald 
1107d84e866fSMatthias Ringwald         if (channel->send_supervisor_frame_receiver_ready){
110878cd8a22SMatthias Ringwald             channel->send_supervisor_frame_receiver_ready = 0;
1109d2afdd38SMatthias Ringwald             log_info("Send S-Frame: RR %u, final %u", channel->req_seq, channel->set_final_bit_after_packet_with_poll_bit_set);
1110d2afdd38SMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 0,  channel->set_final_bit_after_packet_with_poll_bit_set, channel->req_seq);
1111d2afdd38SMatthias Ringwald             channel->set_final_bit_after_packet_with_poll_bit_set = 0;
111238f62777SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
1113675e6881SMatthias Ringwald             continue;
111438f62777SMatthias Ringwald         }
111562041d70SMatthias Ringwald         if (channel->send_supervisor_frame_receiver_ready_poll){
111678cd8a22SMatthias Ringwald             channel->send_supervisor_frame_receiver_ready_poll = 0;
111762041d70SMatthias Ringwald             log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
111862041d70SMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
111962041d70SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
112062041d70SMatthias Ringwald             continue;
112162041d70SMatthias Ringwald         }
11228f1c9639SMatthias Ringwald         if (channel->send_supervisor_frame_receiver_not_ready){
112378cd8a22SMatthias Ringwald             channel->send_supervisor_frame_receiver_not_ready = 0;
11248f1c9639SMatthias Ringwald             log_info("Send S-Frame: RNR %u", channel->req_seq);
11258f1c9639SMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
11268f1c9639SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
11278f1c9639SMatthias Ringwald             continue;
11288f1c9639SMatthias Ringwald         }
1129c7309e8dSMatthias Ringwald         if (channel->send_supervisor_frame_reject){
1130c7309e8dSMatthias Ringwald             channel->send_supervisor_frame_reject = 0;
1131c7309e8dSMatthias Ringwald             log_info("Send S-Frame: REJ %u", channel->req_seq);
1132c7309e8dSMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 0, 0, channel->req_seq);
1133c7309e8dSMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
1134c7309e8dSMatthias Ringwald             continue;
1135c7309e8dSMatthias Ringwald         }
1136df2191a7SMatthias Ringwald         if (channel->send_supervisor_frame_selective_reject){
1137df2191a7SMatthias Ringwald             channel->send_supervisor_frame_selective_reject = 0;
1138df2191a7SMatthias Ringwald             log_info("Send S-Frame: SREJ %u", channel->expected_tx_seq);
1139f85ade6bSMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT, 0, channel->set_final_bit_after_packet_with_poll_bit_set, channel->expected_tx_seq);
1140f85ade6bSMatthias Ringwald             channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1141df2191a7SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
1142df2191a7SMatthias Ringwald             continue;
1143df2191a7SMatthias Ringwald         }
11447b7901d8SMatthias Ringwald 
11457b7901d8SMatthias Ringwald         if (channel->srej_active){
11467b7901d8SMatthias Ringwald             int i;
11477b7901d8SMatthias Ringwald             for (i=0;i<channel->num_tx_buffers;i++){
11487b7901d8SMatthias Ringwald                 l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
11497b7901d8SMatthias Ringwald                 if (tx_state->retransmission_requested) {
11507b7901d8SMatthias Ringwald                     tx_state->retransmission_requested = 0;
1151d2afdd38SMatthias Ringwald                     uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set;
1152d2afdd38SMatthias Ringwald                     channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1153d2afdd38SMatthias Ringwald                     l2cap_ertm_send_information_frame(channel, i, final);
11547b7901d8SMatthias Ringwald                     break;
11557b7901d8SMatthias Ringwald                 }
11567b7901d8SMatthias Ringwald             }
11577b7901d8SMatthias Ringwald             if (i == channel->num_tx_buffers){
11587b7901d8SMatthias Ringwald                 // no retransmission request found
11597b7901d8SMatthias Ringwald                 channel->srej_active = 0;
11607b7901d8SMatthias Ringwald             } else {
11617b7901d8SMatthias Ringwald                 // packet was sent
11627b7901d8SMatthias Ringwald                 continue;
11637b7901d8SMatthias Ringwald             }
11647b7901d8SMatthias Ringwald         }
116538f62777SMatthias Ringwald #endif
116638f62777SMatthias Ringwald 
11672cd0be45Smatthias.ringwald     }
116809e9d05bSMatthias Ringwald #endif
1169da886c03S[email protected] 
1170cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1171efedfb4cSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1172efedfb4cSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
11737f107edaSMatthias Ringwald         uint8_t  * acl_buffer;
11747f107edaSMatthias Ringwald         uint8_t  * l2cap_payload;
11757f107edaSMatthias Ringwald         uint16_t pos;
11767f107edaSMatthias Ringwald         uint16_t payload_size;
1177efedfb4cSMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1178efedfb4cSMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1179efedfb4cSMatthias Ringwald         switch (channel->state){
11805cb87675SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
11815cb87675SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
11825cb87675SMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
11835cb87675SMatthias Ringwald                 // le psm, source cid, mtu, mps, initial credits
11841b8b8d05SMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
118563f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
118663f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
118763f0ac45SMatthias 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);
11885cb87675SMatthias Ringwald                 break;
118923017473SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
119023017473SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
119123017473SMatthias Ringwald                 // TODO: support larger MPS
119223017473SMatthias Ringwald                 channel->state = L2CAP_STATE_OPEN;
119363f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
119463f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
119563f0ac45SMatthias 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);
119664e11ca9SMatthias Ringwald                 // notify client
119744276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0);
119823017473SMatthias Ringwald                 break;
1199e7d0c9aaSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
1200e7d0c9aaSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1201e7d0c9aaSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
120263f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
1203e7d0c9aaSMatthias Ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1204e7d0c9aaSMatthias Ringwald                 l2cap_stop_rtx(channel);
1205e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1206e7d0c9aaSMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
1207e7d0c9aaSMatthias Ringwald                 break;
12087f107edaSMatthias Ringwald             case L2CAP_STATE_OPEN:
120985aeef60SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
121085aeef60SMatthias Ringwald 
121185aeef60SMatthias Ringwald                 // send credits
121285aeef60SMatthias Ringwald                 if (channel->new_credits_incoming){
121385aeef60SMatthias Ringwald                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
121485aeef60SMatthias Ringwald                     channel->local_sig_id = l2cap_next_sig_id();
121585aeef60SMatthias Ringwald                     uint16_t new_credits = channel->new_credits_incoming;
121685aeef60SMatthias Ringwald                     channel->new_credits_incoming = 0;
121785aeef60SMatthias Ringwald                     channel->credits_incoming += new_credits;
121885aeef60SMatthias Ringwald                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
121985aeef60SMatthias Ringwald                     break;
122085aeef60SMatthias Ringwald                 }
122185aeef60SMatthias Ringwald 
122285aeef60SMatthias Ringwald                 // send data
12237f107edaSMatthias Ringwald                 if (!channel->send_sdu_buffer) break;
12247f107edaSMatthias Ringwald                 if (!channel->credits_outgoing) break;
122585aeef60SMatthias Ringwald 
12267f107edaSMatthias Ringwald                 // send part of SDU
12277f107edaSMatthias Ringwald                 hci_reserve_packet_buffer();
12287f107edaSMatthias Ringwald                 acl_buffer = hci_get_outgoing_packet_buffer();
12297f107edaSMatthias Ringwald                 l2cap_payload = acl_buffer + 8;
12307f107edaSMatthias Ringwald                 pos = 0;
12317f107edaSMatthias Ringwald                 if (!channel->send_sdu_pos){
12327f107edaSMatthias Ringwald                     // store SDU len
12337f107edaSMatthias Ringwald                     channel->send_sdu_pos += 2;
12347f107edaSMatthias Ringwald                     little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
12357f107edaSMatthias Ringwald                     pos += 2;
12367f107edaSMatthias Ringwald                 }
12377f107edaSMatthias Ringwald                 payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
123885aeef60SMatthias Ringwald                 log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
12397f107edaSMatthias Ringwald                 memcpy(&l2cap_payload[pos], &channel->send_sdu_buffer[channel->send_sdu_pos-2], payload_size); // -2 for virtual SDU len
12407f107edaSMatthias Ringwald                 pos += payload_size;
12417f107edaSMatthias Ringwald                 channel->send_sdu_pos += payload_size;
1242f511cefaSMatthias Ringwald                 l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
12437f107edaSMatthias Ringwald                 // done
12447f107edaSMatthias Ringwald 
124585aeef60SMatthias Ringwald                 channel->credits_outgoing--;
12467f107edaSMatthias Ringwald 
12477f107edaSMatthias Ringwald                 if (channel->send_sdu_pos >= channel->send_sdu_len + 2){
12487f107edaSMatthias Ringwald                     channel->send_sdu_buffer = NULL;
124944276248SMatthias Ringwald                     // send done event
125044276248SMatthias Ringwald                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
125144276248SMatthias Ringwald                     // inform about can send now
125244276248SMatthias Ringwald                     l2cap_le_notify_channel_can_send(channel);
12537f107edaSMatthias Ringwald                 }
12547f107edaSMatthias Ringwald                 hci_send_acl_packet_buffer(8 + pos);
12557f107edaSMatthias Ringwald                 break;
1256828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1257828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1258828a7f7aSMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
1259828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1260828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1261828a7f7aSMatthias Ringwald                 break;
1262828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1263828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1264828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1265828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1266828a7f7aSMatthias Ringwald                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
1267828a7f7aSMatthias Ringwald                 break;
1268efedfb4cSMatthias Ringwald             default:
1269efedfb4cSMatthias Ringwald                 break;
1270efedfb4cSMatthias Ringwald         }
1271efedfb4cSMatthias Ringwald     }
127209e9d05bSMatthias Ringwald #endif
1273efedfb4cSMatthias Ringwald 
127409e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
1275da886c03S[email protected]     // send l2cap con paramter update if necessary
1276da886c03S[email protected]     hci_connections_get_iterator(&it);
1277665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
1278665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
12795d14fa8fSMatthias Ringwald         if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue;
1280b68d7bc3SMatthias Ringwald         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
1281da886c03S[email protected]         switch (connection->le_con_parameter_update_state){
1282b68d7bc3SMatthias Ringwald             case CON_PARAMETER_UPDATE_SEND_REQUEST:
1283b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1284b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier,
1285b68d7bc3SMatthias Ringwald                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
1286b68d7bc3SMatthias Ringwald                 break;
1287da886c03S[email protected]             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
1288b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
1289b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
1290da886c03S[email protected]                 break;
1291da886c03S[email protected]             case CON_PARAMETER_UPDATE_DENY:
1292b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1293b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
1294da886c03S[email protected]                 break;
1295da886c03S[email protected]             default:
1296da886c03S[email protected]                 break;
1297da886c03S[email protected]         }
1298da886c03S[email protected]     }
12994d7157c3S[email protected] #endif
1300da886c03S[email protected] 
130122c29ab4SMatthias Ringwald     // log_info("l2cap_run: exit");
13022cd0be45Smatthias.ringwald }
13032cd0be45Smatthias.ringwald 
130409e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1305fc64f94aSMatthias Ringwald static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
13062df5dadcS[email protected]     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
13075533f01eS[email protected]         log_info("l2cap_handle_connection_complete expected state");
13082df5dadcS[email protected]         // success, start l2cap handshake
1309fc64f94aSMatthias Ringwald         channel->con_handle = con_handle;
13102df5dadcS[email protected]         // check remote SSP feature first
13112df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
13122df5dadcS[email protected]     }
13132df5dadcS[email protected] }
13142df5dadcS[email protected] 
13151b9cb13dSMatthias Ringwald static void l2cap_ready_to_connect(l2cap_channel_t * channel){
13161b9cb13dSMatthias Ringwald 
13171b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
131827e0774aSMatthias Ringwald     // assumption: outgoing connection
13191b9cb13dSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
13201b9cb13dSMatthias Ringwald     if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
13211b9cb13dSMatthias Ringwald         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
13221b9cb13dSMatthias Ringwald         channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
13231b9cb13dSMatthias Ringwald         return;
13241b9cb13dSMatthias Ringwald     }
13251b9cb13dSMatthias Ringwald #endif
13261b9cb13dSMatthias Ringwald 
13271b9cb13dSMatthias Ringwald     // fine, go ahead
13281b9cb13dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
13291b9cb13dSMatthias Ringwald }
13301b9cb13dSMatthias Ringwald 
13312df5dadcS[email protected] static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
13322df5dadcS[email protected]     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
13332df5dadcS[email protected] 
13342df5dadcS[email protected]     // we have been waiting for remote supported features, if both support SSP,
1335ac301f95S[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));
1336fc64f94aSMatthias Ringwald     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
13372df5dadcS[email protected]         // request security level 2
13382df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
1339fc64f94aSMatthias Ringwald         gap_request_security_level(channel->con_handle, LEVEL_2);
13402df5dadcS[email protected]         return;
13412df5dadcS[email protected]     }
13421b9cb13dSMatthias Ringwald 
13431b9cb13dSMatthias Ringwald     l2cap_ready_to_connect(channel);
13442df5dadcS[email protected] }
134509e9d05bSMatthias Ringwald #endif
13462df5dadcS[email protected] 
134709e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
1348da144af5SMatthias 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,
1349da144af5SMatthias Ringwald     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
1350da144af5SMatthias Ringwald 
1351da144af5SMatthias Ringwald     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1352da144af5SMatthias Ringwald     if (!channel) {
1353da144af5SMatthias Ringwald         return NULL;
1354da144af5SMatthias Ringwald     }
1355da144af5SMatthias Ringwald 
1356da144af5SMatthias Ringwald      // Init memory (make valgrind happy)
1357da144af5SMatthias Ringwald     memset(channel, 0, sizeof(l2cap_channel_t));
1358da144af5SMatthias Ringwald 
1359da144af5SMatthias Ringwald     // fill in
1360da144af5SMatthias Ringwald     channel->packet_handler = packet_handler;
1361da144af5SMatthias Ringwald     bd_addr_copy(channel->address, address);
1362da144af5SMatthias Ringwald     channel->address_type = address_type;
1363da144af5SMatthias Ringwald     channel->psm = psm;
1364da144af5SMatthias Ringwald     channel->local_mtu  = local_mtu;
1365da144af5SMatthias Ringwald     channel->remote_mtu = L2CAP_MINIMAL_MTU;
1366da144af5SMatthias Ringwald     channel->required_security_level = security_level;
1367da144af5SMatthias Ringwald 
1368da144af5SMatthias Ringwald     //
1369da144af5SMatthias Ringwald     channel->local_cid = l2cap_next_local_cid();
1370da144af5SMatthias Ringwald     channel->con_handle = 0;
1371da144af5SMatthias Ringwald 
1372da144af5SMatthias Ringwald     // set initial state
1373da144af5SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
1374da144af5SMatthias Ringwald     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
1375da144af5SMatthias Ringwald     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
1376da144af5SMatthias Ringwald     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
137738f62777SMatthias Ringwald 
1378da144af5SMatthias Ringwald     return channel;
1379da144af5SMatthias Ringwald }
138009e9d05bSMatthias Ringwald #endif
138109e9d05bSMatthias Ringwald 
138209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1383da144af5SMatthias Ringwald 
13849077cb15SMatthias Ringwald /**
13859077cb15SMatthias Ringwald  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
13869077cb15SMatthias Ringwald  * @param packet_handler
13879077cb15SMatthias Ringwald  * @param address
13889077cb15SMatthias Ringwald  * @param psm
13899077cb15SMatthias Ringwald  * @param mtu
13909077cb15SMatthias Ringwald  * @param local_cid
13919077cb15SMatthias Ringwald  */
13929077cb15SMatthias Ringwald 
13939d139fbaSMatthias 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){
13949d139fbaSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
13959d139fbaSMatthias Ringwald     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1396da144af5SMatthias Ringwald 
13979d139fbaSMatthias 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);
1398da144af5SMatthias Ringwald 
1399da144af5SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
1400fc64f94aSMatthias Ringwald     if (!channel) {
14019077cb15SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
14029077cb15SMatthias Ringwald     }
14039077cb15SMatthias Ringwald 
14041b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
14051b9cb13dSMatthias Ringwald     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
14061b9cb13dSMatthias Ringwald #endif
14071b9cb13dSMatthias Ringwald 
14089077cb15SMatthias Ringwald     // add to connections list
1409fc64f94aSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
14109077cb15SMatthias Ringwald 
14119077cb15SMatthias Ringwald     // store local_cid
14129077cb15SMatthias Ringwald     if (out_local_cid){
1413fc64f94aSMatthias Ringwald        *out_local_cid = channel->local_cid;
14149077cb15SMatthias Ringwald     }
14159077cb15SMatthias Ringwald 
14169077cb15SMatthias Ringwald     // check if hci connection is already usable
14179077cb15SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
14189077cb15SMatthias Ringwald     if (conn){
1419add0254bSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
1420fc64f94aSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
14219077cb15SMatthias Ringwald         // check if remote supported fearures are already received
14229077cb15SMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
1423fc64f94aSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
14249077cb15SMatthias Ringwald         }
14259077cb15SMatthias Ringwald     }
14269077cb15SMatthias Ringwald 
14279077cb15SMatthias Ringwald     l2cap_run();
14289077cb15SMatthias Ringwald 
14299077cb15SMatthias Ringwald     return 0;
14309077cb15SMatthias Ringwald }
14319077cb15SMatthias Ringwald 
14321b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
14337b181629SMatthias Ringwald 
1434843bae5dSMatthias Ringwald static uint8_t l2cap_ertm_validate_local_config(uint8_t max_transmit, uint16_t retransmission_timeout_ms, uint16_t monitor_timeout_ms,
1435843bae5dSMatthias Ringwald     uint16_t local_mtu, uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size){
1436843bae5dSMatthias Ringwald 
14372b70d705SMatthias Ringwald     UNUSED(buffer);
14382b70d705SMatthias Ringwald     UNUSED(size);
14392b70d705SMatthias Ringwald 
14402b70d705SMatthias Ringwald     uint8_t result = ERROR_CODE_SUCCESS;
14412b70d705SMatthias Ringwald     if (max_transmit < 1){
14422b70d705SMatthias Ringwald         log_error("max_transmit must be >= 1");
14432b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
14442b70d705SMatthias Ringwald     }
14452b70d705SMatthias Ringwald     if (retransmission_timeout_ms < 2000){
14462b70d705SMatthias Ringwald         log_error("retransmission_timeout_ms must be >= 2000 ms");
14472b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
14482b70d705SMatthias Ringwald     }
14492b70d705SMatthias Ringwald     if (monitor_timeout_ms < 12000){
14502b70d705SMatthias Ringwald         log_error("monitor_timeout_ms must be >= 12000 ms");
14512b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
14522b70d705SMatthias Ringwald     }
1453843bae5dSMatthias Ringwald     if (local_mtu < 48){
1454843bae5dSMatthias Ringwald         log_error("local_mtu must be >= 48");
1455843bae5dSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
1456843bae5dSMatthias Ringwald     }
14572b70d705SMatthias Ringwald     if (num_rx_buffers < 1){
14582b70d705SMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
14592b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
14602b70d705SMatthias Ringwald     }
14612b70d705SMatthias Ringwald     if (num_tx_buffers < 1){
14622b70d705SMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
14632b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
14642b70d705SMatthias Ringwald     }
14652b70d705SMatthias Ringwald     return result;
14662b70d705SMatthias Ringwald }
14672b70d705SMatthias Ringwald 
1468843bae5dSMatthias Ringwald static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, int ertm_mandatory, uint8_t max_transmit, uint16_t retransmission_timeout_ms,
1469843bae5dSMatthias Ringwald     uint16_t monitor_timeout_ms, uint16_t local_mtu, uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size){
14707b181629SMatthias Ringwald 
14717b181629SMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
14727b181629SMatthias Ringwald     channel->ertm_mandatory = ertm_mandatory;
1473bbc0a9e7SMatthias Ringwald     channel->local_max_transmit = max_transmit;
1474bbc0a9e7SMatthias Ringwald     channel->local_retransmission_timeout_ms = retransmission_timeout_ms;
1475bbc0a9e7SMatthias Ringwald     channel->local_monitor_timeout_ms = monitor_timeout_ms;
1476843bae5dSMatthias Ringwald     channel->local_mtu = local_mtu;
14777b181629SMatthias Ringwald     channel->num_rx_buffers = num_rx_buffers;
14787b181629SMatthias Ringwald     channel->num_tx_buffers = num_tx_buffers;
14797b181629SMatthias Ringwald 
1480843bae5dSMatthias Ringwald     // align buffer to 16-byte boundary, just in case
1481843bae5dSMatthias Ringwald     int bytes_till_alignment = 16 - (((uintptr_t) buffer) & 0x0f);
1482843bae5dSMatthias Ringwald     buffer += bytes_till_alignment;
1483843bae5dSMatthias Ringwald     size   -= bytes_till_alignment;
1484843bae5dSMatthias Ringwald 
1485843bae5dSMatthias Ringwald     // setup state buffers
14867b181629SMatthias Ringwald     uint32_t pos = 0;
14877b181629SMatthias Ringwald     channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) &buffer[pos];
14887b181629SMatthias Ringwald     pos += num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
14897b181629SMatthias Ringwald     channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) &buffer[pos];
14907b181629SMatthias Ringwald     pos += num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
1491843bae5dSMatthias Ringwald 
1492843bae5dSMatthias Ringwald     // setup reassembly buffer
1493843bae5dSMatthias Ringwald     channel->reassembly_buffer = &buffer[pos];
1494843bae5dSMatthias Ringwald     pos += local_mtu;
1495843bae5dSMatthias Ringwald 
1496843bae5dSMatthias Ringwald     // divide rest of data equally
1497843bae5dSMatthias Ringwald     channel->local_mps = (size - pos) / (num_rx_buffers + num_tx_buffers);
1498843bae5dSMatthias Ringwald     log_info("Local MPS: %u", channel->local_mtu);
14997b181629SMatthias Ringwald     channel->rx_packets_data = &buffer[pos];
15007b181629SMatthias Ringwald     pos += num_rx_buffers * channel->local_mtu;
15017b181629SMatthias Ringwald     channel->tx_packets_data = &buffer[pos];
15027b181629SMatthias Ringwald }
15037b181629SMatthias Ringwald 
1504501329faSMatthias Ringwald uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
1505501329faSMatthias Ringwald     int ertm_mandatory, uint8_t max_transmit, uint16_t retransmission_timeout_ms, uint16_t monitor_timeout_ms,
1506843bae5dSMatthias Ringwald     uint16_t local_mtu, uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
1507501329faSMatthias Ringwald 
1508843bae5dSMatthias Ringwald     log_info("L2CAP_CREATE_CHANNEL addr %s, psm 0x%x, local mtu %u", bd_addr_to_str(address), psm, local_mtu);
15091b9cb13dSMatthias Ringwald 
15102b70d705SMatthias Ringwald     // validate local config
1511843bae5dSMatthias Ringwald     uint8_t result = l2cap_ertm_validate_local_config(max_transmit, retransmission_timeout_ms, monitor_timeout_ms, local_mtu, num_tx_buffers, num_rx_buffers, buffer, size);
15122b70d705SMatthias Ringwald     if (result) return result;
15132b70d705SMatthias Ringwald 
1514501329faSMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
15151b9cb13dSMatthias Ringwald     if (!channel) {
15161b9cb13dSMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
15171b9cb13dSMatthias Ringwald     }
15181b9cb13dSMatthias Ringwald 
15197b181629SMatthias Ringwald     // configure ERTM
15207b181629SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_mandatory, max_transmit, retransmission_timeout_ms,
1521843bae5dSMatthias Ringwald         local_mtu, monitor_timeout_ms, num_tx_buffers, num_rx_buffers, buffer, size);
15221b9cb13dSMatthias Ringwald 
15231b9cb13dSMatthias Ringwald     // add to connections list
15241b9cb13dSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
15251b9cb13dSMatthias Ringwald 
15261b9cb13dSMatthias Ringwald     // store local_cid
15271b9cb13dSMatthias Ringwald     if (out_local_cid){
15281b9cb13dSMatthias Ringwald        *out_local_cid = channel->local_cid;
15291b9cb13dSMatthias Ringwald     }
15301b9cb13dSMatthias Ringwald 
15311b9cb13dSMatthias Ringwald     // check if hci connection is already usable
15321b9cb13dSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
15331b9cb13dSMatthias Ringwald     if (conn){
15341b9cb13dSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
15351b9cb13dSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
15361b9cb13dSMatthias Ringwald         // check if remote supported fearures are already received
15371b9cb13dSMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
15381b9cb13dSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
15391b9cb13dSMatthias Ringwald         }
15401b9cb13dSMatthias Ringwald     }
15411b9cb13dSMatthias Ringwald 
15421b9cb13dSMatthias Ringwald     l2cap_run();
15431b9cb13dSMatthias Ringwald 
15441b9cb13dSMatthias Ringwald     return 0;
15451b9cb13dSMatthias Ringwald }
15461b9cb13dSMatthias Ringwald #endif
15471b9cb13dSMatthias Ringwald 
1548ce8f182eSMatthias Ringwald void
1549ce8f182eSMatthias Ringwald l2cap_disconnect(uint16_t local_cid, uint8_t reason){
1550e0abb8e7S[email protected]     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
1551b35f641cSmatthias.ringwald     // find channel for local_cid
1552b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1553f62db1e3Smatthias.ringwald     if (channel) {
1554e7ff783cSmatthias.ringwald         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1555f62db1e3Smatthias.ringwald     }
15562cd0be45Smatthias.ringwald     // process
15572cd0be45Smatthias.ringwald     l2cap_run();
155843625864Smatthias.ringwald }
15591e6aba47Smatthias.ringwald 
1560afde0c52Smatthias.ringwald static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
1561665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1562665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1563665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1564665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1565058e3d6bSMatthias Ringwald         if ( bd_addr_cmp( channel->address, address) != 0) continue;
1566c22aecc9S[email protected]         // channel for this address found
1567c22aecc9S[email protected]         switch (channel->state){
1568c22aecc9S[email protected]             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
1569c22aecc9S[email protected]             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1570afde0c52Smatthias.ringwald                 // failure, forward error code
1571afde0c52Smatthias.ringwald                 l2cap_emit_channel_opened(channel, status);
1572afde0c52Smatthias.ringwald                 // discard channel
15739dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
1574665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1575d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
1576c22aecc9S[email protected]                 break;
1577c22aecc9S[email protected]             default:
1578c22aecc9S[email protected]                 break;
1579afde0c52Smatthias.ringwald         }
1580afde0c52Smatthias.ringwald     }
1581afde0c52Smatthias.ringwald }
1582afde0c52Smatthias.ringwald 
1583afde0c52Smatthias.ringwald static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
1584665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1585665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1586665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1587665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1588058e3d6bSMatthias Ringwald         if ( ! bd_addr_cmp( channel->address, address) ){
15892df5dadcS[email protected]             l2cap_handle_connection_complete(handle, channel);
1590afde0c52Smatthias.ringwald         }
1591afde0c52Smatthias.ringwald     }
15926fdcc387Smatthias.ringwald     // process
15936fdcc387Smatthias.ringwald     l2cap_run();
1594afde0c52Smatthias.ringwald }
159509e9d05bSMatthias Ringwald #endif
1596b448a0e7Smatthias.ringwald 
1597*96646001SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1598*96646001SMatthias Ringwald static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel){
1599*96646001SMatthias Ringwald     if (l2cap_ertm_can_store_packet_now(channel)){
1600*96646001SMatthias Ringwald         channel->waiting_for_can_send_now = 0;
1601*96646001SMatthias Ringwald         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
1602*96646001SMatthias Ringwald     }
1603*96646001SMatthias Ringwald }
1604*96646001SMatthias Ringwald #endif
1605*96646001SMatthias Ringwald 
160633c40538SMatthias Ringwald static void l2cap_notify_channel_can_send(void){
160709e9d05bSMatthias Ringwald 
160809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
160933c40538SMatthias Ringwald     btstack_linked_list_iterator_t it;
161033c40538SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
161133c40538SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
161233c40538SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
161333c40538SMatthias Ringwald         if (!channel->waiting_for_can_send_now) continue;
1614fc64f94aSMatthias Ringwald         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
161533c40538SMatthias Ringwald         channel->waiting_for_can_send_now = 0;
161634e7e577SMatthias Ringwald         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
161733c40538SMatthias Ringwald     }
161809e9d05bSMatthias Ringwald #endif
161944276248SMatthias Ringwald 
16202125de09SMatthias Ringwald     int i;
16212125de09SMatthias Ringwald     for (i=0;i<L2CAP_FIXED_CHANNEL_TABLE_SIZE;i++){
1622773c4106SMatthias Ringwald         if (!fixed_channels[i].callback) continue;
16232125de09SMatthias Ringwald         if (!fixed_channels[i].waiting_for_can_send_now) continue;
162435454696SMatthias Ringwald         int can_send = 0;
162534e7e577SMatthias Ringwald         if (l2cap_fixed_channel_table_index_is_le(i)){
162635454696SMatthias Ringwald #ifdef ENABLE_BLE
162734e7e577SMatthias Ringwald             can_send = hci_can_send_acl_le_packet_now();
162835454696SMatthias Ringwald #endif
162934e7e577SMatthias Ringwald         } else {
163035454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
163134e7e577SMatthias Ringwald             can_send = hci_can_send_acl_classic_packet_now();
163235454696SMatthias Ringwald #endif
163334e7e577SMatthias Ringwald         }
163434e7e577SMatthias Ringwald         if (!can_send) continue;
163534e7e577SMatthias Ringwald         fixed_channels[i].waiting_for_can_send_now = 0;
163634e7e577SMatthias Ringwald         l2cap_emit_can_send_now(fixed_channels[i].callback, l2cap_fixed_channel_table_channel_id_for_index(i));
16372125de09SMatthias Ringwald     }
163833c40538SMatthias Ringwald }
163933c40538SMatthias Ringwald 
1640d9a7306aSMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
1641afde0c52Smatthias.ringwald 
16429ec2630cSMatthias Ringwald     UNUSED(packet_type);
16439ec2630cSMatthias Ringwald     UNUSED(cid);
16449ec2630cSMatthias Ringwald     UNUSED(size);
16459ec2630cSMatthias Ringwald 
1646afde0c52Smatthias.ringwald     bd_addr_t address;
1647afde0c52Smatthias.ringwald     hci_con_handle_t handle;
16482d00edd4Smatthias.ringwald     int hci_con_used;
164909e9d05bSMatthias Ringwald     btstack_linked_list_iterator_t it;
165009e9d05bSMatthias Ringwald 
165109e9d05bSMatthias Ringwald     // avoid unused warnings
1652f3963406SMatthias Ringwald     UNUSED(address);
1653f3963406SMatthias Ringwald     UNUSED(hci_con_used);
1654f3963406SMatthias Ringwald     UNUSED(it);
1655f22209dfSMatthias Ringwald     UNUSED(handle);
1656afde0c52Smatthias.ringwald 
16570e2df43fSMatthias Ringwald     switch(hci_event_packet_get_type(packet)){
1658afde0c52Smatthias.ringwald 
165909e9d05bSMatthias Ringwald         // Notify channel packet handler if they can send now
166009e9d05bSMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
166109e9d05bSMatthias Ringwald         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
166209e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
166309e9d05bSMatthias Ringwald             l2cap_notify_channel_can_send();
166409e9d05bSMatthias Ringwald             break;
166509e9d05bSMatthias Ringwald 
166609e9d05bSMatthias Ringwald         case HCI_EVENT_COMMAND_STATUS:
166709e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
166809e9d05bSMatthias Ringwald             break;
166909e9d05bSMatthias Ringwald 
167009e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1671afde0c52Smatthias.ringwald         // handle connection complete events
1672afde0c52Smatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
1673724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], address);
1674afde0c52Smatthias.ringwald             if (packet[2] == 0){
1675f8fbdce0SMatthias Ringwald                 handle = little_endian_read_16(packet, 3);
1676afde0c52Smatthias.ringwald                 l2cap_handle_connection_success_for_addr(address, handle);
1677afde0c52Smatthias.ringwald             } else {
1678afde0c52Smatthias.ringwald                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
1679afde0c52Smatthias.ringwald             }
1680afde0c52Smatthias.ringwald             break;
1681afde0c52Smatthias.ringwald 
1682afde0c52Smatthias.ringwald         // handle successful create connection cancel command
1683afde0c52Smatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
1684073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
1685afde0c52Smatthias.ringwald                 if (packet[5] == 0){
1686724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[6], address);
1687afde0c52Smatthias.ringwald                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
1688afde0c52Smatthias.ringwald                     l2cap_handle_connection_failed_for_addr(address, 0x16);
168903cfbabcSmatthias.ringwald                 }
16901e6aba47Smatthias.ringwald             }
169139d59809Smatthias.ringwald             l2cap_run();    // try sending signaling packets first
169239d59809Smatthias.ringwald             break;
169309e9d05bSMatthias Ringwald #endif
169427a923d0Smatthias.ringwald 
16951e6aba47Smatthias.ringwald         // handle disconnection complete events
1696afde0c52Smatthias.ringwald         case HCI_EVENT_DISCONNECTION_COMPLETE:
1697c22aecc9S[email protected]             // send l2cap disconnect events for all channels on this handle and free them
169809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1699d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1700665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1701665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1702665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1703fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
170415ec09bbSmatthias.ringwald                 l2cap_emit_channel_closed(channel);
17059dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
1706665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1707d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
170827a923d0Smatthias.ringwald             }
170909e9d05bSMatthias Ringwald #endif
1710a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1711d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1712991fea48SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1713991fea48SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1714991fea48SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1715991fea48SMatthias Ringwald                 if (channel->con_handle != handle) continue;
1716991fea48SMatthias Ringwald                 l2cap_emit_channel_closed(channel);
1717991fea48SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1718991fea48SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
1719991fea48SMatthias Ringwald             }
1720991fea48SMatthias Ringwald #endif
1721afde0c52Smatthias.ringwald             break;
1722fcadd0caSmatthias.ringwald 
1723ee091cf1Smatthias.ringwald         // HCI Connection Timeouts
172409e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1725afde0c52Smatthias.ringwald         case L2CAP_EVENT_TIMEOUT_CHECK:
1726f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
1727bd04d84aSMatthias Ringwald             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
172880ca58a0Smatthias.ringwald             if (hci_authentication_active_for_handle(handle)) break;
17292d00edd4Smatthias.ringwald             hci_con_used = 0;
1730665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1731665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1732665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1733fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
17342d00edd4Smatthias.ringwald                 hci_con_used = 1;
1735c22aecc9S[email protected]                 break;
1736ee091cf1Smatthias.ringwald             }
17372d00edd4Smatthias.ringwald             if (hci_con_used) break;
1738d94d3cafS[email protected]             if (!hci_can_send_command_packet_now()) break;
17399edc8742Smatthias.ringwald             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
1740afde0c52Smatthias.ringwald             break;
1741ee091cf1Smatthias.ringwald 
1742df3354fcS[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1743f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1744665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1745665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1746665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1747fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
17482df5dadcS[email protected]                 l2cap_handle_remote_supported_features_received(channel);
1749df3354fcS[email protected]                 break;
1750df3354fcS[email protected]             }
1751c22aecc9S[email protected]             break;
1752df3354fcS[email protected] 
17535611a760SMatthias Ringwald         case GAP_EVENT_SECURITY_LEVEL:
1754f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
1755bd63148eS[email protected]             log_info("l2cap - security level update");
1756665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1757665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1758665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1759fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
17605533f01eS[email protected] 
1761bd63148eS[email protected]                 log_info("l2cap - state %u", channel->state);
1762bd63148eS[email protected] 
1763e569dfd9SMatthias Ringwald                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
17645533f01eS[email protected]                 gap_security_level_t required_level = channel->required_security_level;
17655533f01eS[email protected] 
1766df3354fcS[email protected]                 switch (channel->state){
1767df3354fcS[email protected]                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
17685533f01eS[email protected]                         if (actual_level >= required_level){
176952606043SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
177052606043SMatthias Ringwald                             // we need to know if ERTM is supported before sending a config response
177152606043SMatthias Ringwald                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
177252606043SMatthias Ringwald                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
177352606043SMatthias Ringwald                             channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
177452606043SMatthias Ringwald #else
1775f85a9399S[email protected]                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
177644276248SMatthias Ringwald                             l2cap_emit_incoming_connection(channel);
177752606043SMatthias Ringwald #endif
17781eb2563eS[email protected]                         } else {
1779775ecc36SMatthias Ringwald                             channel->reason = 0x0003; // security block
17801eb2563eS[email protected]                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
17811eb2563eS[email protected]                         }
1782df3354fcS[email protected]                         break;
1783df3354fcS[email protected] 
1784df3354fcS[email protected]                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
17855533f01eS[email protected]                         if (actual_level >= required_level){
17861b9cb13dSMatthias Ringwald                             l2cap_ready_to_connect(channel);
1787df3354fcS[email protected]                         } else {
1788df3354fcS[email protected]                             // disconnnect, authentication not good enough
1789df3354fcS[email protected]                             hci_disconnect_security_block(handle);
1790df3354fcS[email protected]                         }
1791df3354fcS[email protected]                         break;
1792df3354fcS[email protected] 
1793df3354fcS[email protected]                     default:
1794df3354fcS[email protected]                         break;
1795df3354fcS[email protected]                 }
1796f85a9399S[email protected]             }
1797f85a9399S[email protected]             break;
179809e9d05bSMatthias Ringwald #endif
1799f85a9399S[email protected] 
1800afde0c52Smatthias.ringwald         default:
1801afde0c52Smatthias.ringwald             break;
1802afde0c52Smatthias.ringwald     }
1803afde0c52Smatthias.ringwald 
1804bd63148eS[email protected]     l2cap_run();
18051e6aba47Smatthias.ringwald }
18061e6aba47Smatthias.ringwald 
1807e74c5f58SMatthias 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){
18084cf56b4aSmatthias.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."
18092b360848Smatthias.ringwald     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
18102b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].handle = handle;
18112b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].code = code;
18122b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].sig_id = sig_id;
1813e74c5f58SMatthias Ringwald         signaling_responses[signaling_responses_pending].cid = cid;
18142b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].data = data;
18152b360848Smatthias.ringwald         signaling_responses_pending++;
18162b360848Smatthias.ringwald         l2cap_run();
18172b360848Smatthias.ringwald     }
18182b360848Smatthias.ringwald }
18192b360848Smatthias.ringwald 
182009e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
182109e9d05bSMatthias Ringwald static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
182209e9d05bSMatthias Ringwald     channel->remote_sig_id = identifier;
182309e9d05bSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
182409e9d05bSMatthias Ringwald     l2cap_run();
182509e9d05bSMatthias Ringwald }
182609e9d05bSMatthias Ringwald 
1827b35f641cSmatthias.ringwald static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
1828645658c9Smatthias.ringwald 
18299da54300S[email protected]     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
1830645658c9Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
1831645658c9Smatthias.ringwald     if (!service) {
1832645658c9Smatthias.ringwald         // 0x0002 PSM not supported
1833e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
1834645658c9Smatthias.ringwald         return;
1835645658c9Smatthias.ringwald     }
1836645658c9Smatthias.ringwald 
18375061f3afS[email protected]     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
1838645658c9Smatthias.ringwald     if (!hci_connection) {
18392b360848Smatthias.ringwald         //
18409da54300S[email protected]         log_error("no hci_connection for handle %u", handle);
1841645658c9Smatthias.ringwald         return;
1842645658c9Smatthias.ringwald     }
18432bd8b7e7S[email protected] 
1844645658c9Smatthias.ringwald     // alloc structure
18459da54300S[email protected]     // log_info("l2cap_handle_connection_request register channel");
1846da144af5SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, hci_connection->address, BD_ADDR_TYPE_CLASSIC,
1847da144af5SMatthias Ringwald     psm, service->mtu, service->required_security_level);
18482b360848Smatthias.ringwald     if (!channel){
18492b360848Smatthias.ringwald         // 0x0004 No resources available
1850e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
18512b360848Smatthias.ringwald         return;
18522b360848Smatthias.ringwald     }
1853da144af5SMatthias Ringwald 
1854fc64f94aSMatthias Ringwald     channel->con_handle = handle;
1855b35f641cSmatthias.ringwald     channel->remote_cid = source_cid;
1856b1988dceSmatthias.ringwald     channel->remote_sig_id = sig_id;
1857645658c9Smatthias.ringwald 
1858f53da564S[email protected]     // limit local mtu to max acl packet length - l2cap header
18592985cb84Smatthias.ringwald     if (channel->local_mtu > l2cap_max_mtu()) {
18602985cb84Smatthias.ringwald         channel->local_mtu = l2cap_max_mtu();
18619775e25bSmatthias.ringwald     }
18629775e25bSmatthias.ringwald 
1863645658c9Smatthias.ringwald     // set initial state
1864df3354fcS[email protected]     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
1865a24785d0SMatthias Ringwald     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
1866e405ae81Smatthias.ringwald 
1867645658c9Smatthias.ringwald     // add to connections list
1868665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1869645658c9Smatthias.ringwald 
1870f85a9399S[email protected]     // assert security requirements
18711eb2563eS[email protected]     gap_request_security_level(handle, channel->required_security_level);
1872e405ae81Smatthias.ringwald }
1873645658c9Smatthias.ringwald 
1874ce8f182eSMatthias Ringwald void l2cap_accept_connection(uint16_t local_cid){
1875e0abb8e7S[email protected]     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
1876b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1877e405ae81Smatthias.ringwald     if (!channel) {
1878ce8f182eSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
1879e405ae81Smatthias.ringwald         return;
1880e405ae81Smatthias.ringwald     }
1881e405ae81Smatthias.ringwald 
188243ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
188343ec931dSMatthias Ringwald     // configure L2CAP Basic mode
188443ec931dSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
188543ec931dSMatthias Ringwald #endif
188643ec931dSMatthias Ringwald 
1887552d92a1Smatthias.ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
1888e405ae81Smatthias.ringwald 
1889552d92a1Smatthias.ringwald     // process
1890552d92a1Smatthias.ringwald     l2cap_run();
1891e405ae81Smatthias.ringwald }
1892645658c9Smatthias.ringwald 
189343ec931dSMatthias Ringwald 
189443ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1895843bae5dSMatthias Ringwald uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, int ertm_mandatory, uint8_t max_transmit, uint16_t retransmission_timeout_ms,
1896843bae5dSMatthias Ringwald      uint16_t monitor_timeout_ms, uint16_t local_mtu, uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size){
1897501329faSMatthias Ringwald 
189843ec931dSMatthias Ringwald     log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
189943ec931dSMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
190043ec931dSMatthias Ringwald     if (!channel) {
190143ec931dSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
19022b70d705SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
190343ec931dSMatthias Ringwald     }
190443ec931dSMatthias Ringwald 
19052b70d705SMatthias Ringwald     // validate local config
1906843bae5dSMatthias Ringwald     uint8_t result = l2cap_ertm_validate_local_config(max_transmit, retransmission_timeout_ms, monitor_timeout_ms, local_mtu, num_tx_buffers, num_rx_buffers, buffer, size);
19072b70d705SMatthias Ringwald     if (result) return result;
19082b70d705SMatthias Ringwald 
190943ec931dSMatthias Ringwald     // configure L2CAP ERTM
1910843bae5dSMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_mandatory, max_transmit, retransmission_timeout_ms, monitor_timeout_ms, local_mtu, num_tx_buffers, num_rx_buffers, buffer, size);
191143ec931dSMatthias Ringwald 
19127b181629SMatthias Ringwald     // continue
191343ec931dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
191443ec931dSMatthias Ringwald 
191543ec931dSMatthias Ringwald     // process
191643ec931dSMatthias Ringwald     l2cap_run();
19172b70d705SMatthias Ringwald 
19182b70d705SMatthias Ringwald     return ERROR_CODE_SUCCESS;
191943ec931dSMatthias Ringwald }
19202a424812SMatthias Ringwald 
192167a3a5b7SMatthias Ringwald uint8_t l2cap_ertm_set_busy(uint16_t local_cid){
19228f1c9639SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
19238f1c9639SMatthias Ringwald     if (!channel) {
19248f1c9639SMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
19258f1c9639SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
19268f1c9639SMatthias Ringwald     }
19272bea1b8dSMatthias Ringwald     if (!channel->local_busy){
19282bea1b8dSMatthias Ringwald         channel->local_busy = 1;
19298f1c9639SMatthias Ringwald         channel->send_supervisor_frame_receiver_not_ready = 1;
19308f1c9639SMatthias Ringwald         l2cap_run();
19312bea1b8dSMatthias Ringwald     }
193267a3a5b7SMatthias Ringwald     return ERROR_CODE_SUCCESS;
193367a3a5b7SMatthias Ringwald }
193467a3a5b7SMatthias Ringwald 
193567a3a5b7SMatthias Ringwald uint8_t l2cap_ertm_set_ready(uint16_t local_cid){
19362bea1b8dSMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
19372bea1b8dSMatthias Ringwald     if (!channel) {
19382bea1b8dSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
19392bea1b8dSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
19402bea1b8dSMatthias Ringwald     }
19412bea1b8dSMatthias Ringwald     if (channel->local_busy){
19422bea1b8dSMatthias Ringwald         channel->local_busy = 0;
19432bea1b8dSMatthias Ringwald         channel->send_supervisor_frame_receiver_ready_poll = 1;
19442bea1b8dSMatthias Ringwald         l2cap_run();
19452bea1b8dSMatthias Ringwald     }
194667a3a5b7SMatthias Ringwald     return ERROR_CODE_SUCCESS;
194767a3a5b7SMatthias Ringwald }
194867a3a5b7SMatthias Ringwald 
19492a424812SMatthias Ringwald static void l2cap_ertm_handle_req_seq(l2cap_channel_t * l2cap_channel, uint8_t req_seq){
1950*96646001SMatthias Ringwald     int num_buffers_acked = 0;
19512a424812SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
1952bc4521b7SMatthias Ringwald     while (1){
19532a424812SMatthias Ringwald         tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
1954bc4521b7SMatthias Ringwald         // calc delta
1955bc4521b7SMatthias Ringwald         int delta = (req_seq - tx_state->tx_seq) & 0x03f;
1956bc4521b7SMatthias Ringwald         if (delta == 0) break;  // all packets acknowledged
1957bc4521b7SMatthias Ringwald         if (delta > l2cap_channel->remote_tx_window_size) break;
1958bc4521b7SMatthias Ringwald 
1959*96646001SMatthias Ringwald         num_buffers_acked++;
1960bc4521b7SMatthias Ringwald         log_info("RR seq %u => packet with tx_seq %u done", req_seq, tx_state->tx_seq);
1961bc4521b7SMatthias Ringwald 
196262041d70SMatthias Ringwald         // stop retransmission timer
196362041d70SMatthias Ringwald         btstack_run_loop_remove_timer(&tx_state->retransmission_timer);
19642a424812SMatthias Ringwald         l2cap_channel->tx_read_index++;
19652a424812SMatthias Ringwald         if (l2cap_channel->tx_read_index >= l2cap_channel->num_rx_buffers){
19662a424812SMatthias Ringwald             l2cap_channel->tx_read_index = 0;
19672a424812SMatthias Ringwald         }
1968bc4521b7SMatthias Ringwald 
1969bc4521b7SMatthias Ringwald         // no unack packages
1970bc4521b7SMatthias Ringwald         if (l2cap_channel->tx_read_index == l2cap_channel->tx_write_index) break;
19712a424812SMatthias Ringwald     }
1972*96646001SMatthias Ringwald 
1973*96646001SMatthias Ringwald     if (num_buffers_acked){
1974*96646001SMatthias Ringwald         l2cap_ertm_notify_channel_can_send(l2cap_channel);
1975*96646001SMatthias Ringwald     }
19762a424812SMatthias Ringwald }
197767a3a5b7SMatthias Ringwald 
19787b7901d8SMatthias Ringwald static l2cap_ertm_tx_packet_state_t * l2cap_ertm_get_tx_state(l2cap_channel_t * l2cap_channel, uint8_t tx_seq){
19797b7901d8SMatthias Ringwald     int i;
19807b7901d8SMatthias Ringwald     for (i=0;i<l2cap_channel->num_tx_buffers;i++){
19817b7901d8SMatthias Ringwald         l2cap_ertm_tx_packet_state_t * tx_state = &l2cap_channel->tx_packets_state[i];
19827b7901d8SMatthias Ringwald         if (tx_state->tx_seq == tx_seq) return tx_state;
19837b7901d8SMatthias Ringwald     }
19847b7901d8SMatthias Ringwald     return NULL;
19857b7901d8SMatthias Ringwald }
198643ec931dSMatthias Ringwald #endif
198743ec931dSMatthias Ringwald 
198843ec931dSMatthias Ringwald 
19897ef6a7bbSMatthias Ringwald void l2cap_decline_connection(uint16_t local_cid){
19907ef6a7bbSMatthias Ringwald     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
1991b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
1992e405ae81Smatthias.ringwald     if (!channel) {
1993ce8f182eSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
1994e405ae81Smatthias.ringwald         return;
1995e405ae81Smatthias.ringwald     }
1996e7ff783cSmatthias.ringwald     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
19977ef6a7bbSMatthias Ringwald     channel->reason = 0x04; // no resources available
1998e7ff783cSmatthias.ringwald     l2cap_run();
1999645658c9Smatthias.ringwald }
2000645658c9Smatthias.ringwald 
20017f02f414SMatthias Ringwald static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
2002b1988dceSmatthias.ringwald 
2003b1988dceSmatthias.ringwald     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2004b1988dceSmatthias.ringwald 
2005f8fbdce0SMatthias Ringwald     uint16_t flags = little_endian_read_16(command, 6);
200663a7246aSmatthias.ringwald     if (flags & 1) {
200763a7246aSmatthias.ringwald         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
200863a7246aSmatthias.ringwald     }
200963a7246aSmatthias.ringwald 
20102784b77dSmatthias.ringwald     // accept the other's configuration options
2011f8fbdce0SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
20123de7c0caSmatthias.ringwald     uint16_t pos     = 8;
20133de7c0caSmatthias.ringwald     while (pos < end_pos){
201463a7246aSmatthias.ringwald         uint8_t option_hint = command[pos] >> 7;
201563a7246aSmatthias.ringwald         uint8_t option_type = command[pos] & 0x7f;
20163844aeadSMatthias Ringwald         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
201763a7246aSmatthias.ringwald         pos++;
20181dc511deSmatthias.ringwald         uint8_t length = command[pos++];
20191dc511deSmatthias.ringwald         // MTU { type(8): 1, len(8):2, MTU(16) }
202063a7246aSmatthias.ringwald         if (option_type == 1 && length == 2){
2021f8fbdce0SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, pos);
20223844aeadSMatthias Ringwald             log_info("Remote MTU %u", channel->remote_mtu);
20239d139fbaSMatthias Ringwald             if (channel->remote_mtu > l2cap_max_mtu()){
20249d139fbaSMatthias Ringwald                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
20259d139fbaSMatthias Ringwald                 channel->remote_mtu = l2cap_max_mtu();
20269d139fbaSMatthias Ringwald             }
202763a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
202863a7246aSmatthias.ringwald         }
20290fe7a9d0S[email protected]         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
20300fe7a9d0S[email protected]         if (option_type == 2 && length == 2){
2031f8fbdce0SMatthias Ringwald             channel->flush_timeout = little_endian_read_16(command, pos);
20323844aeadSMatthias Ringwald             log_info("Flush timeout: %u ms", channel->flush_timeout);
20330fe7a9d0S[email protected]         }
2034f2fa388dSMatthias Ringwald 
20356dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
20366dca2a0cSMatthias Ringwald         // Retransmission and Flow Control Option
20376dca2a0cSMatthias Ringwald         if (option_type == 4 && length == 9){
20383232a1c6SMatthias Ringwald             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
2039ac8f1300SMatthias Ringwald             switch(channel->mode){
2040ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
204125cd60d3SMatthias Ringwald                     // Store remote config
2042bbc0a9e7SMatthias Ringwald                     channel->remote_tx_window_size = command[pos+1];
2043bbc0a9e7SMatthias Ringwald                     channel->remote_max_transmit   = command[pos+2];
2044bbc0a9e7SMatthias Ringwald                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
2045bbc0a9e7SMatthias Ringwald                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
20463844aeadSMatthias Ringwald                     channel->remote_mps = little_endian_read_16(command, pos + 7);
20473844aeadSMatthias Ringwald                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
2048bbc0a9e7SMatthias Ringwald                         channel->remote_tx_window_size,
2049bbc0a9e7SMatthias Ringwald                         channel->remote_max_transmit,
2050bbc0a9e7SMatthias Ringwald                         channel->remote_retransmission_timeout_ms,
20513844aeadSMatthias Ringwald                         channel->remote_monitor_timeout_ms,
20523844aeadSMatthias Ringwald                         channel->remote_mps);
205325cd60d3SMatthias Ringwald                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
205425cd60d3SMatthias Ringwald                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
205525cd60d3SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2056ac8f1300SMatthias Ringwald                     } else {
2057ac8f1300SMatthias Ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
2058ac8f1300SMatthias Ringwald                     }
2059ac8f1300SMatthias Ringwald                     break;
2060ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
2061ac8f1300SMatthias Ringwald                     switch (mode){
2062ac8f1300SMatthias Ringwald                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2063ac8f1300SMatthias Ringwald                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
2064ac8f1300SMatthias Ringwald                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
2065ac8f1300SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2066ac8f1300SMatthias Ringwald                             }
2067ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
2068ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
2069ac8f1300SMatthias Ringwald                             break;
2070ac8f1300SMatthias Ringwald                         default: // case L2CAP_CHANNEL_MODE_BASIC:
2071ac8f1300SMatthias Ringwald                             // TODO store and evaluate configuration
2072ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
2073ac8f1300SMatthias Ringwald                             break;
2074ac8f1300SMatthias Ringwald                     }
2075ac8f1300SMatthias Ringwald                     break;
2076ac8f1300SMatthias Ringwald                 default:
2077ac8f1300SMatthias Ringwald                     break;
2078ac8f1300SMatthias Ringwald             }
20793232a1c6SMatthias Ringwald         }
20806dca2a0cSMatthias Ringwald #endif
208163a7246aSmatthias.ringwald         // check for unknown options
208263a7246aSmatthias.ringwald         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
2083c177a91cS[email protected]             log_info("l2cap cid %u, unknown options", channel->local_cid);
208463a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
20851dc511deSmatthias.ringwald         }
20861dc511deSmatthias.ringwald         pos += length;
20871dc511deSmatthias.ringwald     }
20882784b77dSmatthias.ringwald }
20892784b77dSmatthias.ringwald 
2090f2fa388dSMatthias Ringwald static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
2091f2fa388dSMatthias Ringwald     log_info("l2cap_signaling_handle_configure_response");
20923232a1c6SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
20933232a1c6SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2094f2fa388dSMatthias Ringwald     uint16_t pos     = 10;
20953232a1c6SMatthias Ringwald     while (pos < end_pos){
20963232a1c6SMatthias Ringwald         uint8_t option_hint = command[pos] >> 7;
20973232a1c6SMatthias Ringwald         uint8_t option_type = command[pos] & 0x7f;
20983232a1c6SMatthias Ringwald         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
20993232a1c6SMatthias Ringwald         pos++;
21003232a1c6SMatthias Ringwald         uint8_t length = command[pos++];
21013232a1c6SMatthias Ringwald 
21023232a1c6SMatthias Ringwald         // Retransmission and Flow Control Option
21033232a1c6SMatthias Ringwald         if (option_type == 4 && length == 9){
2104ac8f1300SMatthias Ringwald             switch (channel->mode){
2105ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2106f2fa388dSMatthias Ringwald                     if (channel->ertm_mandatory){
2107ac8f1300SMatthias Ringwald                         // ??
2108f2fa388dSMatthias Ringwald                     } else {
2109ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
2110ac8f1300SMatthias Ringwald                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2111f2fa388dSMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
21123232a1c6SMatthias Ringwald                         }
21133232a1c6SMatthias Ringwald                     }
2114ac8f1300SMatthias Ringwald                     break;
2115ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
2116ac8f1300SMatthias Ringwald                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2117ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
2118ac8f1300SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2119ac8f1300SMatthias Ringwald                     }
2120ac8f1300SMatthias Ringwald                     break;
2121ac8f1300SMatthias Ringwald                 default:
2122ac8f1300SMatthias Ringwald                     break;
21233232a1c6SMatthias Ringwald             }
2124f2fa388dSMatthias Ringwald         }
21253232a1c6SMatthias Ringwald 
21263232a1c6SMatthias Ringwald         // check for unknown options
21273232a1c6SMatthias Ringwald         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
21283232a1c6SMatthias Ringwald             log_info("l2cap cid %u, unknown options", channel->local_cid);
21293232a1c6SMatthias Ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
21303232a1c6SMatthias Ringwald         }
21313232a1c6SMatthias Ringwald 
21323232a1c6SMatthias Ringwald         pos += length;
21333232a1c6SMatthias Ringwald     }
21343232a1c6SMatthias Ringwald #endif
21353232a1c6SMatthias Ringwald }
21363232a1c6SMatthias Ringwald 
2137fa8473a4Smatthias.ringwald static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
21389da54300S[email protected]     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
213973cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
214073cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
2141019f9b43SMatthias Ringwald     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
2142019f9b43SMatthias Ringwald     if (channel->state == L2CAP_STATE_OPEN) return 0;
2143fa8473a4Smatthias.ringwald     return 1;
2144fa8473a4Smatthias.ringwald }
2145fa8473a4Smatthias.ringwald 
2146fa8473a4Smatthias.ringwald 
21477f02f414SMatthias Ringwald static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
21481e6aba47Smatthias.ringwald 
214900d93d79Smatthias.ringwald     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
215000d93d79Smatthias.ringwald     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
215138e5900eSmatthias.ringwald     uint16_t result = 0;
21521e6aba47Smatthias.ringwald 
21539da54300S[email protected]     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
2154b35f641cSmatthias.ringwald 
21559a011532Smatthias.ringwald     // handle DISCONNECT REQUESTS seperately
21569a011532Smatthias.ringwald     if (code == DISCONNECTION_REQUEST){
21579a011532Smatthias.ringwald         switch (channel->state){
2158fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
21599a011532Smatthias.ringwald             case L2CAP_STATE_OPEN:
21602b83fb7dSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
21619a011532Smatthias.ringwald             case L2CAP_STATE_WAIT_DISCONNECT:
21629a011532Smatthias.ringwald                 l2cap_handle_disconnect_request(channel, identifier);
21639a011532Smatthias.ringwald                 break;
21649a011532Smatthias.ringwald 
21659a011532Smatthias.ringwald             default:
21669a011532Smatthias.ringwald                 // ignore in other states
21679a011532Smatthias.ringwald                 break;
21689a011532Smatthias.ringwald         }
21699a011532Smatthias.ringwald         return;
21709a011532Smatthias.ringwald     }
21719a011532Smatthias.ringwald 
217256081214Smatthias.ringwald     // @STATEMACHINE(l2cap)
21731e6aba47Smatthias.ringwald     switch (channel->state) {
21741e6aba47Smatthias.ringwald 
21751e6aba47Smatthias.ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
21761e6aba47Smatthias.ringwald             switch (code){
21771e6aba47Smatthias.ringwald                 case CONNECTION_RESPONSE:
21785932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2179f8fbdce0SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
218038e5900eSmatthias.ringwald                     switch (result) {
218138e5900eSmatthias.ringwald                         case 0:
2182169f8b28Smatthias.ringwald                             // successful connection
2183f8fbdce0SMatthias Ringwald                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2184fa8473a4Smatthias.ringwald                             channel->state = L2CAP_STATE_CONFIG;
218528ca2b46S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
218638e5900eSmatthias.ringwald                             break;
218738e5900eSmatthias.ringwald                         case 1:
21885932bd7cS[email protected]                             // connection pending. get some coffee, but start the ERTX
21895932bd7cS[email protected]                             l2cap_start_ertx(channel);
219038e5900eSmatthias.ringwald                             break;
219138e5900eSmatthias.ringwald                         default:
2192eb920dbeSmatthias.ringwald                             // channel closed
2193eb920dbeSmatthias.ringwald                             channel->state = L2CAP_STATE_CLOSED;
2194f32b992eSmatthias.ringwald                             // map l2cap connection response result to BTstack status enumeration
219538e5900eSmatthias.ringwald                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
2196eb920dbeSmatthias.ringwald 
2197eb920dbeSmatthias.ringwald                             // drop link key if security block
2198eb920dbeSmatthias.ringwald                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
219915a95bd5SMatthias Ringwald                                 gap_drop_link_key_for_bd_addr(channel->address);
2200eb920dbeSmatthias.ringwald                             }
2201eb920dbeSmatthias.ringwald 
2202eb920dbeSmatthias.ringwald                             // discard channel
2203665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2204d3a9df87Smatthias.ringwald                             btstack_memory_l2cap_channel_free(channel);
220538e5900eSmatthias.ringwald                             break;
22061e6aba47Smatthias.ringwald                     }
22071e6aba47Smatthias.ringwald                     break;
220838e5900eSmatthias.ringwald 
220938e5900eSmatthias.ringwald                 default:
22101e6aba47Smatthias.ringwald                     //@TODO: implement other signaling packets
221138e5900eSmatthias.ringwald                     break;
22121e6aba47Smatthias.ringwald             }
22131e6aba47Smatthias.ringwald             break;
22141e6aba47Smatthias.ringwald 
2215fa8473a4Smatthias.ringwald         case L2CAP_STATE_CONFIG:
2216f8fbdce0SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2217ae280e73Smatthias.ringwald             switch (code) {
2218ae280e73Smatthias.ringwald                 case CONFIGURE_REQUEST:
221928ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
2220ae280e73Smatthias.ringwald                     l2cap_signaling_handle_configure_request(channel, command);
222163a7246aSmatthias.ringwald                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
222263a7246aSmatthias.ringwald                         // only done if continuation not set
222363a7246aSmatthias.ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
222463a7246aSmatthias.ringwald                     }
2225ae280e73Smatthias.ringwald                     break;
22261e6aba47Smatthias.ringwald                 case CONFIGURE_RESPONSE:
22275932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2228f2fa388dSMatthias Ringwald                     l2cap_signaling_handle_configure_response(channel, result, command);
22295932bd7cS[email protected]                     switch (result){
22305932bd7cS[email protected]                         case 0: // success
22315932bd7cS[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
22325932bd7cS[email protected]                             break;
22335932bd7cS[email protected]                         case 4: // pending
22345932bd7cS[email protected]                             l2cap_start_ertx(channel);
22355932bd7cS[email protected]                             break;
22365932bd7cS[email protected]                         default:
2237a32d6a03SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2238a32d6a03SMatthias Ringwald                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
2239a32d6a03SMatthias Ringwald                                 // remote does not offer ertm but it's required
2240a32d6a03SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2241a32d6a03SMatthias Ringwald                                 break;
2242a32d6a03SMatthias Ringwald                             }
2243a32d6a03SMatthias Ringwald #endif
2244fe9d8984S[email protected]                             // retry on negative result
2245fe9d8984S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2246fe9d8984S[email protected]                             break;
2247fe9d8984S[email protected]                     }
22485a67bd4aSmatthias.ringwald                     break;
22495a67bd4aSmatthias.ringwald                 default:
22505a67bd4aSmatthias.ringwald                     break;
22511e6aba47Smatthias.ringwald             }
2252fa8473a4Smatthias.ringwald             if (l2cap_channel_ready_for_open(channel)){
2253fa8473a4Smatthias.ringwald                 // for open:
22545a67bd4aSmatthias.ringwald                 channel->state = L2CAP_STATE_OPEN;
2255fa8473a4Smatthias.ringwald                 l2cap_emit_channel_opened(channel, 0);
2256c8e4258aSmatthias.ringwald             }
2257c8e4258aSmatthias.ringwald             break;
2258f62db1e3Smatthias.ringwald 
2259f62db1e3Smatthias.ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
2260f62db1e3Smatthias.ringwald             switch (code) {
2261f62db1e3Smatthias.ringwald                 case DISCONNECTION_RESPONSE:
226227a923d0Smatthias.ringwald                     l2cap_finialize_channel_close(channel);
226327a923d0Smatthias.ringwald                     break;
22645a67bd4aSmatthias.ringwald                 default:
22655a67bd4aSmatthias.ringwald                     //@TODO: implement other signaling packets
22665a67bd4aSmatthias.ringwald                     break;
226727a923d0Smatthias.ringwald             }
226827a923d0Smatthias.ringwald             break;
226984836b65Smatthias.ringwald 
227084836b65Smatthias.ringwald         case L2CAP_STATE_CLOSED:
227184836b65Smatthias.ringwald             // @TODO handle incoming requests
227284836b65Smatthias.ringwald             break;
227384836b65Smatthias.ringwald 
227484836b65Smatthias.ringwald         case L2CAP_STATE_OPEN:
227584836b65Smatthias.ringwald             //@TODO: implement other signaling packets, e.g. re-configure
227684836b65Smatthias.ringwald             break;
227710642e45Smatthias.ringwald         default:
227810642e45Smatthias.ringwald             break;
227927a923d0Smatthias.ringwald     }
22809da54300S[email protected]     // log_info("new state %u", channel->state);
228127a923d0Smatthias.ringwald }
228227a923d0Smatthias.ringwald 
228300d93d79Smatthias.ringwald 
22847f02f414SMatthias Ringwald static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
228500d93d79Smatthias.ringwald 
22861b9cb13dSMatthias Ringwald     btstack_linked_list_iterator_t it;
22871b9cb13dSMatthias Ringwald 
228800d93d79Smatthias.ringwald     // get code, signalind identifier and command len
228900d93d79Smatthias.ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
229000d93d79Smatthias.ringwald     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
229100d93d79Smatthias.ringwald 
22921b9cb13dSMatthias Ringwald     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
22931b9cb13dSMatthias Ringwald     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_RESPONSE){
2294e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
229500d93d79Smatthias.ringwald         return;
229600d93d79Smatthias.ringwald     }
229700d93d79Smatthias.ringwald 
229800d93d79Smatthias.ringwald     // general commands without an assigned channel
229900d93d79Smatthias.ringwald     switch(code) {
230000d93d79Smatthias.ringwald 
230100d93d79Smatthias.ringwald         case CONNECTION_REQUEST: {
2302f8fbdce0SMatthias Ringwald             uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2303f8fbdce0SMatthias Ringwald             uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
230400d93d79Smatthias.ringwald             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
23052b83fb7dSmatthias.ringwald             return;
230600d93d79Smatthias.ringwald         }
230700d93d79Smatthias.ringwald 
23082b360848Smatthias.ringwald         case ECHO_REQUEST:
2309e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
23102b83fb7dSmatthias.ringwald             return;
231100d93d79Smatthias.ringwald 
231200d93d79Smatthias.ringwald         case INFORMATION_REQUEST: {
2313f8fbdce0SMatthias Ringwald             uint16_t infoType = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2314e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, infoType);
23152b83fb7dSmatthias.ringwald             return;
231600d93d79Smatthias.ringwald         }
231700d93d79Smatthias.ringwald 
23181b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
23191b9cb13dSMatthias Ringwald         case INFORMATION_RESPONSE: {
23201b9cb13dSMatthias Ringwald             hci_connection_t * connection = hci_connection_for_handle(handle);
23211b9cb13dSMatthias Ringwald             if (!connection) return;
23221b9cb13dSMatthias Ringwald             uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
23231b9cb13dSMatthias Ringwald             uint16_t result =  little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
23241b9cb13dSMatthias Ringwald             if (result != 0) return;
2325543b84e4SMatthias Ringwald             if (info_type != 0x02) return;
23261b9cb13dSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
23271b9cb13dSMatthias Ringwald             connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2328543b84e4SMatthias Ringwald             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
23291b9cb13dSMatthias Ringwald             // trigger connection request
23301b9cb13dSMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
23311b9cb13dSMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
23321b9cb13dSMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2333543b84e4SMatthias Ringwald                 if (channel->con_handle != handle) continue;
2334543b84e4SMatthias Ringwald                 // bail if ERTM was requested but is not supported
2335543b84e4SMatthias Ringwald                 if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2336f073f086SMatthias Ringwald                     if (channel->ertm_mandatory){
2337543b84e4SMatthias Ringwald                         // channel closed
2338543b84e4SMatthias Ringwald                         channel->state = L2CAP_STATE_CLOSED;
2339543b84e4SMatthias Ringwald                         // map l2cap connection response result to BTstack status enumeration
2340543b84e4SMatthias Ringwald                         l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTD);
2341543b84e4SMatthias Ringwald                         // discard channel
2342543b84e4SMatthias Ringwald                         btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2343543b84e4SMatthias Ringwald                         btstack_memory_l2cap_channel_free(channel);
2344543b84e4SMatthias Ringwald                         continue;
2345f073f086SMatthias Ringwald                     } else {
2346f073f086SMatthias Ringwald                         // fallback to Basic mode
2347f073f086SMatthias Ringwald                         channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2348f073f086SMatthias Ringwald                     }
2349543b84e4SMatthias Ringwald                 }
2350543b84e4SMatthias Ringwald                 // start connecting
23511b9cb13dSMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
23521b9cb13dSMatthias Ringwald                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
23531b9cb13dSMatthias Ringwald                 }
235452606043SMatthias Ringwald                 // respond to connection request
235552606043SMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
235652606043SMatthias Ringwald                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
235752606043SMatthias Ringwald                     l2cap_emit_incoming_connection(channel);
235852606043SMatthias Ringwald                 }
23591b9cb13dSMatthias Ringwald             }
23601b9cb13dSMatthias Ringwald             return;
23611b9cb13dSMatthias Ringwald         }
23621b9cb13dSMatthias Ringwald #endif
23631b9cb13dSMatthias Ringwald 
236400d93d79Smatthias.ringwald         default:
236500d93d79Smatthias.ringwald             break;
236600d93d79Smatthias.ringwald     }
236700d93d79Smatthias.ringwald 
236800d93d79Smatthias.ringwald 
236900d93d79Smatthias.ringwald     // Get potential destination CID
2370f8fbdce0SMatthias Ringwald     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
237100d93d79Smatthias.ringwald 
237200d93d79Smatthias.ringwald     // Find channel for this sig_id and connection handle
2373665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2374665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2375665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2376fc64f94aSMatthias Ringwald         if (channel->con_handle != handle) continue;
237700d93d79Smatthias.ringwald         if (code & 1) {
2378b1988dceSmatthias.ringwald             // match odd commands (responses) by previous signaling identifier
2379b1988dceSmatthias.ringwald             if (channel->local_sig_id == sig_id) {
238000d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
23814e32727eSmatthias.ringwald                 break;
238200d93d79Smatthias.ringwald             }
238300d93d79Smatthias.ringwald         } else {
2384b1988dceSmatthias.ringwald             // match even commands (requests) by local channel id
238500d93d79Smatthias.ringwald             if (channel->local_cid == dest_cid) {
238600d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
23874e32727eSmatthias.ringwald                 break;
238800d93d79Smatthias.ringwald             }
238900d93d79Smatthias.ringwald         }
239000d93d79Smatthias.ringwald     }
239100d93d79Smatthias.ringwald }
239209e9d05bSMatthias Ringwald #endif
239300d93d79Smatthias.ringwald 
2394e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
239509e9d05bSMatthias Ringwald 
239609e9d05bSMatthias Ringwald static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
239709e9d05bSMatthias Ringwald     uint8_t event[6];
239809e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
239909e9d05bSMatthias Ringwald     event[1] = 4;
240009e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
240109e9d05bSMatthias Ringwald     little_endian_store_16(event, 4, result);
240209e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
240309e9d05bSMatthias Ringwald     if (!l2cap_event_packet_handler) return;
240409e9d05bSMatthias Ringwald     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
240509e9d05bSMatthias Ringwald }
240609e9d05bSMatthias Ringwald 
2407c48b2a2cSMatthias Ringwald // @returns valid
2408c48b2a2cSMatthias Ringwald static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
2409e7d0c9aaSMatthias Ringwald     hci_connection_t * connection;
2410c48b2a2cSMatthias Ringwald     uint16_t result;
2411c48b2a2cSMatthias Ringwald     uint8_t  event[10];
241283fd9c76SMatthias Ringwald 
2413cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2414a3dc965aSMatthias Ringwald     btstack_linked_list_iterator_t it;
2415a3dc965aSMatthias Ringwald     l2cap_channel_t * channel;
2416a3dc965aSMatthias Ringwald     uint16_t local_cid;
241783fd9c76SMatthias Ringwald     uint16_t le_psm;
241863f0ac45SMatthias Ringwald     uint16_t new_credits;
241963f0ac45SMatthias Ringwald     uint16_t credits_before;
2420e7d0c9aaSMatthias Ringwald     l2cap_service_t * service;
242111cae19eSMilanka Ringwald     uint16_t source_cid;
242283fd9c76SMatthias Ringwald #endif
242300d93d79Smatthias.ringwald 
24241b8b8d05SMatthias Ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
242523017473SMatthias Ringwald     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u", code, sig_id);
24261b8b8d05SMatthias Ringwald 
24271b8b8d05SMatthias Ringwald     switch (code){
242800d93d79Smatthias.ringwald 
2429c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
2430c48b2a2cSMatthias Ringwald             result = little_endian_read_16(command, 4);
2431ccf076adS[email protected]             l2cap_emit_connection_parameter_update_response(handle, result);
2432ccf076adS[email protected]             break;
2433da886c03S[email protected] 
2434c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_REQUEST:
2435e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
2436da886c03S[email protected]             if (connection){
24376d91fb6cSMatthias Ringwald                 if (connection->role != HCI_ROLE_MASTER){
24386d91fb6cSMatthias Ringwald                     // reject command without notifying upper layer when not in master role
2439c48b2a2cSMatthias Ringwald                     return 0;
24406d91fb6cSMatthias Ringwald                 }
2441da886c03S[email protected]                 int update_parameter = 1;
2442a4c06b28SMatthias Ringwald                 le_connection_parameter_range_t existing_range;
24434ced4e8cSMatthias Ringwald                 gap_get_connection_parameter_range(&existing_range);
2444c48b2a2cSMatthias Ringwald                 uint16_t le_conn_interval_min = little_endian_read_16(command,8);
2445c48b2a2cSMatthias Ringwald                 uint16_t le_conn_interval_max = little_endian_read_16(command,10);
2446c48b2a2cSMatthias Ringwald                 uint16_t le_conn_latency = little_endian_read_16(command,12);
2447c48b2a2cSMatthias Ringwald                 uint16_t le_supervision_timeout = little_endian_read_16(command,14);
2448da886c03S[email protected] 
2449da886c03S[email protected]                 if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
2450da886c03S[email protected]                 if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
2451da886c03S[email protected] 
2452da886c03S[email protected]                 if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
2453da886c03S[email protected]                 if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
2454da886c03S[email protected] 
2455da886c03S[email protected]                 if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
2456da886c03S[email protected]                 if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
2457da886c03S[email protected] 
2458da886c03S[email protected]                 if (update_parameter){
2459da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
2460da886c03S[email protected]                     connection->le_conn_interval_min = le_conn_interval_min;
2461da886c03S[email protected]                     connection->le_conn_interval_max = le_conn_interval_max;
2462da886c03S[email protected]                     connection->le_conn_latency = le_conn_latency;
2463da886c03S[email protected]                     connection->le_supervision_timeout = le_supervision_timeout;
2464da886c03S[email protected]                 } else {
2465da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
2466da886c03S[email protected]                 }
2467c48b2a2cSMatthias Ringwald                 connection->le_con_param_update_identifier = sig_id;
2468da886c03S[email protected]             }
2469da886c03S[email protected] 
247033c40538SMatthias Ringwald             if (!l2cap_event_packet_handler) break;
2471c48b2a2cSMatthias Ringwald 
2472c48b2a2cSMatthias Ringwald             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
2473c48b2a2cSMatthias Ringwald             event[1] = 8;
2474c48b2a2cSMatthias Ringwald             memcpy(&event[2], &command[4], 8);
2475c48b2a2cSMatthias Ringwald             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
247633c40538SMatthias Ringwald             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
2477ccf076adS[email protected]             break;
2478c48b2a2cSMatthias Ringwald 
2479a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2480a3dc965aSMatthias Ringwald 
248163f0ac45SMatthias Ringwald         case COMMAND_REJECT:
248263f0ac45SMatthias Ringwald             // Find channel for this sig_id and connection handle
248363f0ac45SMatthias Ringwald             channel = NULL;
248463f0ac45SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
248563f0ac45SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
248663f0ac45SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
248763f0ac45SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
248863f0ac45SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
248963f0ac45SMatthias Ringwald                 channel = a_channel;
249063f0ac45SMatthias Ringwald                 break;
249163f0ac45SMatthias Ringwald             }
249263f0ac45SMatthias Ringwald             if (!channel) break;
249363f0ac45SMatthias Ringwald 
249463f0ac45SMatthias Ringwald             // if received while waiting for le connection response, assume legacy device
249563f0ac45SMatthias Ringwald             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
249663f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
249763f0ac45SMatthias Ringwald                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
249844276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0x0002);
249963f0ac45SMatthias Ringwald 
250063f0ac45SMatthias Ringwald                 // discard channel
250163f0ac45SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
250263f0ac45SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
250363f0ac45SMatthias Ringwald                 break;
250463f0ac45SMatthias Ringwald             }
250563f0ac45SMatthias Ringwald             break;
250663f0ac45SMatthias Ringwald 
2507e7d0c9aaSMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_REQUEST:
2508e7d0c9aaSMatthias Ringwald 
2509e7d0c9aaSMatthias Ringwald             // get hci connection, bail if not found (must not happen)
2510e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
2511e7d0c9aaSMatthias Ringwald             if (!connection) return 0;
2512e7d0c9aaSMatthias Ringwald 
2513e7d0c9aaSMatthias Ringwald             // check if service registered
2514e7d0c9aaSMatthias Ringwald             le_psm  = little_endian_read_16(command, 4);
2515e7d0c9aaSMatthias Ringwald             service = l2cap_le_get_service(le_psm);
251611cae19eSMilanka Ringwald             source_cid = little_endian_read_16(command, 6);
2517e7d0c9aaSMatthias Ringwald 
2518e7d0c9aaSMatthias Ringwald             if (service){
2519e7d0c9aaSMatthias Ringwald                 if (source_cid < 0x40){
2520e7d0c9aaSMatthias Ringwald                     // 0x0009 Connection refused - Invalid Source CID
2521e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
2522e7d0c9aaSMatthias Ringwald                     return 1;
2523e7d0c9aaSMatthias Ringwald                 }
2524e7d0c9aaSMatthias Ringwald 
2525e7d0c9aaSMatthias Ringwald                 // go through list of channels for this ACL connection and check if we get a match
2526e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2527e7d0c9aaSMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&it)){
25281b8b8d05SMatthias Ringwald                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
25291b8b8d05SMatthias Ringwald                     if (a_channel->con_handle != handle) continue;
25301b8b8d05SMatthias Ringwald                     if (a_channel->remote_cid != source_cid) continue;
2531e7d0c9aaSMatthias Ringwald                     // 0x000a Connection refused - Source CID already allocated
2532e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
2533e7d0c9aaSMatthias Ringwald                     return 1;
2534e7d0c9aaSMatthias Ringwald                 }
2535e7d0c9aaSMatthias Ringwald 
253683fd9c76SMatthias Ringwald                 // security: check encryption
253783fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_2){
253883fd9c76SMatthias Ringwald                     if (sm_encryption_key_size(handle) == 0){
253983fd9c76SMatthias Ringwald                         // 0x0008 Connection refused - insufficient encryption
2540e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
254183fd9c76SMatthias Ringwald                         return 1;
254283fd9c76SMatthias Ringwald                     }
254383fd9c76SMatthias Ringwald                     // anything less than 16 byte key size is insufficient
254483fd9c76SMatthias Ringwald                     if (sm_encryption_key_size(handle) < 16){
254583fd9c76SMatthias Ringwald                         // 0x0007 Connection refused – insufficient encryption key size
2546e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
254783fd9c76SMatthias Ringwald                         return 1;
254883fd9c76SMatthias Ringwald                     }
254983fd9c76SMatthias Ringwald                 }
255083fd9c76SMatthias Ringwald 
255183fd9c76SMatthias Ringwald                 // security: check authencation
255283fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_3){
255383fd9c76SMatthias Ringwald                     if (!sm_authenticated(handle)){
255483fd9c76SMatthias Ringwald                         // 0x0005 Connection refused – insufficient authentication
2555e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
255683fd9c76SMatthias Ringwald                         return 1;
255783fd9c76SMatthias Ringwald                     }
255883fd9c76SMatthias Ringwald                 }
255983fd9c76SMatthias Ringwald 
256083fd9c76SMatthias Ringwald                 // security: check authorization
256183fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_4){
256283fd9c76SMatthias Ringwald                     if (sm_authorization_state(handle) != AUTHORIZATION_GRANTED){
256383fd9c76SMatthias Ringwald                         // 0x0006 Connection refused – insufficient authorization
2564e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
256583fd9c76SMatthias Ringwald                         return 1;
256683fd9c76SMatthias Ringwald                     }
256783fd9c76SMatthias Ringwald                 }
2568e7d0c9aaSMatthias Ringwald 
2569e7d0c9aaSMatthias Ringwald                 // allocate channel
25701b8b8d05SMatthias Ringwald                 channel = l2cap_create_channel_entry(service->packet_handler, connection->address,
2571e7d0c9aaSMatthias Ringwald                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
2572e7d0c9aaSMatthias Ringwald                 if (!channel){
2573e7d0c9aaSMatthias Ringwald                     // 0x0004 Connection refused – no resources available
2574e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2575e7d0c9aaSMatthias Ringwald                     return 1;
2576e7d0c9aaSMatthias Ringwald                 }
2577e7d0c9aaSMatthias Ringwald 
2578e7d0c9aaSMatthias Ringwald                 channel->con_handle = handle;
2579e7d0c9aaSMatthias Ringwald                 channel->remote_cid = source_cid;
2580e7d0c9aaSMatthias Ringwald                 channel->remote_sig_id = sig_id;
25817f107edaSMatthias Ringwald                 channel->remote_mtu = little_endian_read_16(command, 8);
25827f107edaSMatthias Ringwald                 channel->remote_mps = little_endian_read_16(command, 10);
25837f107edaSMatthias Ringwald                 channel->credits_outgoing = little_endian_read_16(command, 12);
2584e7d0c9aaSMatthias Ringwald 
2585e7d0c9aaSMatthias Ringwald                 // set initial state
2586e7d0c9aaSMatthias Ringwald                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2587c99bb618SMatthias Ringwald                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
2588e7d0c9aaSMatthias Ringwald 
2589e7d0c9aaSMatthias Ringwald                 // add to connections list
2590e7d0c9aaSMatthias Ringwald                 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2591e7d0c9aaSMatthias Ringwald 
2592e7d0c9aaSMatthias Ringwald                 // post connection request event
259344276248SMatthias Ringwald                 l2cap_emit_le_incoming_connection(channel);
2594e7d0c9aaSMatthias Ringwald 
2595e7d0c9aaSMatthias Ringwald             } else {
2596e7d0c9aaSMatthias Ringwald                 // Connection refused – LE_PSM not supported
2597e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2598e7d0c9aaSMatthias Ringwald             }
2599e7d0c9aaSMatthias Ringwald             break;
26001b8b8d05SMatthias Ringwald 
26011b8b8d05SMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
26021b8b8d05SMatthias Ringwald             // Find channel for this sig_id and connection handle
26031b8b8d05SMatthias Ringwald             channel = NULL;
26041b8b8d05SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
26051b8b8d05SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
26061b8b8d05SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
26071b8b8d05SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
26081b8b8d05SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
26091b8b8d05SMatthias Ringwald                 channel = a_channel;
26101b8b8d05SMatthias Ringwald                 break;
26111b8b8d05SMatthias Ringwald             }
26121b8b8d05SMatthias Ringwald             if (!channel) break;
26131b8b8d05SMatthias Ringwald 
26141b8b8d05SMatthias Ringwald             // cid + 0
26151b8b8d05SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
26161b8b8d05SMatthias Ringwald             if (result){
26171b8b8d05SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
26181b8b8d05SMatthias Ringwald                 // map l2cap connection response result to BTstack status enumeration
261944276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, result);
26201b8b8d05SMatthias Ringwald 
26211b8b8d05SMatthias Ringwald                 // discard channel
262263f0ac45SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
26231b8b8d05SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
26241b8b8d05SMatthias Ringwald                 break;
26251b8b8d05SMatthias Ringwald             }
26261b8b8d05SMatthias Ringwald 
26271b8b8d05SMatthias Ringwald             // success
26281b8b8d05SMatthias Ringwald             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
26291b8b8d05SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
26301b8b8d05SMatthias Ringwald             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
26311b8b8d05SMatthias Ringwald             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
26321b8b8d05SMatthias Ringwald             channel->state = L2CAP_STATE_OPEN;
263344276248SMatthias Ringwald             l2cap_emit_le_channel_opened(channel, result);
26341b8b8d05SMatthias Ringwald             break;
26351b8b8d05SMatthias Ringwald 
263685aeef60SMatthias Ringwald         case LE_FLOW_CONTROL_CREDIT:
263785aeef60SMatthias Ringwald             // find channel
263885aeef60SMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
263985aeef60SMatthias Ringwald             channel = l2cap_le_get_channel_for_local_cid(local_cid);
264063f0ac45SMatthias Ringwald             if (!channel) {
264163f0ac45SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
264263f0ac45SMatthias Ringwald                 break;
264363f0ac45SMatthias Ringwald             }
264463f0ac45SMatthias Ringwald             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
264563f0ac45SMatthias Ringwald             credits_before = channel->credits_outgoing;
264663f0ac45SMatthias Ringwald             channel->credits_outgoing += new_credits;
264763f0ac45SMatthias Ringwald             // check for credit overrun
264863f0ac45SMatthias Ringwald             if (credits_before > channel->credits_outgoing){
264963f0ac45SMatthias Ringwald                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
265063f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
265163f0ac45SMatthias Ringwald                 break;
265263f0ac45SMatthias Ringwald             }
265363f0ac45SMatthias Ringwald             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
265485aeef60SMatthias Ringwald             break;
265585aeef60SMatthias Ringwald 
2656828a7f7aSMatthias Ringwald         case DISCONNECTION_REQUEST:
2657828a7f7aSMatthias Ringwald             // find channel
2658828a7f7aSMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
2659828a7f7aSMatthias Ringwald             channel = l2cap_le_get_channel_for_local_cid(local_cid);
266063f34e00SMatthias Ringwald             if (!channel) {
266163f34e00SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
266263f34e00SMatthias Ringwald                 break;
266363f34e00SMatthias Ringwald             }
2664828a7f7aSMatthias Ringwald             channel->remote_sig_id = sig_id;
2665828a7f7aSMatthias Ringwald             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
2666828a7f7aSMatthias Ringwald             break;
2667828a7f7aSMatthias Ringwald 
2668a3dc965aSMatthias Ringwald #endif
2669a3dc965aSMatthias Ringwald 
267063f0ac45SMatthias Ringwald         case DISCONNECTION_RESPONSE:
267163f0ac45SMatthias Ringwald             break;
267263f0ac45SMatthias Ringwald 
2673c48b2a2cSMatthias Ringwald         default:
2674c48b2a2cSMatthias Ringwald             // command unknown -> reject command
2675c48b2a2cSMatthias Ringwald             return 0;
2676ccf076adS[email protected]     }
2677c48b2a2cSMatthias Ringwald     return 1;
2678c48b2a2cSMatthias Ringwald }
2679e7d0c9aaSMatthias Ringwald #endif
2680c48b2a2cSMatthias Ringwald 
2681d48432d4SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
268270734707SMatthias Ringwald 
268370734707SMatthias Ringwald // @param delta number of frames in the future, >= 1
268470734707SMatthias Ringwald static void l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel_t * l2cap_channel, l2cap_segmentation_and_reassembly_t sar, int delta, uint8_t * payload, uint16_t size){
268570734707SMatthias Ringwald     log_info("Store SDU with delta %u", delta);
268670734707SMatthias Ringwald     // get rx state for packet to store
268770734707SMatthias Ringwald     int index = l2cap_channel->rx_store_index + delta - 1;
268870734707SMatthias Ringwald     if (index > l2cap_channel->num_rx_buffers){
268970734707SMatthias Ringwald         index -= l2cap_channel->num_rx_buffers;
269070734707SMatthias Ringwald     }
269170734707SMatthias Ringwald     log_info("Index of packet to store %u", index);
269270734707SMatthias Ringwald     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
269370734707SMatthias Ringwald     // check if buffer is free
269470734707SMatthias Ringwald     if (rx_state->valid){
269570734707SMatthias Ringwald         log_error("Packet buffer already used");
269670734707SMatthias Ringwald         return;
269770734707SMatthias Ringwald     }
269870734707SMatthias Ringwald     rx_state->valid = 1;
269970734707SMatthias Ringwald     rx_state->sar = sar;
270070734707SMatthias Ringwald     rx_state->len = size;
270170734707SMatthias Ringwald     uint8_t * rx_buffer = &l2cap_channel->rx_packets_data[index];
270270734707SMatthias Ringwald     memcpy(rx_buffer, payload, size);
270370734707SMatthias Ringwald }
270470734707SMatthias Ringwald 
2705e32be409SMatthias Ringwald static void l2cap_ertm_handle_in_sequence_sdu(l2cap_channel_t * l2cap_channel, l2cap_segmentation_and_reassembly_t sar, uint8_t * payload, uint16_t size){
2706d48432d4SMatthias Ringwald     switch (sar){
2707d48432d4SMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
2708e32be409SMatthias Ringwald             // packet complete -> disapatch
2709e32be409SMatthias Ringwald             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, payload, size);
2710d48432d4SMatthias Ringwald             break;
2711d48432d4SMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
2712d48432d4SMatthias Ringwald             // TODO: check if reassembly started
2713e8e9809fSMatthias Ringwald             // TODO: check sdu_len against local mtu
2714e32be409SMatthias Ringwald             l2cap_channel->reassembly_sdu_length = little_endian_read_16(payload, 0);
2715e32be409SMatthias Ringwald             payload += 2;
2716e32be409SMatthias Ringwald             size    -= 2;
2717e32be409SMatthias Ringwald             memcpy(&l2cap_channel->reassembly_buffer[0], payload, size);
2718e32be409SMatthias Ringwald             l2cap_channel->reassembly_pos = size;
2719d48432d4SMatthias Ringwald             break;
2720d48432d4SMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
2721e32be409SMatthias Ringwald             memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos], payload, size);
2722e32be409SMatthias Ringwald             l2cap_channel->reassembly_pos += size;
2723e32be409SMatthias Ringwald             break;
2724e32be409SMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
2725e32be409SMatthias Ringwald             memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos], payload, size);
2726e32be409SMatthias Ringwald             l2cap_channel->reassembly_pos += size;
2727e32be409SMatthias Ringwald             // packet complete -> disapatch
2728e32be409SMatthias Ringwald             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->reassembly_buffer, l2cap_channel->reassembly_pos);
2729e32be409SMatthias Ringwald             l2cap_channel->reassembly_pos = 0;
2730d48432d4SMatthias Ringwald             break;
2731d48432d4SMatthias Ringwald     }
2732d48432d4SMatthias Ringwald }
2733d48432d4SMatthias Ringwald #endif
2734d48432d4SMatthias Ringwald 
2735c48b2a2cSMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size ){
27369ec2630cSMatthias Ringwald     UNUSED(packet_type);
27379ec2630cSMatthias Ringwald     UNUSED(channel);
2738c48b2a2cSMatthias Ringwald 
273909e9d05bSMatthias Ringwald     l2cap_channel_t * l2cap_channel;
2740f3963406SMatthias Ringwald     UNUSED(l2cap_channel);
274109e9d05bSMatthias Ringwald 
2742c48b2a2cSMatthias Ringwald     // Get Channel ID
2743c48b2a2cSMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
2744c48b2a2cSMatthias Ringwald     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
2745c48b2a2cSMatthias Ringwald 
2746c48b2a2cSMatthias Ringwald     switch (channel_id) {
2747c48b2a2cSMatthias Ringwald 
274809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2749c48b2a2cSMatthias Ringwald         case L2CAP_CID_SIGNALING: {
2750c48b2a2cSMatthias Ringwald             uint16_t command_offset = 8;
2751c48b2a2cSMatthias Ringwald             while (command_offset < size) {
2752c48b2a2cSMatthias Ringwald                 // handle signaling commands
2753c48b2a2cSMatthias Ringwald                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
2754c48b2a2cSMatthias Ringwald 
2755c48b2a2cSMatthias Ringwald                 // increment command_offset
2756c48b2a2cSMatthias Ringwald                 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2757c48b2a2cSMatthias Ringwald             }
2758c48b2a2cSMatthias Ringwald             break;
2759c48b2a2cSMatthias Ringwald         }
276009e9d05bSMatthias Ringwald #endif
2761c48b2a2cSMatthias Ringwald 
2762e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
2763e7d0c9aaSMatthias Ringwald         case L2CAP_CID_SIGNALING_LE: {
2764e7d0c9aaSMatthias Ringwald             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
2765e7d0c9aaSMatthias Ringwald             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
2766c48b2a2cSMatthias Ringwald             if (!valid){
2767e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2768ccf076adS[email protected]             }
2769ccf076adS[email protected]             break;
2770e7d0c9aaSMatthias Ringwald         }
2771e7d0c9aaSMatthias Ringwald #endif
2772c48b2a2cSMatthias Ringwald 
2773c48b2a2cSMatthias Ringwald         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
2774c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback) {
2775c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2776ccf076adS[email protected]             }
2777c48b2a2cSMatthias Ringwald             break;
2778c48b2a2cSMatthias Ringwald 
2779c48b2a2cSMatthias Ringwald         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
2780c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback) {
2781c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2782c48b2a2cSMatthias Ringwald             }
2783c48b2a2cSMatthias Ringwald             break;
2784c48b2a2cSMatthias Ringwald 
2785c48b2a2cSMatthias Ringwald         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
2786c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback) {
2787c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2788c48b2a2cSMatthias Ringwald             }
2789c48b2a2cSMatthias Ringwald             break;
27901bbc0b23S[email protected] 
279109e9d05bSMatthias Ringwald         default:
279209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
279300d93d79Smatthias.ringwald             // Find channel for this channel_id and connection handle
279464e11ca9SMatthias Ringwald             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
2795d1fd2a88SMatthias Ringwald             if (l2cap_channel) {
279627e0774aSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
279727e0774aSMatthias Ringwald                 if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
279827e0774aSMatthias Ringwald 
279927e0774aSMatthias Ringwald                     // verify FCS
280027e0774aSMatthias Ringwald                     uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
280127e0774aSMatthias Ringwald                     uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
280227e0774aSMatthias Ringwald                     log_info("Packet FCS 0x%04x, calculated FCS 0x%04x", fcs_packet, fcs_calculated);
280327e0774aSMatthias Ringwald                     if (fcs_calculated != fcs_packet){
280427e0774aSMatthias Ringwald                         log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
280527e0774aSMatthias Ringwald                         // TODO: trigger retransmission or something like that
280627e0774aSMatthias Ringwald                         break;
280727e0774aSMatthias Ringwald                     }
280827e0774aSMatthias Ringwald 
280927e0774aSMatthias Ringwald                     // switch on packet type
281027e0774aSMatthias Ringwald                     uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
281138f62777SMatthias Ringwald                     uint8_t  req_seq = (control >> 8) & 0x3f;
28122bea1b8dSMatthias Ringwald                     int final = (control >> 7) & 0x01;
281327e0774aSMatthias Ringwald                     if (control & 1){
281427e0774aSMatthias Ringwald                         // S-Frame
281578cd8a22SMatthias Ringwald                         int poll  = (control >> 4) & 0x01;
2816bdbe2e49SMatthias Ringwald                         l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
28179ffcbce4SMatthias Ringwald                         log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
28187b7901d8SMatthias Ringwald                         l2cap_ertm_tx_packet_state_t * tx_state;
2819bdbe2e49SMatthias Ringwald                         switch (s){
2820bdbe2e49SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
28219ffcbce4SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
28222a424812SMatthias Ringwald                                 l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
28233233d8abSMatthias Ringwald                                 if (poll && final){
28243233d8abSMatthias Ringwald                                     // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
28253233d8abSMatthias Ringwald                                     log_error("P=F=1 in S-Frame");
28263233d8abSMatthias Ringwald                                     break;
28273233d8abSMatthias Ringwald                                 }
282878cd8a22SMatthias Ringwald                                 if (poll){
2829f85ade6bSMatthias Ringwald                                     // check if we did request selective retransmission before <==> we have stored SDU segments
2830f85ade6bSMatthias Ringwald                                     int i;
2831f85ade6bSMatthias Ringwald                                     int num_stored_out_of_order_packets = 0;
2832f85ade6bSMatthias Ringwald                                     for (i=0;i<l2cap_channel->num_rx_buffers;i++){
2833f85ade6bSMatthias Ringwald                                         int index = l2cap_channel->rx_store_index + i;
2834f85ade6bSMatthias Ringwald                                         if (index >= l2cap_channel->num_rx_buffers){
2835f85ade6bSMatthias Ringwald                                             index -= l2cap_channel->num_rx_buffers;
2836f85ade6bSMatthias Ringwald                                         }
2837f85ade6bSMatthias Ringwald                                         l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
2838f85ade6bSMatthias Ringwald                                         if (!rx_state->valid) continue;
2839f85ade6bSMatthias Ringwald                                         num_stored_out_of_order_packets++;
2840f85ade6bSMatthias Ringwald                                     }
2841f85ade6bSMatthias Ringwald                                     if (num_stored_out_of_order_packets){
2842f85ade6bSMatthias Ringwald                                         l2cap_channel->send_supervisor_frame_selective_reject = 1;
2843f85ade6bSMatthias Ringwald                                     } else {
2844d2afdd38SMatthias Ringwald                                         l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
284578cd8a22SMatthias Ringwald                                     }
2846f85ade6bSMatthias Ringwald                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
2847f85ade6bSMatthias Ringwald                                 }
28483233d8abSMatthias Ringwald                                 if (final){
28493233d8abSMatthias Ringwald                                     // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
28503233d8abSMatthias Ringwald                                     l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
28513233d8abSMatthias Ringwald                                 }
2852bdbe2e49SMatthias Ringwald                                 break;
28539ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
28549ffcbce4SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
28559ffcbce4SMatthias Ringwald                                 l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
28569ffcbce4SMatthias Ringwald                                 // rsetart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_handle_req_seq)
28579ffcbce4SMatthias Ringwald                                 l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
28589ffcbce4SMatthias Ringwald                                 break;
28599ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
28609ffcbce4SMatthias Ringwald                                 log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
28619ffcbce4SMatthias Ringwald                                 break;
28629ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
28637b7901d8SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
28647b7901d8SMatthias Ringwald                                 if (poll){
28657b7901d8SMatthias Ringwald                                     l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
28667b7901d8SMatthias Ringwald                                 }
28677b7901d8SMatthias Ringwald                                 // find requested i-frame
28687b7901d8SMatthias Ringwald                                 tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
28697b7901d8SMatthias Ringwald                                 if (tx_state){
28707b7901d8SMatthias Ringwald                                     log_info("Retransmission for tx_seq %u requested", req_seq);
2871d2afdd38SMatthias Ringwald                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
28727b7901d8SMatthias Ringwald                                     tx_state->retransmission_requested = 1;
28737b7901d8SMatthias Ringwald                                     l2cap_channel->srej_active = 1;
28747b7901d8SMatthias Ringwald                                 }
28759ffcbce4SMatthias Ringwald                                 break;
2876bdbe2e49SMatthias Ringwald                             default:
2877bdbe2e49SMatthias Ringwald                                 break;
2878bdbe2e49SMatthias Ringwald                         }
287927e0774aSMatthias Ringwald                         break;
288027e0774aSMatthias Ringwald                     } else {
288127e0774aSMatthias Ringwald                         // I-Frame
288227e0774aSMatthias Ringwald                         // get control
288327e0774aSMatthias Ringwald                         l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
288438f62777SMatthias Ringwald                         uint8_t tx_seq = (control >> 1) & 0x3f;
288538f62777SMatthias Ringwald                         log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
2886e8e9809fSMatthias Ringwald                         log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
288738f62777SMatthias Ringwald                         log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
28882a424812SMatthias Ringwald                         l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
288911b576c5SMatthias Ringwald                         if (final){
289011b576c5SMatthias Ringwald                             // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
289111b576c5SMatthias Ringwald                             l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
289211b576c5SMatthias Ringwald                         }
289338f62777SMatthias Ringwald                         // check ordering
289438f62777SMatthias Ringwald                         if (l2cap_channel->expected_tx_seq == tx_seq){
289538f62777SMatthias Ringwald                             log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
289638f62777SMatthias Ringwald                             l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
2897f85ade6bSMatthias Ringwald                             l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
2898d48432d4SMatthias Ringwald 
2899e32be409SMatthias Ringwald                             // process SDU
2900e32be409SMatthias Ringwald                             l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, &packet[COMPLETE_L2CAP_HEADER+2], size-(COMPLETE_L2CAP_HEADER+2));
2901d48432d4SMatthias Ringwald 
290270734707SMatthias Ringwald                             // process stored segments
290370734707SMatthias Ringwald                             while (1){
290470734707SMatthias Ringwald                                 int index = l2cap_channel->rx_store_index;
290570734707SMatthias Ringwald                                 l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
290670734707SMatthias Ringwald                                 if (!rx_state->valid) break;
2907f85ade6bSMatthias Ringwald 
2908f85ade6bSMatthias Ringwald                                 log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
2909f85ade6bSMatthias Ringwald                                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
2910f85ade6bSMatthias Ringwald                                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
2911f85ade6bSMatthias Ringwald 
291270734707SMatthias Ringwald                                 rx_state->valid = 0;
291370734707SMatthias Ringwald                                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
2914f85ade6bSMatthias Ringwald 
2915f85ade6bSMatthias Ringwald                                 // update rx store index
291670734707SMatthias Ringwald                                 index++;
291770734707SMatthias Ringwald                                 if (index >= l2cap_channel->num_rx_buffers){
291870734707SMatthias Ringwald                                     index = 0;
291970734707SMatthias Ringwald                                 }
292070734707SMatthias Ringwald                                 l2cap_channel->rx_store_index = index;
292170734707SMatthias Ringwald                             }
292270734707SMatthias Ringwald 
2923f85ade6bSMatthias Ringwald                             //
2924f85ade6bSMatthias Ringwald                             l2cap_channel->send_supervisor_frame_receiver_ready = 1;
2925f85ade6bSMatthias Ringwald 
2926c7309e8dSMatthias Ringwald                         } else {
2927df2191a7SMatthias Ringwald                             int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
2928df2191a7SMatthias Ringwald                             if (delta < 2){
292970734707SMatthias Ringwald                                 // store segment
293070734707SMatthias Ringwald                                 l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, &packet[COMPLETE_L2CAP_HEADER+2], size-(COMPLETE_L2CAP_HEADER+2));
293170734707SMatthias Ringwald 
2932df2191a7SMatthias Ringwald                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
2933df2191a7SMatthias Ringwald                                 l2cap_channel->send_supervisor_frame_selective_reject = 1;
2934df2191a7SMatthias Ringwald                             } else {
2935df2191a7SMatthias Ringwald                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
2936c7309e8dSMatthias Ringwald                                 l2cap_channel->send_supervisor_frame_reject = 1;
293727e0774aSMatthias Ringwald                             }
293838f62777SMatthias Ringwald                         }
2939df2191a7SMatthias Ringwald                     }
294027e0774aSMatthias Ringwald                     break;
294127e0774aSMatthias Ringwald                 }
294227e0774aSMatthias Ringwald #endif
29433d50b4baSMatthias Ringwald                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
294400d93d79Smatthias.ringwald             }
294509e9d05bSMatthias Ringwald #endif
2946a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
294764e11ca9SMatthias Ringwald             l2cap_channel = l2cap_le_get_channel_for_local_cid(channel_id);
294864e11ca9SMatthias Ringwald             if (l2cap_channel) {
294985aeef60SMatthias Ringwald                 // credit counting
295085aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming == 0){
295185aeef60SMatthias Ringwald                     log_error("LE Data Channel packet received but no incoming credits");
295285aeef60SMatthias Ringwald                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
295385aeef60SMatthias Ringwald                     break;
295485aeef60SMatthias Ringwald                 }
295585aeef60SMatthias Ringwald                 l2cap_channel->credits_incoming--;
295685aeef60SMatthias Ringwald 
295785aeef60SMatthias Ringwald                 // automatic credits
295885aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){
295985aeef60SMatthias Ringwald                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
296085aeef60SMatthias Ringwald                 }
296185aeef60SMatthias Ringwald 
2962cd529728SMatthias Ringwald                 // first fragment
2963cd529728SMatthias Ringwald                 uint16_t pos = 0;
2964cd529728SMatthias Ringwald                 if (!l2cap_channel->receive_sdu_len){
2965cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
2966cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_pos = 0;
2967cd529728SMatthias Ringwald                     pos  += 2;
2968cd529728SMatthias Ringwald                     size -= 2;
2969cd529728SMatthias Ringwald                 }
2970cd529728SMatthias Ringwald                 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], size-COMPLETE_L2CAP_HEADER);
2971cd529728SMatthias Ringwald                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
2972cd529728SMatthias Ringwald                 // done?
297363f0ac45SMatthias Ringwald                 log_info("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
2974cd529728SMatthias Ringwald                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
2975cd529728SMatthias Ringwald                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
2976cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = 0;
2977cd529728SMatthias Ringwald                 }
297863f0ac45SMatthias Ringwald             } else {
297963f0ac45SMatthias Ringwald                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
298064e11ca9SMatthias Ringwald             }
298164e11ca9SMatthias Ringwald #endif
29825652b5ffS[email protected]             break;
29835652b5ffS[email protected]     }
298400d93d79Smatthias.ringwald 
29851eb2563eS[email protected]     l2cap_run();
29862718e2e7Smatthias.ringwald }
298700d93d79Smatthias.ringwald 
298809e9d05bSMatthias Ringwald // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
298909e9d05bSMatthias Ringwald void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
299009e9d05bSMatthias Ringwald     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
299109e9d05bSMatthias Ringwald     if (index < 0) return;
299209e9d05bSMatthias Ringwald     fixed_channels[index].callback = the_packet_handler;
299309e9d05bSMatthias Ringwald }
299409e9d05bSMatthias Ringwald 
299509e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
299615ec09bbSmatthias.ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
299727a923d0Smatthias.ringwald void l2cap_finialize_channel_close(l2cap_channel_t * channel){
2998f62db1e3Smatthias.ringwald     channel->state = L2CAP_STATE_CLOSED;
2999f62db1e3Smatthias.ringwald     l2cap_emit_channel_closed(channel);
3000f62db1e3Smatthias.ringwald     // discard channel
30019dcb2fb2S[email protected]     l2cap_stop_rtx(channel);
3002665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3003d3a9df87Smatthias.ringwald     btstack_memory_l2cap_channel_free(channel);
3004c8e4258aSmatthias.ringwald }
30051e6aba47Smatthias.ringwald 
30068f2a52f4SMatthias Ringwald static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3007665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
3008665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, services);
3009665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
3010665d90f2SMatthias Ringwald         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
30119d9bbc01Smatthias.ringwald         if ( service->psm == psm){
30129d9bbc01Smatthias.ringwald             return service;
30139d9bbc01Smatthias.ringwald         };
30149d9bbc01Smatthias.ringwald     }
30159d9bbc01Smatthias.ringwald     return NULL;
30169d9bbc01Smatthias.ringwald }
30179d9bbc01Smatthias.ringwald 
30187192e786SMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
30197192e786SMatthias Ringwald     return l2cap_get_service_internal(&l2cap_services, psm);
30207192e786SMatthias Ringwald }
30217192e786SMatthias Ringwald 
3022e0abb8e7S[email protected] 
3023be2053a6SMatthias 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){
3024be2053a6SMatthias Ringwald 
3025be2053a6SMatthias Ringwald     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
3026e0abb8e7S[email protected] 
30274bb582b6Smatthias.ringwald     // check for alread registered psm
30289d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
3029277abc2cSmatthias.ringwald     if (service) {
3030be2053a6SMatthias Ringwald         log_error("l2cap_register_service: PSM %u already registered", psm);
3031be2053a6SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
3032277abc2cSmatthias.ringwald     }
30339d9bbc01Smatthias.ringwald 
30344bb582b6Smatthias.ringwald     // alloc structure
3035bb69aaaeS[email protected]     service = btstack_memory_l2cap_service_get();
3036277abc2cSmatthias.ringwald     if (!service) {
3037be2053a6SMatthias Ringwald         log_error("l2cap_register_service: no memory for l2cap_service_t");
3038be2053a6SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
3039277abc2cSmatthias.ringwald     }
30409d9bbc01Smatthias.ringwald 
30419d9bbc01Smatthias.ringwald     // fill in
30429d9bbc01Smatthias.ringwald     service->psm = psm;
30439d9bbc01Smatthias.ringwald     service->mtu = mtu;
304405ae8de3SMatthias Ringwald     service->packet_handler = service_packet_handler;
3045df3354fcS[email protected]     service->required_security_level = security_level;
30469d9bbc01Smatthias.ringwald 
30479d9bbc01Smatthias.ringwald     // add to services list
3048665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
3049c0e866bfSmatthias.ringwald 
3050c0e866bfSmatthias.ringwald     // enable page scan
305115a95bd5SMatthias Ringwald     gap_connectable_control(1);
30525842b6d9Smatthias.ringwald 
3053be2053a6SMatthias Ringwald     return 0;
30549d9bbc01Smatthias.ringwald }
30559d9bbc01Smatthias.ringwald 
30567e8856ebSMatthias Ringwald uint8_t l2cap_unregister_service(uint16_t psm){
3057e0abb8e7S[email protected] 
3058e0abb8e7S[email protected]     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
3059e0abb8e7S[email protected] 
30609d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
30617e8856ebSMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3062665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
3063d3a9df87Smatthias.ringwald     btstack_memory_l2cap_service_free(service);
3064c0e866bfSmatthias.ringwald 
3065c0e866bfSmatthias.ringwald     // disable page scan when no services registered
30667e8856ebSMatthias Ringwald     if (btstack_linked_list_empty(&l2cap_services)) {
306715a95bd5SMatthias Ringwald         gap_connectable_control(0);
30689d9bbc01Smatthias.ringwald     }
30697e8856ebSMatthias Ringwald     return 0;
30707e8856ebSMatthias Ringwald }
307109e9d05bSMatthias Ringwald #endif
30729d9bbc01Smatthias.ringwald 
30737192e786SMatthias Ringwald 
3074cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
307583fd9c76SMatthias Ringwald 
307657be49d6SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
307757be49d6SMatthias Ringwald     if (!channel->waiting_for_can_send_now) return;
307857be49d6SMatthias Ringwald     if (channel->send_sdu_buffer) return;
307957be49d6SMatthias Ringwald     channel->waiting_for_can_send_now = 0;
308057be49d6SMatthias Ringwald     log_info("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
308157be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
308257be49d6SMatthias Ringwald }
308357be49d6SMatthias Ringwald 
308457be49d6SMatthias Ringwald // 1BH2222
308557be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
308657be49d6SMatthias 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",
308757be49d6SMatthias Ringwald              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
308857be49d6SMatthias Ringwald     uint8_t event[19];
308957be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
309057be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
309157be49d6SMatthias Ringwald     event[2] = channel->address_type;
309257be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
309357be49d6SMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
309457be49d6SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
309557be49d6SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
309657be49d6SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
309757be49d6SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_mtu);
309857be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
309957be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
310057be49d6SMatthias Ringwald }
310157be49d6SMatthias Ringwald // 11BH22222
310257be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
310357be49d6SMatthias 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",
310457be49d6SMatthias Ringwald              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
310557be49d6SMatthias Ringwald              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
3106c99bb618SMatthias Ringwald     uint8_t event[23];
310757be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
310857be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
310957be49d6SMatthias Ringwald     event[2] = status;
311057be49d6SMatthias Ringwald     event[3] = channel->address_type;
311157be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[4]);
311257be49d6SMatthias Ringwald     little_endian_store_16(event, 10, channel->con_handle);
3113c99bb618SMatthias Ringwald     event[12] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
3114c99bb618SMatthias Ringwald     little_endian_store_16(event, 13, channel->psm);
3115c99bb618SMatthias Ringwald     little_endian_store_16(event, 15, channel->local_cid);
3116c99bb618SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_cid);
3117c99bb618SMatthias Ringwald     little_endian_store_16(event, 19, channel->local_mtu);
3118c99bb618SMatthias Ringwald     little_endian_store_16(event, 21, channel->remote_mtu);
311957be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
312057be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
312157be49d6SMatthias Ringwald }
312257be49d6SMatthias Ringwald 
312357be49d6SMatthias Ringwald static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid){
312457be49d6SMatthias Ringwald     btstack_linked_list_iterator_t it;
312557be49d6SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
312657be49d6SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
312757be49d6SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
312857be49d6SMatthias Ringwald         if ( channel->local_cid == local_cid) {
312957be49d6SMatthias Ringwald             return channel;
313057be49d6SMatthias Ringwald         }
313157be49d6SMatthias Ringwald     }
313257be49d6SMatthias Ringwald     return NULL;
313357be49d6SMatthias Ringwald }
313457be49d6SMatthias Ringwald 
313557be49d6SMatthias Ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
313657be49d6SMatthias Ringwald void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
313757be49d6SMatthias Ringwald     channel->state = L2CAP_STATE_CLOSED;
313857be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
313957be49d6SMatthias Ringwald     // discard channel
314057be49d6SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
314157be49d6SMatthias Ringwald     btstack_memory_l2cap_channel_free(channel);
314257be49d6SMatthias Ringwald }
314357be49d6SMatthias Ringwald 
3144e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
3145e7d0c9aaSMatthias Ringwald     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
31467192e786SMatthias Ringwald }
3147efedfb4cSMatthias Ringwald 
3148da144af5SMatthias Ringwald uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
31497192e786SMatthias Ringwald 
3150da144af5SMatthias Ringwald     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
31517192e786SMatthias Ringwald 
31527192e786SMatthias Ringwald     // check for alread registered psm
31537192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
31547192e786SMatthias Ringwald     if (service) {
3155da144af5SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
31567192e786SMatthias Ringwald     }
31577192e786SMatthias Ringwald 
31587192e786SMatthias Ringwald     // alloc structure
31597192e786SMatthias Ringwald     service = btstack_memory_l2cap_service_get();
31607192e786SMatthias Ringwald     if (!service) {
31617192e786SMatthias Ringwald         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
3162da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
31637192e786SMatthias Ringwald     }
31647192e786SMatthias Ringwald 
31657192e786SMatthias Ringwald     // fill in
31667192e786SMatthias Ringwald     service->psm = psm;
3167da144af5SMatthias Ringwald     service->mtu = 0;
31687192e786SMatthias Ringwald     service->packet_handler = packet_handler;
31697192e786SMatthias Ringwald     service->required_security_level = security_level;
31707192e786SMatthias Ringwald 
31717192e786SMatthias Ringwald     // add to services list
3172665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
31737192e786SMatthias Ringwald 
31747192e786SMatthias Ringwald     // done
3175da144af5SMatthias Ringwald     return 0;
31767192e786SMatthias Ringwald }
31777192e786SMatthias Ringwald 
3178da144af5SMatthias Ringwald uint8_t l2cap_le_unregister_service(uint16_t psm) {
31797192e786SMatthias Ringwald     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
31807192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
31819367f9b0SMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3182da144af5SMatthias Ringwald 
3183665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
31847192e786SMatthias Ringwald     btstack_memory_l2cap_service_free(service);
3185da144af5SMatthias Ringwald     return 0;
31867192e786SMatthias Ringwald }
3187da144af5SMatthias Ringwald 
3188da144af5SMatthias Ringwald uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
3189e7d0c9aaSMatthias Ringwald     // get channel
3190e7d0c9aaSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3191e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3192e7d0c9aaSMatthias Ringwald 
3193e7d0c9aaSMatthias Ringwald     // validate state
3194e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3195e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
3196e7d0c9aaSMatthias Ringwald     }
3197e7d0c9aaSMatthias Ringwald 
3198efedfb4cSMatthias Ringwald     // set state accept connection
319923017473SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
320023017473SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
320123017473SMatthias Ringwald     channel->local_mtu = mtu;
320285aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
320385aeef60SMatthias Ringwald     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
320485aeef60SMatthias Ringwald 
320585aeef60SMatthias Ringwald     // test
320663f0ac45SMatthias Ringwald     // channel->new_credits_incoming = 1;
3207e7d0c9aaSMatthias Ringwald 
3208e7d0c9aaSMatthias Ringwald     // go
3209e7d0c9aaSMatthias Ringwald     l2cap_run();
3210da144af5SMatthias Ringwald     return 0;
3211da144af5SMatthias Ringwald }
3212da144af5SMatthias Ringwald 
3213da144af5SMatthias Ringwald /**
3214da144af5SMatthias Ringwald  * @brief Deny incoming LE Data Channel connection due to resource constraints
3215da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3216da144af5SMatthias Ringwald  */
3217da144af5SMatthias Ringwald 
3218da144af5SMatthias Ringwald uint8_t l2cap_le_decline_connection(uint16_t local_cid){
3219e7d0c9aaSMatthias Ringwald     // get channel
3220e7d0c9aaSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3221e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3222e7d0c9aaSMatthias Ringwald 
3223e7d0c9aaSMatthias Ringwald     // validate state
3224e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3225e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
3226e7d0c9aaSMatthias Ringwald     }
3227e7d0c9aaSMatthias Ringwald 
3228efedfb4cSMatthias Ringwald     // set state decline connection
3229e7d0c9aaSMatthias Ringwald     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
3230e7d0c9aaSMatthias Ringwald     channel->reason = 0x04; // no resources available
3231e7d0c9aaSMatthias Ringwald     l2cap_run();
3232da144af5SMatthias Ringwald     return 0;
3233da144af5SMatthias Ringwald }
3234da144af5SMatthias Ringwald 
32357dafa750SMatthias Ringwald uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
3236da144af5SMatthias Ringwald     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
3237efedfb4cSMatthias Ringwald     uint16_t * out_local_cid) {
3238efedfb4cSMatthias Ringwald 
32397dafa750SMatthias Ringwald     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
3240da144af5SMatthias Ringwald 
32417dafa750SMatthias Ringwald 
32427dafa750SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
32437dafa750SMatthias Ringwald     if (!connection) {
32447dafa750SMatthias Ringwald         log_error("no hci_connection for handle 0x%04x", con_handle);
32457dafa750SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
32467dafa750SMatthias Ringwald     }
32477dafa750SMatthias Ringwald 
32487dafa750SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, connection->address, connection->address_type, psm, mtu, security_level);
3249da144af5SMatthias Ringwald     if (!channel) {
3250da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
3251da144af5SMatthias Ringwald     }
3252e7d0c9aaSMatthias Ringwald     log_info("l2cap_le_create_channel %p", channel);
3253da144af5SMatthias Ringwald 
3254da144af5SMatthias Ringwald     // store local_cid
3255da144af5SMatthias Ringwald     if (out_local_cid){
3256da144af5SMatthias Ringwald        *out_local_cid = channel->local_cid;
3257da144af5SMatthias Ringwald     }
3258da144af5SMatthias Ringwald 
32597dafa750SMatthias Ringwald     // provide buffer
32607dafa750SMatthias Ringwald     channel->con_handle = con_handle;
3261cd529728SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
32627dafa750SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
326385aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
326485aeef60SMatthias Ringwald     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
326585aeef60SMatthias Ringwald 
3266efedfb4cSMatthias Ringwald     // add to connections list
3267efedfb4cSMatthias Ringwald     btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
3268efedfb4cSMatthias Ringwald 
32697dafa750SMatthias Ringwald     // go
327063f0ac45SMatthias Ringwald     l2cap_run();
3271da144af5SMatthias Ringwald     return 0;
3272da144af5SMatthias Ringwald }
3273da144af5SMatthias Ringwald 
3274da144af5SMatthias Ringwald /**
3275da144af5SMatthias Ringwald  * @brief Provide credtis for LE Data Channel
3276da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3277da144af5SMatthias Ringwald  * @param credits               Number additional credits for peer
3278da144af5SMatthias Ringwald  */
327964e11ca9SMatthias Ringwald uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
328063f0ac45SMatthias Ringwald 
328163f0ac45SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
328263f0ac45SMatthias Ringwald     if (!channel) {
328363f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
328463f0ac45SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
328563f0ac45SMatthias Ringwald     }
328663f0ac45SMatthias Ringwald 
3287efedfb4cSMatthias Ringwald     // check state
328863f0ac45SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN){
328963f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
329063f0ac45SMatthias Ringwald     }
329163f0ac45SMatthias Ringwald 
329263f0ac45SMatthias Ringwald     // assert incoming credits + credits <= 0xffff
329363f0ac45SMatthias Ringwald     uint32_t total_credits = channel->credits_incoming;
329463f0ac45SMatthias Ringwald     total_credits += channel->new_credits_incoming;
329563f0ac45SMatthias Ringwald     total_credits += credits;
329663f0ac45SMatthias Ringwald     if (total_credits > 0xffff){
329763f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
329863f0ac45SMatthias Ringwald             channel->new_credits_incoming, credits);
329963f0ac45SMatthias Ringwald     }
330063f0ac45SMatthias Ringwald 
3301efedfb4cSMatthias Ringwald     // set credits_granted
330263f0ac45SMatthias Ringwald     channel->new_credits_incoming += credits;
330363f0ac45SMatthias Ringwald 
330463f0ac45SMatthias Ringwald     // go
330563f0ac45SMatthias Ringwald     l2cap_run();
3306da144af5SMatthias Ringwald     return 0;
3307da144af5SMatthias Ringwald }
3308da144af5SMatthias Ringwald 
3309da144af5SMatthias Ringwald /**
3310da144af5SMatthias Ringwald  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
3311da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3312da144af5SMatthias Ringwald  */
331364e11ca9SMatthias Ringwald int l2cap_le_can_send_now(uint16_t local_cid){
331444276248SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
331544276248SMatthias Ringwald     if (!channel) {
331644276248SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
3317da144af5SMatthias Ringwald         return 0;
3318da144af5SMatthias Ringwald     }
3319da144af5SMatthias Ringwald 
332044276248SMatthias Ringwald     // check state
332144276248SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN) return 0;
332244276248SMatthias Ringwald 
332344276248SMatthias Ringwald     // check queue
332444276248SMatthias Ringwald     if (channel->send_sdu_buffer) return 0;
332544276248SMatthias Ringwald 
332644276248SMatthias Ringwald     // fine, go ahead
332744276248SMatthias Ringwald     return 1;
332844276248SMatthias Ringwald }
332944276248SMatthias Ringwald 
3330da144af5SMatthias Ringwald /**
3331da144af5SMatthias Ringwald  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
3332da144af5SMatthias Ringwald  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
3333da144af5SMatthias Ringwald  *       so packet handler should be ready to handle it
3334da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3335da144af5SMatthias Ringwald  */
333664e11ca9SMatthias Ringwald uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
333744276248SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
333844276248SMatthias Ringwald     if (!channel) {
333944276248SMatthias Ringwald         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
334044276248SMatthias Ringwald         return 0;
334144276248SMatthias Ringwald     }
334244276248SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
334344276248SMatthias Ringwald     l2cap_le_notify_channel_can_send(channel);
3344da144af5SMatthias Ringwald     return 0;
3345da144af5SMatthias Ringwald }
3346da144af5SMatthias Ringwald 
3347da144af5SMatthias Ringwald /**
3348da144af5SMatthias Ringwald  * @brief Send data via LE Data Channel
3349da144af5SMatthias Ringwald  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
3350da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3351da144af5SMatthias Ringwald  * @param data                  data to send
3352da144af5SMatthias Ringwald  * @param size                  data size
3353da144af5SMatthias Ringwald  */
335464e11ca9SMatthias Ringwald uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
335564e11ca9SMatthias Ringwald 
335664e11ca9SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
335764e11ca9SMatthias Ringwald     if (!channel) {
335864e11ca9SMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
3359828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
336064e11ca9SMatthias Ringwald     }
336164e11ca9SMatthias Ringwald 
336264e11ca9SMatthias Ringwald     if (len > channel->remote_mtu){
336364e11ca9SMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
336464e11ca9SMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
336564e11ca9SMatthias Ringwald     }
336664e11ca9SMatthias Ringwald 
33677f107edaSMatthias Ringwald     if (channel->send_sdu_buffer){
336864e11ca9SMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
336964e11ca9SMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
337064e11ca9SMatthias Ringwald     }
337164e11ca9SMatthias Ringwald 
33727f107edaSMatthias Ringwald     channel->send_sdu_buffer = data;
33737f107edaSMatthias Ringwald     channel->send_sdu_len    = len;
33747f107edaSMatthias Ringwald     channel->send_sdu_pos    = 0;
337564e11ca9SMatthias Ringwald 
33767f107edaSMatthias Ringwald     l2cap_run();
33777f107edaSMatthias Ringwald     return 0;
3378da144af5SMatthias Ringwald }
3379da144af5SMatthias Ringwald 
3380da144af5SMatthias Ringwald /**
3381da144af5SMatthias Ringwald  * @brief Disconnect from LE Data Channel
3382da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3383da144af5SMatthias Ringwald  */
3384828a7f7aSMatthias Ringwald uint8_t l2cap_le_disconnect(uint16_t local_cid)
3385da144af5SMatthias Ringwald {
3386828a7f7aSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3387828a7f7aSMatthias Ringwald     if (!channel) {
3388828a7f7aSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
3389828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3390828a7f7aSMatthias Ringwald     }
3391828a7f7aSMatthias Ringwald 
3392828a7f7aSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3393828a7f7aSMatthias Ringwald     l2cap_run();
3394da144af5SMatthias Ringwald     return 0;
3395da144af5SMatthias Ringwald }
3396da144af5SMatthias Ringwald 
33977f02f414SMatthias Ringwald #endif
3398