xref: /btstack/src/l2cap.c (revision e32be4094e1e6f0fdffd3da398b93e076083531a)
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
114212b6be2SMatthias Ringwald static int l2cap_ertm_num_unacknowledged_tx_packets(l2cap_channel_t * channel);
115212b6be2SMatthias Ringwald #endif
11633c40538SMatthias Ringwald 
1175628cf69SMatthias Ringwald typedef struct l2cap_fixed_channel {
1185628cf69SMatthias Ringwald     btstack_packet_handler_t callback;
1192125de09SMatthias Ringwald     uint8_t waiting_for_can_send_now;
1205628cf69SMatthias Ringwald } l2cap_fixed_channel_t;
1215628cf69SMatthias Ringwald 
12209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1235628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_channels;
1245628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_services;
12509e9d05bSMatthias Ringwald static uint8_t require_security_level2_for_outgoing_sdp;
12609e9d05bSMatthias Ringwald #endif
12757be49d6SMatthias Ringwald 
12857be49d6SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1295628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_le_channels;
1305628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_le_services;
13157be49d6SMatthias Ringwald #endif
13239bda6d5Smatthias.ringwald 
13339bda6d5Smatthias.ringwald // used to cache l2cap rejects, echo, and informational requests
1342b83fb7dSmatthias.ringwald static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
1352b83fb7dSmatthias.ringwald static int signaling_responses_pending;
1362b83fb7dSmatthias.ringwald 
137fb37a842SMatthias Ringwald static btstack_packet_callback_registration_t hci_event_callback_registration;
1385628cf69SMatthias Ringwald static l2cap_fixed_channel_t fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_SIZE];
13939bda6d5Smatthias.ringwald 
140d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
141d6ed9f9cSMatthias Ringwald // only used for connection parameter update events
142d6ed9f9cSMatthias Ringwald static btstack_packet_handler_t l2cap_event_packet_handler;
143d6ed9f9cSMatthias Ringwald #endif
144d6ed9f9cSMatthias Ringwald 
14585ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
14685ddcd84SMatthias Ringwald 
14785ddcd84SMatthias Ringwald /*
14885ddcd84SMatthias Ringwald  * CRC lookup table for generator polynom D^16 + D^15 + D^2 + 1
14985ddcd84SMatthias Ringwald  */
15085ddcd84SMatthias Ringwald static const uint16_t crc16_table[256] = {
15185ddcd84SMatthias Ringwald     0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
15285ddcd84SMatthias Ringwald     0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841,
15385ddcd84SMatthias Ringwald     0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41,
15485ddcd84SMatthias Ringwald     0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040,
15585ddcd84SMatthias Ringwald     0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441,
15685ddcd84SMatthias Ringwald     0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840,
15785ddcd84SMatthias Ringwald     0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40,
15885ddcd84SMatthias Ringwald     0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041,
15985ddcd84SMatthias Ringwald     0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
16085ddcd84SMatthias Ringwald     0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840,
16185ddcd84SMatthias Ringwald     0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
16285ddcd84SMatthias Ringwald     0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041,
16385ddcd84SMatthias Ringwald     0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440,
16485ddcd84SMatthias Ringwald     0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841,
16585ddcd84SMatthias Ringwald     0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41,
16685ddcd84SMatthias Ringwald     0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040,
16785ddcd84SMatthias Ringwald };
16885ddcd84SMatthias Ringwald 
16985ddcd84SMatthias Ringwald static uint16_t crc16_calc(uint8_t * data, uint16_t len){
17085ddcd84SMatthias Ringwald     uint16_t crc = 0;   // initial value = 0
17185ddcd84SMatthias Ringwald     while (len--){
17285ddcd84SMatthias Ringwald         crc = (crc >> 8) ^ crc16_table[ (crc ^ ((uint16_t) *data++)) & 0x00FF ];
17385ddcd84SMatthias Ringwald     }
17485ddcd84SMatthias Ringwald     return crc;
17585ddcd84SMatthias Ringwald }
17685ddcd84SMatthias Ringwald 
17785ddcd84SMatthias Ringwald #endif
17885ddcd84SMatthias Ringwald 
17985ddcd84SMatthias Ringwald 
18034e7e577SMatthias Ringwald static uint16_t l2cap_fixed_channel_table_channel_id_for_index(int index){
18134e7e577SMatthias Ringwald     switch (index){
18234e7e577SMatthias Ringwald         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL:
18334e7e577SMatthias Ringwald             return L2CAP_CID_ATTRIBUTE_PROTOCOL;
18434e7e577SMatthias Ringwald         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL:
18534e7e577SMatthias Ringwald             return L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
18634e7e577SMatthias Ringwald         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL:
18734e7e577SMatthias Ringwald             return L2CAP_CID_CONNECTIONLESS_CHANNEL;
18834e7e577SMatthias Ringwald         default:
18934e7e577SMatthias Ringwald             return 0;
19034e7e577SMatthias Ringwald     }
19134e7e577SMatthias Ringwald }
1925628cf69SMatthias Ringwald static int l2cap_fixed_channel_table_index_for_channel_id(uint16_t channel_id){
1935628cf69SMatthias Ringwald     switch (channel_id){
1945628cf69SMatthias Ringwald         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
1955628cf69SMatthias Ringwald             return L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL;
1965628cf69SMatthias Ringwald         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
1975628cf69SMatthias Ringwald             return  L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL;
1985628cf69SMatthias Ringwald         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
1995628cf69SMatthias Ringwald             return  L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL;
2005628cf69SMatthias Ringwald         default:
2015628cf69SMatthias Ringwald             return -1;
2025628cf69SMatthias Ringwald         }
2035628cf69SMatthias Ringwald }
20439bda6d5Smatthias.ringwald 
20534e7e577SMatthias Ringwald static int l2cap_fixed_channel_table_index_is_le(int index){
20634e7e577SMatthias Ringwald     if (index == L2CAP_CID_CONNECTIONLESS_CHANNEL) return 0;
20734e7e577SMatthias Ringwald     return 1;
20834e7e577SMatthias Ringwald }
20934e7e577SMatthias Ringwald 
21071de195eSMatthias Ringwald void l2cap_init(void){
2112b83fb7dSmatthias.ringwald     signaling_responses_pending = 0;
212808a48abSmatthias.ringwald 
21309e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
214f5454fc6Smatthias.ringwald     l2cap_channels = NULL;
215f5454fc6Smatthias.ringwald     l2cap_services = NULL;
21609e9d05bSMatthias Ringwald     require_security_level2_for_outgoing_sdp = 0;
21709e9d05bSMatthias Ringwald #endif
218a3dc965aSMatthias Ringwald 
219a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2207192e786SMatthias Ringwald     l2cap_le_services = NULL;
2217192e786SMatthias Ringwald     l2cap_le_channels = NULL;
222a3dc965aSMatthias Ringwald #endif
223f5454fc6Smatthias.ringwald 
224d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
22533c40538SMatthias Ringwald     l2cap_event_packet_handler = NULL;
226d6ed9f9cSMatthias Ringwald #endif
2275628cf69SMatthias Ringwald     memset(fixed_channels, 0, sizeof(fixed_channels));
228f5454fc6Smatthias.ringwald 
229fcadd0caSmatthias.ringwald     //
2302718e2e7Smatthias.ringwald     // register callback with HCI
231fcadd0caSmatthias.ringwald     //
232d9a7306aSMatthias Ringwald     hci_event_callback_registration.callback = &l2cap_hci_event_handler;
233fb37a842SMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
234fb37a842SMatthias Ringwald 
235d9a7306aSMatthias Ringwald     hci_register_acl_packet_handler(&l2cap_acl_handler);
236fb37a842SMatthias Ringwald 
237be005ed6SMatthias Ringwald #ifdef ENABLE_CLASSIC
23815a95bd5SMatthias Ringwald     gap_connectable_control(0); // no services yet
239be005ed6SMatthias Ringwald #endif
240fcadd0caSmatthias.ringwald }
241fcadd0caSmatthias.ringwald 
242ffbf8201SMatthias Ringwald void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
243d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
24433c40538SMatthias Ringwald     l2cap_event_packet_handler = handler;
245d6ed9f9cSMatthias Ringwald #else
246d6ed9f9cSMatthias Ringwald     UNUSED(handler);
247d6ed9f9cSMatthias Ringwald #endif
2481e6aba47Smatthias.ringwald }
2491e6aba47Smatthias.ringwald 
25009e9d05bSMatthias Ringwald void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
2519ec2630cSMatthias Ringwald     UNUSED(con_handle);
2529ec2630cSMatthias Ringwald 
25309e9d05bSMatthias Ringwald     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
25409e9d05bSMatthias Ringwald     if (index < 0) return;
25509e9d05bSMatthias Ringwald     fixed_channels[index].waiting_for_can_send_now = 1;
25609e9d05bSMatthias Ringwald     l2cap_notify_channel_can_send();
25709e9d05bSMatthias Ringwald }
25809e9d05bSMatthias Ringwald 
25909e9d05bSMatthias Ringwald int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
2609ec2630cSMatthias Ringwald     UNUSED(channel_id);
2619ec2630cSMatthias Ringwald 
26209e9d05bSMatthias Ringwald     return hci_can_send_acl_packet_now(con_handle);
26309e9d05bSMatthias Ringwald }
26409e9d05bSMatthias Ringwald 
26509e9d05bSMatthias Ringwald uint8_t *l2cap_get_outgoing_buffer(void){
26609e9d05bSMatthias Ringwald     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
26709e9d05bSMatthias Ringwald }
26809e9d05bSMatthias Ringwald 
26909e9d05bSMatthias Ringwald int l2cap_reserve_packet_buffer(void){
27009e9d05bSMatthias Ringwald     return hci_reserve_packet_buffer();
27109e9d05bSMatthias Ringwald }
27209e9d05bSMatthias Ringwald 
27309e9d05bSMatthias Ringwald void l2cap_release_packet_buffer(void){
27409e9d05bSMatthias Ringwald     hci_release_packet_buffer();
27509e9d05bSMatthias Ringwald }
27609e9d05bSMatthias Ringwald 
277f511cefaSMatthias 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){
27809e9d05bSMatthias Ringwald     // 0 - Connection handle : PB=pb : BC=00
279f511cefaSMatthias Ringwald     little_endian_store_16(acl_buffer, 0, con_handle | (packet_boundary << 12) | (0 << 14));
28009e9d05bSMatthias Ringwald     // 2 - ACL length
28109e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 2,  len + 4);
28209e9d05bSMatthias Ringwald     // 4 - L2CAP packet length
28309e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 4,  len + 0);
28409e9d05bSMatthias Ringwald     // 6 - L2CAP channel DEST
28509e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 6,  remote_cid);
28609e9d05bSMatthias Ringwald }
28709e9d05bSMatthias Ringwald 
288f511cefaSMatthias Ringwald // assumption - only on LE connections
28909e9d05bSMatthias Ringwald int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
29009e9d05bSMatthias Ringwald 
29109e9d05bSMatthias Ringwald     if (!hci_is_packet_buffer_reserved()){
29209e9d05bSMatthias Ringwald         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
29309e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
29409e9d05bSMatthias Ringwald     }
29509e9d05bSMatthias Ringwald 
29609e9d05bSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
29709e9d05bSMatthias Ringwald         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
29809e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
29909e9d05bSMatthias Ringwald     }
30009e9d05bSMatthias Ringwald 
30109e9d05bSMatthias Ringwald     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
30209e9d05bSMatthias Ringwald 
30309e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
304f511cefaSMatthias Ringwald     l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
30509e9d05bSMatthias Ringwald     // send
30609e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len+8);
30709e9d05bSMatthias Ringwald }
30809e9d05bSMatthias Ringwald 
309f511cefaSMatthias Ringwald // assumption - only on LE connections
31009e9d05bSMatthias Ringwald int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
31109e9d05bSMatthias Ringwald 
31209e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(con_handle)){
31309e9d05bSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", cid);
31409e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
31509e9d05bSMatthias Ringwald     }
31609e9d05bSMatthias Ringwald 
31709e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
31809e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
31909e9d05bSMatthias Ringwald 
32009e9d05bSMatthias Ringwald     memcpy(&acl_buffer[8], data, len);
32109e9d05bSMatthias Ringwald 
32209e9d05bSMatthias Ringwald     return l2cap_send_prepared_connectionless(con_handle, cid, len);
32309e9d05bSMatthias Ringwald }
32409e9d05bSMatthias Ringwald 
32509e9d05bSMatthias Ringwald static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
326d9d23054SMatthias Ringwald     log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
32709e9d05bSMatthias Ringwald     uint8_t event[4];
32809e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
32909e9d05bSMatthias Ringwald     event[1] = sizeof(event) - 2;
33009e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, channel);
33109e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
33209e9d05bSMatthias Ringwald     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
33309e9d05bSMatthias Ringwald }
33409e9d05bSMatthias Ringwald 
33509e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
33617a9b554SMatthias Ringwald static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
33758de5610Smatthias.ringwald     (* (channel->packet_handler))(type, channel->local_cid, data, size);
33858de5610Smatthias.ringwald }
33958de5610Smatthias.ringwald 
34044276248SMatthias Ringwald static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
34144276248SMatthias Ringwald     uint8_t event[4];
34244276248SMatthias Ringwald     event[0] = event_code;
34344276248SMatthias Ringwald     event[1] = sizeof(event) - 2;
34444276248SMatthias Ringwald     little_endian_store_16(event, 2, channel->local_cid);
34544276248SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
34644276248SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
34744276248SMatthias Ringwald }
34809e9d05bSMatthias Ringwald #endif
34944276248SMatthias Ringwald 
35009e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
35158de5610Smatthias.ringwald void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
352c9dc710bS[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",
353fc64f94aSMatthias Ringwald              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
354c9dc710bS[email protected]              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
355bab5f4f0SMatthias Ringwald     uint8_t event[24];
35658de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
35758de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
35858de5610Smatthias.ringwald     event[2] = status;
359724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
360fc64f94aSMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
361f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
362f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
363f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
364f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 17, channel->local_mtu);
365f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 19, channel->remote_mtu);
366f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 21, channel->flush_timeout);
367bab5f4f0SMatthias Ringwald     event[23] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
36858de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
36917a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
37058de5610Smatthias.ringwald }
37158de5610Smatthias.ringwald 
37244276248SMatthias Ringwald static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
373e0abb8e7S[email protected]     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
37444276248SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
37558de5610Smatthias.ringwald }
37658de5610Smatthias.ringwald 
37744276248SMatthias Ringwald static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
378e0abb8e7S[email protected]     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
379fc64f94aSMatthias Ringwald              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
38058de5610Smatthias.ringwald     uint8_t event[16];
38158de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
38258de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
383724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[2]);
384fc64f94aSMatthias Ringwald     little_endian_store_16(event,  8, channel->con_handle);
385f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 10, channel->psm);
386f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 12, channel->local_cid);
387f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 14, channel->remote_cid);
38858de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
38917a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3900af41d30Smatthias.ringwald }
391808a48abSmatthias.ringwald 
3927f02f414SMatthias Ringwald static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
393665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
394665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
395665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
396665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
397b35f641cSmatthias.ringwald         if ( channel->local_cid == local_cid) {
398f62db1e3Smatthias.ringwald             return channel;
399f62db1e3Smatthias.ringwald         }
400f62db1e3Smatthias.ringwald     }
401f62db1e3Smatthias.ringwald     return NULL;
402f62db1e3Smatthias.ringwald }
403f62db1e3Smatthias.ringwald 
4040b9d7e78SMatthias Ringwald ///
4050b9d7e78SMatthias Ringwald 
40630725612SMatthias Ringwald void l2cap_request_can_send_now_event(uint16_t local_cid){
40730725612SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
40830725612SMatthias Ringwald     if (!channel) return;
40930725612SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
41030725612SMatthias Ringwald     l2cap_notify_channel_can_send();
41130725612SMatthias Ringwald }
41230725612SMatthias Ringwald 
4136b1fde37Smatthias.ringwald int  l2cap_can_send_packet_now(uint16_t local_cid){
4146b1fde37Smatthias.ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
4156b1fde37Smatthias.ringwald     if (!channel) return 0;
4160b9d7e78SMatthias Ringwald     return hci_can_send_acl_packet_now(channel->con_handle);
4177856fb31S[email protected] }
4187856fb31S[email protected] 
41983e7cdd9SMatthias Ringwald int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
42083e7cdd9SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
42183e7cdd9SMatthias Ringwald     if (!channel) return 0;
4220b9d7e78SMatthias Ringwald     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
42383e7cdd9SMatthias Ringwald }
42496cbd662Smatthias.ringwald uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
42596cbd662Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
42696cbd662Smatthias.ringwald     if (channel) {
42796cbd662Smatthias.ringwald         return channel->remote_mtu;
42896cbd662Smatthias.ringwald     }
42996cbd662Smatthias.ringwald     return 0;
43096cbd662Smatthias.ringwald }
43196cbd662Smatthias.ringwald 
432ec820d77SMatthias Ringwald static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
433665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
434665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
435665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
436665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4375932bd7cS[email protected]         if ( &channel->rtx == ts) {
4385932bd7cS[email protected]             return channel;
4395932bd7cS[email protected]         }
4405932bd7cS[email protected]     }
4415932bd7cS[email protected]     return NULL;
4425932bd7cS[email protected] }
4435932bd7cS[email protected] 
444ec820d77SMatthias Ringwald static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
4455932bd7cS[email protected]     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
44695d2c8f4SMatthias Ringwald     if (!channel) return;
4475932bd7cS[email protected] 
4485932bd7cS[email protected]     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
4495932bd7cS[email protected] 
4505932bd7cS[email protected]     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
4515932bd7cS[email protected]     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
4525932bd7cS[email protected]     // notify client
4535932bd7cS[email protected]     l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
4545932bd7cS[email protected] 
4555932bd7cS[email protected]     // discard channel
4569dcb2fb2S[email protected]     // no need to stop timer here, it is removed from list during timer callback
457665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4585932bd7cS[email protected]     btstack_memory_l2cap_channel_free(channel);
4595932bd7cS[email protected] }
4605932bd7cS[email protected] 
4615932bd7cS[email protected] static void l2cap_stop_rtx(l2cap_channel_t * channel){
4625932bd7cS[email protected]     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
463528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->rtx);
4645932bd7cS[email protected] }
4655932bd7cS[email protected] 
4665932bd7cS[email protected] static void l2cap_start_rtx(l2cap_channel_t * channel){
4675932bd7cS[email protected]     l2cap_stop_rtx(channel);
468cb0ff06bS[email protected]     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
469528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
470528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
471528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
4725932bd7cS[email protected] }
4735932bd7cS[email protected] 
4745932bd7cS[email protected] static void l2cap_start_ertx(l2cap_channel_t * channel){
4755932bd7cS[email protected]     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
4765932bd7cS[email protected]     l2cap_stop_rtx(channel);
477528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
478528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
479528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
4805932bd7cS[email protected] }
4815932bd7cS[email protected] 
48271de195eSMatthias Ringwald void l2cap_require_security_level_2_for_outgoing_sdp(void){
483ac301f95S[email protected]     require_security_level2_for_outgoing_sdp = 1;
484ac301f95S[email protected] }
485ac301f95S[email protected] 
486df3354fcS[email protected] static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
487235946f1SMatthias Ringwald     return (psm == BLUETOOTH_PROTOCOL_SDP) && (!require_security_level2_for_outgoing_sdp);
488df3354fcS[email protected] }
4895932bd7cS[email protected] 
4907f02f414SMatthias Ringwald static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
491a35252c8S[email protected]     if (!hci_can_send_acl_packet_now(handle)){
4929da54300S[email protected]         log_info("l2cap_send_signaling_packet, cannot send");
493b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
494b1d43497Smatthias.ringwald     }
495b1d43497Smatthias.ringwald 
4969da54300S[email protected]     // log_info("l2cap_send_signaling_packet type %u", cmd);
4972a373862S[email protected]     hci_reserve_packet_buffer();
498facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
49958de5610Smatthias.ringwald     va_list argptr;
50058de5610Smatthias.ringwald     va_start(argptr, identifier);
50170efece1S[email protected]     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
50258de5610Smatthias.ringwald     va_end(argptr);
5039da54300S[email protected]     // log_info("l2cap_send_signaling_packet con %u!", handle);
504826f7347S[email protected]     return hci_send_acl_packet_buffer(len);
50558de5610Smatthias.ringwald }
50658de5610Smatthias.ringwald 
507f511cefaSMatthias Ringwald // assumption - only on Classic connections
508b1d43497Smatthias.ringwald int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
509b1d43497Smatthias.ringwald 
510c8b9416aS[email protected]     if (!hci_is_packet_buffer_reserved()){
511c8b9416aS[email protected]         log_error("l2cap_send_prepared called without reserving packet first");
512c8b9416aS[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
513c8b9416aS[email protected]     }
514c8b9416aS[email protected] 
51558de5610Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
516b1d43497Smatthias.ringwald     if (!channel) {
5179da54300S[email protected]         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
518b1d43497Smatthias.ringwald         return -1;   // TODO: define error
5196218e6f1Smatthias.ringwald     }
5206218e6f1Smatthias.ringwald 
521fc64f94aSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
5229da54300S[email protected]         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
523a35252c8S[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
524a35252c8S[email protected]     }
525a35252c8S[email protected] 
526fc64f94aSMatthias Ringwald     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
527b1d43497Smatthias.ringwald 
52885ddcd84SMatthias Ringwald     int fcs_size = 0;
52985ddcd84SMatthias Ringwald 
53085ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
53185ddcd84SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
53285ddcd84SMatthias Ringwald         fcs_size = 2;
53385ddcd84SMatthias Ringwald     }
53485ddcd84SMatthias Ringwald #endif
53585ddcd84SMatthias Ringwald 
536f511cefaSMatthias Ringwald     // set non-flushable packet boundary flag if supported on Controller
537facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
538f511cefaSMatthias Ringwald     uint8_t packet_boundary_flag = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
53985ddcd84SMatthias Ringwald     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
54085ddcd84SMatthias Ringwald 
54185ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
54285ddcd84SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
54385ddcd84SMatthias Ringwald         // calculate FCS over l2cap data
54485ddcd84SMatthias Ringwald         uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
54585ddcd84SMatthias Ringwald         log_info("I-Frame: fcs 0x%04x", fcs);
54685ddcd84SMatthias Ringwald         little_endian_store_16(acl_buffer, 8 + len, fcs);
54758de5610Smatthias.ringwald     }
54885ddcd84SMatthias Ringwald #endif
54985ddcd84SMatthias Ringwald 
55085ddcd84SMatthias Ringwald     // send
55185ddcd84SMatthias Ringwald     return hci_send_acl_packet_buffer(len+8+fcs_size);
55285ddcd84SMatthias Ringwald }
55385ddcd84SMatthias Ringwald 
55485ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
55585ddcd84SMatthias 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){
55685ddcd84SMatthias Ringwald     return (((uint16_t) sar) << 14) | (req_seq << 8) | (final << 7) | (tx_seq << 1) | 0;
55785ddcd84SMatthias Ringwald }
55885ddcd84SMatthias Ringwald static inline uint16_t l2cap_encanced_control_field_for_supevisor_frame(l2cap_supervisory_function_t supervisory_function, int poll, int final, uint8_t req_seq){
55938f62777SMatthias Ringwald     return (req_seq << 8) | (final << 7) | (poll << 4) | (((int) supervisory_function) << 2) | 1;
56085ddcd84SMatthias Ringwald }
56185ddcd84SMatthias Ringwald static int l2cap_next_ertm_seq_nr(int seq_nr){
56285ddcd84SMatthias Ringwald     return (seq_nr + 1) & 0x3f;
56385ddcd84SMatthias Ringwald }
564f0fb4cd7SMatthias Ringwald static void l2cap_ertm_next_tx_write_index(l2cap_channel_t * channel){
565f0fb4cd7SMatthias Ringwald     channel->tx_write_index++;
566f0fb4cd7SMatthias Ringwald     if (channel->tx_write_index < channel->num_tx_buffers) return;
567f0fb4cd7SMatthias Ringwald     channel->tx_write_index = 0;
568f0fb4cd7SMatthias Ringwald }
56920fa474dSMatthias Ringwald static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts){
57020fa474dSMatthias Ringwald     log_info("l2cap_ertm_monitor_timeout_callback");
571db55d2e9SMatthias Ringwald     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
572db55d2e9SMatthias Ringwald 
573db55d2e9SMatthias Ringwald     // TODO: we assume that it's the oldest packet
574db55d2e9SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
575db55d2e9SMatthias Ringwald     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
576db55d2e9SMatthias Ringwald 
577db55d2e9SMatthias Ringwald     // check retry count
578db55d2e9SMatthias Ringwald     if (tx_state->retry_count < l2cap_channel->remote_max_transmit){
579db55d2e9SMatthias Ringwald         // increment retry count
580db55d2e9SMatthias Ringwald         tx_state->retry_count++;
581db55d2e9SMatthias Ringwald 
582db55d2e9SMatthias Ringwald         // start monitor timer
583db55d2e9SMatthias Ringwald         btstack_run_loop_set_timer_handler(&tx_state->monitor_timer, &l2cap_ertm_monitor_timeout_callback);
584db55d2e9SMatthias Ringwald         btstack_run_loop_set_timer_context(&tx_state->monitor_timer, l2cap_channel);
585db55d2e9SMatthias Ringwald         btstack_run_loop_set_timer(&tx_state->monitor_timer, l2cap_channel->local_monitor_timeout_ms);
586db55d2e9SMatthias Ringwald         btstack_run_loop_add_timer(&tx_state->monitor_timer);
587db55d2e9SMatthias Ringwald 
588db55d2e9SMatthias Ringwald         // send RR/P=1
589db55d2e9SMatthias Ringwald         l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
590db55d2e9SMatthias Ringwald     } else {
591db55d2e9SMatthias Ringwald         log_info("Monitor timer expired & retry count >= max transmit -> disconnect");
592db55d2e9SMatthias Ringwald         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
593db55d2e9SMatthias Ringwald     }
594db55d2e9SMatthias Ringwald     l2cap_run();
595db55d2e9SMatthias Ringwald }
596db55d2e9SMatthias Ringwald static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts){
597db55d2e9SMatthias Ringwald     log_info("l2cap_ertm_retransmission_timeout_callback");
598db55d2e9SMatthias Ringwald     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
599db55d2e9SMatthias Ringwald 
600db55d2e9SMatthias Ringwald     // TODO: we assume that it's the oldest packet
601db55d2e9SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
602db55d2e9SMatthias Ringwald     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
603db55d2e9SMatthias Ringwald 
604db55d2e9SMatthias Ringwald     // set retry count = 1
605db55d2e9SMatthias Ringwald     tx_state->retry_count = 1;
606db55d2e9SMatthias Ringwald 
607db55d2e9SMatthias Ringwald     // start monitor timer
608db55d2e9SMatthias Ringwald     btstack_run_loop_set_timer_handler(&tx_state->monitor_timer, &l2cap_ertm_monitor_timeout_callback);
609db55d2e9SMatthias Ringwald     btstack_run_loop_set_timer_context(&tx_state->monitor_timer, l2cap_channel);
610db55d2e9SMatthias Ringwald     btstack_run_loop_set_timer(&tx_state->monitor_timer, l2cap_channel->local_monitor_timeout_ms);
611db55d2e9SMatthias Ringwald     btstack_run_loop_add_timer(&tx_state->monitor_timer);
612db55d2e9SMatthias Ringwald 
613db55d2e9SMatthias Ringwald     // send RR/P=1
614db55d2e9SMatthias Ringwald     l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
61520fa474dSMatthias Ringwald     l2cap_run();
61620fa474dSMatthias Ringwald }
6177b7901d8SMatthias Ringwald static int l2cap_ertm_send_information_frame(l2cap_channel_t * channel, int index, int final){
618f0fb4cd7SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
619f0fb4cd7SMatthias Ringwald     hci_reserve_packet_buffer();
620f0fb4cd7SMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
62182bb0e22SMatthias Ringwald     uint16_t control = l2cap_encanced_control_field_for_information_frame(tx_state->tx_seq, final, channel->req_seq, tx_state->sar);
622f0fb4cd7SMatthias Ringwald     log_info("I-Frame: control 0x%04x", control);
623f0fb4cd7SMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
624f0fb4cd7SMatthias Ringwald     memcpy(&acl_buffer[8+2], &channel->tx_packets_data[index * channel->local_mtu], tx_state->len);
625f0fb4cd7SMatthias Ringwald     // send
626f0fb4cd7SMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2 + tx_state->len);
627f0fb4cd7SMatthias Ringwald }
62882bb0e22SMatthias Ringwald 
6297bebc11cSMatthias 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){
6307bebc11cSMatthias Ringwald     // get next index for storing packets
631f0fb4cd7SMatthias Ringwald     int index = channel->tx_write_index;
63282bb0e22SMatthias Ringwald 
633f0fb4cd7SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
634f0fb4cd7SMatthias Ringwald     tx_state->tx_seq = channel->next_tx_seq;
635f0fb4cd7SMatthias Ringwald     tx_state->len = len;
6367bebc11cSMatthias Ringwald     tx_state->sar = sar;
637db55d2e9SMatthias Ringwald     tx_state->retry_count = 0;
63882bb0e22SMatthias Ringwald 
63982bb0e22SMatthias Ringwald     uint8_t * tx_packet = &channel->tx_packets_data[index * channel->local_mtu];
6407bebc11cSMatthias Ringwald     int pos = 0;
6417bebc11cSMatthias Ringwald     if (sar == L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU){
6427bebc11cSMatthias Ringwald         little_endian_store_16(tx_packet, 0, sdu_length);
6437bebc11cSMatthias Ringwald         pos += 2;
6447bebc11cSMatthias Ringwald     }
6457bebc11cSMatthias Ringwald     memcpy(&tx_packet[pos], data, len);
64682bb0e22SMatthias Ringwald 
647f0fb4cd7SMatthias Ringwald     // update
648f0fb4cd7SMatthias Ringwald     channel->next_tx_seq = l2cap_next_ertm_seq_nr(channel->next_tx_seq);
649f0fb4cd7SMatthias Ringwald     l2cap_ertm_next_tx_write_index(channel);
65082bb0e22SMatthias Ringwald 
65162041d70SMatthias Ringwald     // set retransmission timer
65262041d70SMatthias Ringwald     btstack_run_loop_set_timer_handler(&tx_state->retransmission_timer, &l2cap_ertm_retransmission_timeout_callback);
65362041d70SMatthias Ringwald     btstack_run_loop_set_timer_context(&tx_state->retransmission_timer, channel);
65462041d70SMatthias Ringwald     btstack_run_loop_set_timer(&tx_state->retransmission_timer, channel->local_retransmission_timeout_ms);
65562041d70SMatthias Ringwald     btstack_run_loop_add_timer(&tx_state->retransmission_timer);
6567bebc11cSMatthias Ringwald }
6577bebc11cSMatthias Ringwald 
6587bebc11cSMatthias Ringwald static int l2cap_ertm_send(l2cap_channel_t * channel, uint8_t * data, uint16_t len){
6597bebc11cSMatthias Ringwald     if (len > channel->remote_mtu){
6607bebc11cSMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
6617bebc11cSMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
6627bebc11cSMatthias Ringwald     }
6637bebc11cSMatthias Ringwald 
6647bebc11cSMatthias Ringwald     // check if it needs to get fragmented
6657bebc11cSMatthias Ringwald     if (len > channel->remote_mps){
6667bebc11cSMatthias Ringwald         // fragmentation needed.
6677bebc11cSMatthias Ringwald         l2cap_segmentation_and_reassembly_t sar =  L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU;
6687bebc11cSMatthias Ringwald         int chunk_len;
6697bebc11cSMatthias Ringwald         while (len){
6707bebc11cSMatthias Ringwald             switch (sar){
6717bebc11cSMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
6727bebc11cSMatthias Ringwald                     chunk_len = channel->remote_mps - 2;    // sdu_length
6737bebc11cSMatthias Ringwald                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
6747bebc11cSMatthias Ringwald                     len -= chunk_len;
6757bebc11cSMatthias Ringwald                     sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU;
6767bebc11cSMatthias Ringwald                     break;
6777bebc11cSMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
6787bebc11cSMatthias Ringwald                     chunk_len = channel->remote_mps;
6797bebc11cSMatthias Ringwald                     if (chunk_len >= len){
6807bebc11cSMatthias Ringwald                         sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU;
6817bebc11cSMatthias Ringwald                         chunk_len = len;
6827bebc11cSMatthias Ringwald                     }
6837bebc11cSMatthias Ringwald                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
6847bebc11cSMatthias Ringwald                     len -= chunk_len;
6857bebc11cSMatthias Ringwald                     break;
6867bebc11cSMatthias Ringwald                 default:
6877bebc11cSMatthias Ringwald                     break;
6887bebc11cSMatthias Ringwald             }
6897bebc11cSMatthias Ringwald         }
6907bebc11cSMatthias Ringwald 
6917bebc11cSMatthias Ringwald     } else {
6927bebc11cSMatthias Ringwald         l2cap_ertm_store_fragment(channel, L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU, 0, data, len);
6937bebc11cSMatthias Ringwald     }
69482bb0e22SMatthias Ringwald 
695675e6881SMatthias Ringwald     // try to send
696675e6881SMatthias Ringwald     l2cap_run();
697f0fb4cd7SMatthias Ringwald     return 0;
698f0fb4cd7SMatthias Ringwald }
69985ddcd84SMatthias Ringwald #endif
70058de5610Smatthias.ringwald 
701f511cefaSMatthias Ringwald // assumption - only on Classic connections
702ce8f182eSMatthias Ringwald int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
703a35252c8S[email protected]     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
704a35252c8S[email protected]     if (!channel) {
705ce8f182eSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
706a35252c8S[email protected]         return -1;   // TODO: define error
707a35252c8S[email protected]     }
708a35252c8S[email protected] 
709f0fb4cd7SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
710f0fb4cd7SMatthias Ringwald     // send in ERTM
711f0fb4cd7SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
712f0fb4cd7SMatthias Ringwald         return l2cap_ertm_send(channel, data, len);
713f0fb4cd7SMatthias Ringwald     }
714f0fb4cd7SMatthias Ringwald #endif
715f0fb4cd7SMatthias Ringwald 
716f0efaa57S[email protected]     if (len > channel->remote_mtu){
717ce8f182eSMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
718f0efaa57S[email protected]         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
719f0efaa57S[email protected]     }
720f0efaa57S[email protected] 
721fc64f94aSMatthias Ringwald     if (!hci_can_send_acl_packet_now(channel->con_handle)){
722ce8f182eSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
723b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
724b1d43497Smatthias.ringwald     }
725b1d43497Smatthias.ringwald 
7262a373862S[email protected]     hci_reserve_packet_buffer();
727facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
728f0fb4cd7SMatthias Ringwald     memcpy(&acl_buffer[8], data, len);
729f0fb4cd7SMatthias Ringwald     return l2cap_send_prepared(local_cid, len);
730b1d43497Smatthias.ringwald }
731b1d43497Smatthias.ringwald 
732fc64f94aSMatthias Ringwald int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
733fc64f94aSMatthias Ringwald     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
7340e37e417S[email protected] }
7350e37e417S[email protected] 
73628ca2b46S[email protected] static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
73728ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
73828ca2b46S[email protected] }
73928ca2b46S[email protected] 
74028ca2b46S[email protected] static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
74128ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
74228ca2b46S[email protected] }
74309e9d05bSMatthias Ringwald #endif
74428ca2b46S[email protected] 
74528ca2b46S[email protected] 
74609e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
74709e9d05bSMatthias Ringwald static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
74809e9d05bSMatthias Ringwald 
74909e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(handle)){
75009e9d05bSMatthias Ringwald         log_info("l2cap_send_le_signaling_packet, cannot send");
75109e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
75209e9d05bSMatthias Ringwald     }
75309e9d05bSMatthias Ringwald 
75409e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
75509e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
75609e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
75709e9d05bSMatthias Ringwald     va_list argptr;
75809e9d05bSMatthias Ringwald     va_start(argptr, identifier);
75909e9d05bSMatthias Ringwald     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
76009e9d05bSMatthias Ringwald     va_end(argptr);
76109e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
76209e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len);
76309e9d05bSMatthias Ringwald }
76409e9d05bSMatthias Ringwald #endif
76509e9d05bSMatthias Ringwald 
76609e9d05bSMatthias Ringwald uint16_t l2cap_max_mtu(void){
76709e9d05bSMatthias Ringwald     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
76809e9d05bSMatthias Ringwald }
76909e9d05bSMatthias Ringwald 
77009e9d05bSMatthias Ringwald uint16_t l2cap_max_le_mtu(void){
77109e9d05bSMatthias Ringwald     return l2cap_max_mtu();
77209e9d05bSMatthias Ringwald }
773b1d43497Smatthias.ringwald 
7746dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
775450ad7ecSMatthias Ringwald static uint16_t l2cap_setup_options_ertm(l2cap_channel_t * channel, uint8_t * config_options){
7766dca2a0cSMatthias Ringwald     config_options[0] = 0x04;   // RETRANSMISSION AND FLOW CONTROL OPTION
7776dca2a0cSMatthias Ringwald     config_options[1] = 9;      // length
7786dca2a0cSMatthias Ringwald     config_options[2] = (uint8_t) channel->mode;
7797b181629SMatthias Ringwald     config_options[3] = channel->num_rx_buffers;    // == TxWindows size
780bbc0a9e7SMatthias Ringwald     config_options[4] = channel->local_max_transmit;
781bbc0a9e7SMatthias Ringwald     little_endian_store_16( config_options, 5, channel->local_retransmission_timeout_ms);
782bbc0a9e7SMatthias Ringwald     little_endian_store_16( config_options, 7, channel->local_monitor_timeout_ms);
783843bae5dSMatthias Ringwald     little_endian_store_16( config_options, 9, channel->local_mps);
784450ad7ecSMatthias Ringwald     return 11;
7856dca2a0cSMatthias Ringwald }
78638f62777SMatthias Ringwald static int l2cap_ertm_send_supervisor_frame(l2cap_channel_t * channel, uint16_t control){
78738f62777SMatthias Ringwald     hci_reserve_packet_buffer();
78838f62777SMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
78938f62777SMatthias Ringwald     log_info("S-Frame: control 0x%04x", control);
79038f62777SMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
79138f62777SMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2);
79238f62777SMatthias Ringwald }
793212b6be2SMatthias Ringwald static int l2cap_ertm_num_unacknowledged_tx_packets(l2cap_channel_t * channel){
794212b6be2SMatthias Ringwald     int unacknowledged_packets = channel->tx_send_index - channel->tx_read_index;
795212b6be2SMatthias Ringwald     if (unacknowledged_packets < 0){
796212b6be2SMatthias Ringwald         unacknowledged_packets += channel->num_tx_buffers;
797212b6be2SMatthias Ringwald     }
798212b6be2SMatthias Ringwald     return unacknowledged_packets;
799212b6be2SMatthias Ringwald }
800450ad7ecSMatthias Ringwald #endif
801450ad7ecSMatthias Ringwald 
802d2afdd38SMatthias Ringwald #ifdef ENABLE_CLASSIC
803d2afdd38SMatthias Ringwald 
804d2afdd38SMatthias Ringwald static uint16_t l2cap_setup_options_mtu(l2cap_channel_t * channel, uint8_t * config_options){
805d2afdd38SMatthias Ringwald     config_options[0] = 1; // MTU
806d2afdd38SMatthias Ringwald     config_options[1] = 2; // len param
807d2afdd38SMatthias Ringwald     little_endian_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
808d2afdd38SMatthias Ringwald     return 4;
809d2afdd38SMatthias Ringwald }
810d2afdd38SMatthias Ringwald 
811450ad7ecSMatthias Ringwald static uint16_t l2cap_setup_options(l2cap_channel_t * channel, uint8_t * config_options){
812450ad7ecSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
813450ad7ecSMatthias Ringwald     // use ERTM options if supported
814450ad7ecSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
815450ad7ecSMatthias Ringwald     if ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE) && (connection->l2cap_state.extended_feature_mask & 0x08)){
816450ad7ecSMatthias Ringwald         return l2cap_setup_options_ertm(channel, config_options);
817450ad7ecSMatthias Ringwald 
818450ad7ecSMatthias Ringwald     }
819450ad7ecSMatthias Ringwald #endif
820450ad7ecSMatthias Ringwald     return l2cap_setup_options_mtu(channel, config_options);
8216dca2a0cSMatthias Ringwald }
8226dca2a0cSMatthias Ringwald 
8231b9cb13dSMatthias Ringwald static uint32_t l2cap_extended_features_mask(void){
8241b9cb13dSMatthias Ringwald     // extended features request supported, features: fixed channels, unicast connectionless data reception
8251b9cb13dSMatthias Ringwald     uint32_t features = 0x280;
8261b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
8271b9cb13dSMatthias Ringwald     features |= 0x0008;
8281b9cb13dSMatthias Ringwald #endif
8291b9cb13dSMatthias Ringwald     return features;
8301b9cb13dSMatthias Ringwald }
831d2afdd38SMatthias Ringwald #endif
8321b9cb13dSMatthias Ringwald 
8338158c421Smatthias.ringwald // MARK: L2CAP_RUN
8342cd0be45Smatthias.ringwald // process outstanding signaling tasks
8357f02f414SMatthias Ringwald static void l2cap_run(void){
8362b83fb7dSmatthias.ringwald 
83722c29ab4SMatthias Ringwald     // log_info("l2cap_run: entered");
83822c29ab4SMatthias Ringwald 
8392b83fb7dSmatthias.ringwald     // check pending signaling responses
8402b83fb7dSmatthias.ringwald     while (signaling_responses_pending){
8412b83fb7dSmatthias.ringwald 
8422b83fb7dSmatthias.ringwald         hci_con_handle_t handle = signaling_responses[0].handle;
843a35252c8S[email protected] 
844a35252c8S[email protected]         if (!hci_can_send_acl_packet_now(handle)) break;
845a35252c8S[email protected] 
8462b83fb7dSmatthias.ringwald         uint8_t  sig_id        = signaling_responses[0].sig_id;
847e74c5f58SMatthias Ringwald         uint8_t  response_code = signaling_responses[0].code;
8482b360848Smatthias.ringwald         uint16_t infoType      = signaling_responses[0].data;  // INFORMATION_REQUEST
84963a7246aSmatthias.ringwald         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
850b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
851b3264428SMatthias Ringwald         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
852b3264428SMatthias Ringwald #endif
853f3963406SMatthias Ringwald         UNUSED(infoType);
85409e9d05bSMatthias Ringwald 
855f53da564S[email protected]         // remove first item before sending (to avoid sending response mutliple times)
856f53da564S[email protected]         signaling_responses_pending--;
857f53da564S[email protected]         int i;
858f53da564S[email protected]         for (i=0; i < signaling_responses_pending; i++){
859f53da564S[email protected]             memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t));
860f53da564S[email protected]         }
861f53da564S[email protected] 
862f53da564S[email protected]         switch (response_code){
86309e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
8642b360848Smatthias.ringwald             case CONNECTION_REQUEST:
865e74c5f58SMatthias Ringwald                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
8662bd8b7e7S[email protected]                 // also disconnect if result is 0x0003 - security blocked
8674d816277S[email protected]                 if (result == 0x0003){
8682bd8b7e7S[email protected]                     hci_disconnect_security_block(handle);
8694d816277S[email protected]                 }
8702b360848Smatthias.ringwald                 break;
8712b83fb7dSmatthias.ringwald             case ECHO_REQUEST:
8722b83fb7dSmatthias.ringwald                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
8732b83fb7dSmatthias.ringwald                 break;
8742b83fb7dSmatthias.ringwald             case INFORMATION_REQUEST:
8753b0484b3S[email protected]                 switch (infoType){
8763b0484b3S[email protected]                     case 1: { // Connectionless MTU
8773b0484b3S[email protected]                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
8783b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(connectionless_mtu), &connectionless_mtu);
8793b0484b3S[email protected]                         }
880202c8a4cSMatthias Ringwald                         break;
8813b0484b3S[email protected]                     case 2: {  // Extended Features Supported
8821b9cb13dSMatthias Ringwald                             uint32_t features = l2cap_extended_features_mask();
8833b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(features), &features);
8843b0484b3S[email protected]                         }
885202c8a4cSMatthias Ringwald                         break;
8863b0484b3S[email protected]                     case 3: { // Fixed Channels Supported
8873b0484b3S[email protected]                             uint8_t map[8];
8883b0484b3S[email protected]                             memset(map, 0, 8);
889288636a2SMatthias Ringwald                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
8903b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(map), &map);
8913b0484b3S[email protected]                         }
892202c8a4cSMatthias Ringwald                         break;
8933b0484b3S[email protected]                     default:
8942b83fb7dSmatthias.ringwald                         // all other types are not supported
8952b83fb7dSmatthias.ringwald                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
8963b0484b3S[email protected]                         break;
8972b83fb7dSmatthias.ringwald                 }
8982b83fb7dSmatthias.ringwald                 break;
89963a7246aSmatthias.ringwald             case COMMAND_REJECT:
9005ca8d57bS[email protected]                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
90163f0ac45SMatthias Ringwald                 break;
90209e9d05bSMatthias Ringwald #endif
903a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
90463f0ac45SMatthias Ringwald             case LE_CREDIT_BASED_CONNECTION_REQUEST:
90563f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
90663f0ac45SMatthias Ringwald                 break;
90770efece1S[email protected]             case COMMAND_REJECT_LE:
90870efece1S[email protected]                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
90963a7246aSmatthias.ringwald                 break;
91070efece1S[email protected] #endif
9112b83fb7dSmatthias.ringwald             default:
9122b83fb7dSmatthias.ringwald                 // should not happen
9132b83fb7dSmatthias.ringwald                 break;
9142b83fb7dSmatthias.ringwald         }
9152b83fb7dSmatthias.ringwald     }
9162b83fb7dSmatthias.ringwald 
917665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
918f3963406SMatthias Ringwald     UNUSED(it);
91909e9d05bSMatthias Ringwald 
9201b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
9211b9cb13dSMatthias Ringwald     // send l2cap information request if neccessary
9221b9cb13dSMatthias Ringwald     hci_connections_get_iterator(&it);
9231b9cb13dSMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
9241b9cb13dSMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
9251b9cb13dSMatthias Ringwald         if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST){
9261b9cb13dSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
9271b9cb13dSMatthias Ringwald             // send information request for extended features
9281b9cb13dSMatthias Ringwald             uint8_t sig_id = l2cap_next_sig_id();
9291b9cb13dSMatthias Ringwald             uint8_t info_type = 2;
9301b9cb13dSMatthias Ringwald             l2cap_send_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
9311b9cb13dSMatthias Ringwald             return;
9321b9cb13dSMatthias Ringwald         }
9331b9cb13dSMatthias Ringwald     }
9341b9cb13dSMatthias Ringwald #endif
9351b9cb13dSMatthias Ringwald 
93609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
93743ec931dSMatthias Ringwald     uint8_t  config_options[10];
938665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
939665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
940baf94f06S[email protected] 
941665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
94222c29ab4SMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
9432cd0be45Smatthias.ringwald         switch (channel->state){
9442cd0be45Smatthias.ringwald 
945df3354fcS[email protected]             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
946ad671560S[email protected]             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
947fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
948a00031e2S[email protected]                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
949ad671560S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
950fc64f94aSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
951ad671560S[email protected]                 }
952ad671560S[email protected]                 break;
953ad671560S[email protected] 
95402b22dc4Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
955baf94f06S[email protected]                 if (!hci_can_send_command_packet_now()) break;
95664472d52Smatthias.ringwald                 // send connection request - set state first
95764472d52Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
95802b22dc4Smatthias.ringwald                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
9598f8108aaSmatthias.ringwald                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
96002b22dc4Smatthias.ringwald                 break;
96102b22dc4Smatthias.ringwald 
962e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
963fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
96422c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
965fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
966e7ff783cSmatthias.ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
9679dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
968665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
969d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
970e7ff783cSmatthias.ringwald                 break;
971e7ff783cSmatthias.ringwald 
972552d92a1Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
973fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
974fa8473a4Smatthias.ringwald                 channel->state = L2CAP_STATE_CONFIG;
97528ca2b46S[email protected]                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
976fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
977552d92a1Smatthias.ringwald                 break;
978552d92a1Smatthias.ringwald 
9796fdcc387Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
980fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
9816fdcc387Smatthias.ringwald                 // success, start l2cap handshake
982b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
9836fdcc387Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
984fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
9855932bd7cS[email protected]                 l2cap_start_rtx(channel);
9866fdcc387Smatthias.ringwald                 break;
9876fdcc387Smatthias.ringwald 
988fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
989fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
99073cf2b3dSmatthias.ringwald                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
99163a7246aSmatthias.ringwald                     uint16_t flags = 0;
99228ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
99363a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
99463a7246aSmatthias.ringwald                         flags = 1;
99563a7246aSmatthias.ringwald                     } else {
99628ca2b46S[email protected]                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
99763a7246aSmatthias.ringwald                     }
99863a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
999ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1000fc64f94aSMatthias 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);
1001ac8f1300SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1002ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
1003ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1004ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
10056dca2a0cSMatthias Ringwald                         uint16_t options_size = l2cap_setup_options(channel, config_options);
1006ac8f1300SMatthias 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);
1007ac8f1300SMatthias Ringwald #endif
1008ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
100963a7246aSmatthias.ringwald                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1010ac8f1300SMatthias Ringwald                         uint16_t options_size = l2cap_setup_options(channel, config_options);
1011ac8f1300SMatthias 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);
101263a7246aSmatthias.ringwald                     } else {
1013ac8f1300SMatthias Ringwald                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
101463a7246aSmatthias.ringwald                     }
101563a7246aSmatthias.ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1016fa8473a4Smatthias.ringwald                 }
101773cf2b3dSmatthias.ringwald                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
101828ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
101928ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
1020b1988dceSmatthias.ringwald                     channel->local_sig_id = l2cap_next_sig_id();
10216dca2a0cSMatthias Ringwald                     uint16_t options_size = l2cap_setup_options(channel, config_options);
10226dca2a0cSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options);
10235932bd7cS[email protected]                     l2cap_start_rtx(channel);
1024fa8473a4Smatthias.ringwald                 }
1025fa8473a4Smatthias.ringwald                 if (l2cap_channel_ready_for_open(channel)){
1026552d92a1Smatthias.ringwald                     channel->state = L2CAP_STATE_OPEN;
1027552d92a1Smatthias.ringwald                     l2cap_emit_channel_opened(channel, 0);  // success
1028fa8473a4Smatthias.ringwald                 }
1029552d92a1Smatthias.ringwald                 break;
1030552d92a1Smatthias.ringwald 
1031e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1032fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
103322c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1034fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
10355932bd7cS[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 :)
1036756102d3Smatthias.ringwald                 l2cap_finialize_channel_close(channel);  // -- remove from list
1037e7ff783cSmatthias.ringwald                 break;
1038e7ff783cSmatthias.ringwald 
1039e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1040fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1041b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
10422cd0be45Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1043fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
10442cd0be45Smatthias.ringwald                 break;
10452cd0be45Smatthias.ringwald             default:
10462cd0be45Smatthias.ringwald                 break;
10472cd0be45Smatthias.ringwald         }
104838f62777SMatthias Ringwald 
104938f62777SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
105038f62777SMatthias Ringwald         // send s-frame to acknowledge received packets
105138f62777SMatthias Ringwald         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
1052675e6881SMatthias Ringwald 
1053675e6881SMatthias Ringwald         if (channel->tx_send_index != channel->tx_write_index){
1054212b6be2SMatthias Ringwald             int unacknowledged_packets = l2cap_ertm_num_unacknowledged_tx_packets(channel);
1055212b6be2SMatthias Ringwald             // check remote tx window
1056212b6be2SMatthias Ringwald             log_info("unacknowledged_packets %u, remote tx window size %u", unacknowledged_packets, channel->remote_tx_window_size);
1057212b6be2SMatthias Ringwald             if (unacknowledged_packets < channel->remote_tx_window_size){
1058675e6881SMatthias Ringwald                 int index = channel->tx_send_index;
1059675e6881SMatthias Ringwald                 channel->tx_send_index++;
1060675e6881SMatthias Ringwald                 if (channel->tx_send_index >= channel->num_tx_buffers){
1061675e6881SMatthias Ringwald                     channel->tx_send_index = 0;
1062675e6881SMatthias Ringwald                 }
10637b7901d8SMatthias Ringwald                 l2cap_ertm_send_information_frame(channel, index, 0);   // final = 0
1064675e6881SMatthias Ringwald                 continue;
1065675e6881SMatthias Ringwald             }
1066212b6be2SMatthias Ringwald         }
1067675e6881SMatthias Ringwald 
1068d84e866fSMatthias Ringwald         if (channel->send_supervisor_frame_receiver_ready){
106978cd8a22SMatthias Ringwald             channel->send_supervisor_frame_receiver_ready = 0;
1070d2afdd38SMatthias Ringwald             log_info("Send S-Frame: RR %u, final %u", channel->req_seq, channel->set_final_bit_after_packet_with_poll_bit_set);
1071d2afdd38SMatthias 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);
1072d2afdd38SMatthias Ringwald             channel->set_final_bit_after_packet_with_poll_bit_set = 0;
107338f62777SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
1074675e6881SMatthias Ringwald             continue;
107538f62777SMatthias Ringwald         }
107662041d70SMatthias Ringwald         if (channel->send_supervisor_frame_receiver_ready_poll){
107778cd8a22SMatthias Ringwald             channel->send_supervisor_frame_receiver_ready_poll = 0;
107862041d70SMatthias Ringwald             log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
107962041d70SMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
108062041d70SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
108162041d70SMatthias Ringwald             continue;
108262041d70SMatthias Ringwald         }
10838f1c9639SMatthias Ringwald         if (channel->send_supervisor_frame_receiver_not_ready){
108478cd8a22SMatthias Ringwald             channel->send_supervisor_frame_receiver_not_ready = 0;
10858f1c9639SMatthias Ringwald             log_info("Send S-Frame: RNR %u", channel->req_seq);
10868f1c9639SMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
10878f1c9639SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
10888f1c9639SMatthias Ringwald             continue;
10898f1c9639SMatthias Ringwald         }
1090c7309e8dSMatthias Ringwald         if (channel->send_supervisor_frame_reject){
1091c7309e8dSMatthias Ringwald             channel->send_supervisor_frame_reject = 0;
1092c7309e8dSMatthias Ringwald             log_info("Send S-Frame: REJ %u", channel->req_seq);
1093c7309e8dSMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 0, 0, channel->req_seq);
1094c7309e8dSMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
1095c7309e8dSMatthias Ringwald             continue;
1096c7309e8dSMatthias Ringwald         }
1097df2191a7SMatthias Ringwald         if (channel->send_supervisor_frame_selective_reject){
1098df2191a7SMatthias Ringwald             channel->send_supervisor_frame_selective_reject = 0;
1099df2191a7SMatthias Ringwald             log_info("Send S-Frame: SREJ %u", channel->expected_tx_seq);
1100df2191a7SMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT, 0, 0, channel->expected_tx_seq);
1101df2191a7SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
1102df2191a7SMatthias Ringwald             continue;
1103df2191a7SMatthias Ringwald         }
11047b7901d8SMatthias Ringwald 
11057b7901d8SMatthias Ringwald         if (channel->srej_active){
11067b7901d8SMatthias Ringwald             int i;
11077b7901d8SMatthias Ringwald             for (i=0;i<channel->num_tx_buffers;i++){
11087b7901d8SMatthias Ringwald                 l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
11097b7901d8SMatthias Ringwald                 if (tx_state->retransmission_requested) {
11107b7901d8SMatthias Ringwald                     tx_state->retransmission_requested = 0;
1111d2afdd38SMatthias Ringwald                     uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set;
1112d2afdd38SMatthias Ringwald                     channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1113d2afdd38SMatthias Ringwald                     l2cap_ertm_send_information_frame(channel, i, final);
11147b7901d8SMatthias Ringwald                     break;
11157b7901d8SMatthias Ringwald                 }
11167b7901d8SMatthias Ringwald             }
11177b7901d8SMatthias Ringwald             if (i == channel->num_tx_buffers){
11187b7901d8SMatthias Ringwald                 // no retransmission request found
11197b7901d8SMatthias Ringwald                 channel->srej_active = 0;
11207b7901d8SMatthias Ringwald             } else {
11217b7901d8SMatthias Ringwald                 // packet was sent
11227b7901d8SMatthias Ringwald                 continue;
11237b7901d8SMatthias Ringwald             }
11247b7901d8SMatthias Ringwald         }
112538f62777SMatthias Ringwald #endif
112638f62777SMatthias Ringwald 
11272cd0be45Smatthias.ringwald     }
112809e9d05bSMatthias Ringwald #endif
1129da886c03S[email protected] 
1130cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1131efedfb4cSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1132efedfb4cSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
11337f107edaSMatthias Ringwald         uint8_t  * acl_buffer;
11347f107edaSMatthias Ringwald         uint8_t  * l2cap_payload;
11357f107edaSMatthias Ringwald         uint16_t pos;
11367f107edaSMatthias Ringwald         uint16_t payload_size;
1137efedfb4cSMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1138efedfb4cSMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1139efedfb4cSMatthias Ringwald         switch (channel->state){
11405cb87675SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
11415cb87675SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
11425cb87675SMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
11435cb87675SMatthias Ringwald                 // le psm, source cid, mtu, mps, initial credits
11441b8b8d05SMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
114563f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
114663f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
114763f0ac45SMatthias 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);
11485cb87675SMatthias Ringwald                 break;
114923017473SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
115023017473SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
115123017473SMatthias Ringwald                 // TODO: support larger MPS
115223017473SMatthias Ringwald                 channel->state = L2CAP_STATE_OPEN;
115363f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
115463f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
115563f0ac45SMatthias 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);
115664e11ca9SMatthias Ringwald                 // notify client
115744276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0);
115823017473SMatthias Ringwald                 break;
1159e7d0c9aaSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
1160e7d0c9aaSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1161e7d0c9aaSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
116263f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
1163e7d0c9aaSMatthias Ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1164e7d0c9aaSMatthias Ringwald                 l2cap_stop_rtx(channel);
1165e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1166e7d0c9aaSMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
1167e7d0c9aaSMatthias Ringwald                 break;
11687f107edaSMatthias Ringwald             case L2CAP_STATE_OPEN:
116985aeef60SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
117085aeef60SMatthias Ringwald 
117185aeef60SMatthias Ringwald                 // send credits
117285aeef60SMatthias Ringwald                 if (channel->new_credits_incoming){
117385aeef60SMatthias Ringwald                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
117485aeef60SMatthias Ringwald                     channel->local_sig_id = l2cap_next_sig_id();
117585aeef60SMatthias Ringwald                     uint16_t new_credits = channel->new_credits_incoming;
117685aeef60SMatthias Ringwald                     channel->new_credits_incoming = 0;
117785aeef60SMatthias Ringwald                     channel->credits_incoming += new_credits;
117885aeef60SMatthias Ringwald                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
117985aeef60SMatthias Ringwald                     break;
118085aeef60SMatthias Ringwald                 }
118185aeef60SMatthias Ringwald 
118285aeef60SMatthias Ringwald                 // send data
11837f107edaSMatthias Ringwald                 if (!channel->send_sdu_buffer) break;
11847f107edaSMatthias Ringwald                 if (!channel->credits_outgoing) break;
118585aeef60SMatthias Ringwald 
11867f107edaSMatthias Ringwald                 // send part of SDU
11877f107edaSMatthias Ringwald                 hci_reserve_packet_buffer();
11887f107edaSMatthias Ringwald                 acl_buffer = hci_get_outgoing_packet_buffer();
11897f107edaSMatthias Ringwald                 l2cap_payload = acl_buffer + 8;
11907f107edaSMatthias Ringwald                 pos = 0;
11917f107edaSMatthias Ringwald                 if (!channel->send_sdu_pos){
11927f107edaSMatthias Ringwald                     // store SDU len
11937f107edaSMatthias Ringwald                     channel->send_sdu_pos += 2;
11947f107edaSMatthias Ringwald                     little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
11957f107edaSMatthias Ringwald                     pos += 2;
11967f107edaSMatthias Ringwald                 }
11977f107edaSMatthias Ringwald                 payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
119885aeef60SMatthias Ringwald                 log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
11997f107edaSMatthias Ringwald                 memcpy(&l2cap_payload[pos], &channel->send_sdu_buffer[channel->send_sdu_pos-2], payload_size); // -2 for virtual SDU len
12007f107edaSMatthias Ringwald                 pos += payload_size;
12017f107edaSMatthias Ringwald                 channel->send_sdu_pos += payload_size;
1202f511cefaSMatthias Ringwald                 l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
12037f107edaSMatthias Ringwald                 // done
12047f107edaSMatthias Ringwald 
120585aeef60SMatthias Ringwald                 channel->credits_outgoing--;
12067f107edaSMatthias Ringwald 
12077f107edaSMatthias Ringwald                 if (channel->send_sdu_pos >= channel->send_sdu_len + 2){
12087f107edaSMatthias Ringwald                     channel->send_sdu_buffer = NULL;
120944276248SMatthias Ringwald                     // send done event
121044276248SMatthias Ringwald                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
121144276248SMatthias Ringwald                     // inform about can send now
121244276248SMatthias Ringwald                     l2cap_le_notify_channel_can_send(channel);
12137f107edaSMatthias Ringwald                 }
12147f107edaSMatthias Ringwald                 hci_send_acl_packet_buffer(8 + pos);
12157f107edaSMatthias Ringwald                 break;
1216828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1217828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1218828a7f7aSMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
1219828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1220828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1221828a7f7aSMatthias Ringwald                 break;
1222828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1223828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1224828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1225828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1226828a7f7aSMatthias Ringwald                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
1227828a7f7aSMatthias Ringwald                 break;
1228efedfb4cSMatthias Ringwald             default:
1229efedfb4cSMatthias Ringwald                 break;
1230efedfb4cSMatthias Ringwald         }
1231efedfb4cSMatthias Ringwald     }
123209e9d05bSMatthias Ringwald #endif
1233efedfb4cSMatthias Ringwald 
123409e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
1235da886c03S[email protected]     // send l2cap con paramter update if necessary
1236da886c03S[email protected]     hci_connections_get_iterator(&it);
1237665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
1238665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
12395d14fa8fSMatthias Ringwald         if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue;
1240b68d7bc3SMatthias Ringwald         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
1241da886c03S[email protected]         switch (connection->le_con_parameter_update_state){
1242b68d7bc3SMatthias Ringwald             case CON_PARAMETER_UPDATE_SEND_REQUEST:
1243b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1244b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier,
1245b68d7bc3SMatthias Ringwald                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
1246b68d7bc3SMatthias Ringwald                 break;
1247da886c03S[email protected]             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
1248b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
1249b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
1250da886c03S[email protected]                 break;
1251da886c03S[email protected]             case CON_PARAMETER_UPDATE_DENY:
1252b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1253b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
1254da886c03S[email protected]                 break;
1255da886c03S[email protected]             default:
1256da886c03S[email protected]                 break;
1257da886c03S[email protected]         }
1258da886c03S[email protected]     }
12594d7157c3S[email protected] #endif
1260da886c03S[email protected] 
126122c29ab4SMatthias Ringwald     // log_info("l2cap_run: exit");
12622cd0be45Smatthias.ringwald }
12632cd0be45Smatthias.ringwald 
126409e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1265fc64f94aSMatthias Ringwald static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
12662df5dadcS[email protected]     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
12675533f01eS[email protected]         log_info("l2cap_handle_connection_complete expected state");
12682df5dadcS[email protected]         // success, start l2cap handshake
1269fc64f94aSMatthias Ringwald         channel->con_handle = con_handle;
12702df5dadcS[email protected]         // check remote SSP feature first
12712df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
12722df5dadcS[email protected]     }
12732df5dadcS[email protected] }
12742df5dadcS[email protected] 
12751b9cb13dSMatthias Ringwald static void l2cap_ready_to_connect(l2cap_channel_t * channel){
12761b9cb13dSMatthias Ringwald 
12771b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
127827e0774aSMatthias Ringwald     // assumption: outgoing connection
12791b9cb13dSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
12801b9cb13dSMatthias Ringwald     if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
12811b9cb13dSMatthias Ringwald         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
12821b9cb13dSMatthias Ringwald         channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
12831b9cb13dSMatthias Ringwald         return;
12841b9cb13dSMatthias Ringwald     }
12851b9cb13dSMatthias Ringwald #endif
12861b9cb13dSMatthias Ringwald 
12871b9cb13dSMatthias Ringwald     // fine, go ahead
12881b9cb13dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
12891b9cb13dSMatthias Ringwald }
12901b9cb13dSMatthias Ringwald 
12912df5dadcS[email protected] static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
12922df5dadcS[email protected]     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
12932df5dadcS[email protected] 
12942df5dadcS[email protected]     // we have been waiting for remote supported features, if both support SSP,
1295ac301f95S[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));
1296fc64f94aSMatthias Ringwald     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
12972df5dadcS[email protected]         // request security level 2
12982df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
1299fc64f94aSMatthias Ringwald         gap_request_security_level(channel->con_handle, LEVEL_2);
13002df5dadcS[email protected]         return;
13012df5dadcS[email protected]     }
13021b9cb13dSMatthias Ringwald 
13031b9cb13dSMatthias Ringwald     l2cap_ready_to_connect(channel);
13042df5dadcS[email protected] }
130509e9d05bSMatthias Ringwald #endif
13062df5dadcS[email protected] 
130709e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
1308da144af5SMatthias 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,
1309da144af5SMatthias Ringwald     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
1310da144af5SMatthias Ringwald 
1311da144af5SMatthias Ringwald     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1312da144af5SMatthias Ringwald     if (!channel) {
1313da144af5SMatthias Ringwald         return NULL;
1314da144af5SMatthias Ringwald     }
1315da144af5SMatthias Ringwald 
1316da144af5SMatthias Ringwald      // Init memory (make valgrind happy)
1317da144af5SMatthias Ringwald     memset(channel, 0, sizeof(l2cap_channel_t));
1318da144af5SMatthias Ringwald 
1319da144af5SMatthias Ringwald     // fill in
1320da144af5SMatthias Ringwald     channel->packet_handler = packet_handler;
1321da144af5SMatthias Ringwald     bd_addr_copy(channel->address, address);
1322da144af5SMatthias Ringwald     channel->address_type = address_type;
1323da144af5SMatthias Ringwald     channel->psm = psm;
1324da144af5SMatthias Ringwald     channel->local_mtu  = local_mtu;
1325da144af5SMatthias Ringwald     channel->remote_mtu = L2CAP_MINIMAL_MTU;
1326da144af5SMatthias Ringwald     channel->required_security_level = security_level;
1327da144af5SMatthias Ringwald 
1328da144af5SMatthias Ringwald     //
1329da144af5SMatthias Ringwald     channel->local_cid = l2cap_next_local_cid();
1330da144af5SMatthias Ringwald     channel->con_handle = 0;
1331da144af5SMatthias Ringwald 
1332da144af5SMatthias Ringwald     // set initial state
1333da144af5SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
1334da144af5SMatthias Ringwald     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
1335da144af5SMatthias Ringwald     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
1336da144af5SMatthias Ringwald     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
133738f62777SMatthias Ringwald 
1338da144af5SMatthias Ringwald     return channel;
1339da144af5SMatthias Ringwald }
134009e9d05bSMatthias Ringwald #endif
134109e9d05bSMatthias Ringwald 
134209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1343da144af5SMatthias Ringwald 
13449077cb15SMatthias Ringwald /**
13459077cb15SMatthias Ringwald  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
13469077cb15SMatthias Ringwald  * @param packet_handler
13479077cb15SMatthias Ringwald  * @param address
13489077cb15SMatthias Ringwald  * @param psm
13499077cb15SMatthias Ringwald  * @param mtu
13509077cb15SMatthias Ringwald  * @param local_cid
13519077cb15SMatthias Ringwald  */
13529077cb15SMatthias Ringwald 
13539d139fbaSMatthias 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){
13549d139fbaSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
13559d139fbaSMatthias Ringwald     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1356da144af5SMatthias Ringwald 
13579d139fbaSMatthias 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);
1358da144af5SMatthias Ringwald 
1359da144af5SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
1360fc64f94aSMatthias Ringwald     if (!channel) {
13619077cb15SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
13629077cb15SMatthias Ringwald     }
13639077cb15SMatthias Ringwald 
13641b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
13651b9cb13dSMatthias Ringwald     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
13661b9cb13dSMatthias Ringwald #endif
13671b9cb13dSMatthias Ringwald 
13689077cb15SMatthias Ringwald     // add to connections list
1369fc64f94aSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
13709077cb15SMatthias Ringwald 
13719077cb15SMatthias Ringwald     // store local_cid
13729077cb15SMatthias Ringwald     if (out_local_cid){
1373fc64f94aSMatthias Ringwald        *out_local_cid = channel->local_cid;
13749077cb15SMatthias Ringwald     }
13759077cb15SMatthias Ringwald 
13769077cb15SMatthias Ringwald     // check if hci connection is already usable
13779077cb15SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
13789077cb15SMatthias Ringwald     if (conn){
1379add0254bSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
1380fc64f94aSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
13819077cb15SMatthias Ringwald         // check if remote supported fearures are already received
13829077cb15SMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
1383fc64f94aSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
13849077cb15SMatthias Ringwald         }
13859077cb15SMatthias Ringwald     }
13869077cb15SMatthias Ringwald 
13879077cb15SMatthias Ringwald     l2cap_run();
13889077cb15SMatthias Ringwald 
13899077cb15SMatthias Ringwald     return 0;
13909077cb15SMatthias Ringwald }
13919077cb15SMatthias Ringwald 
13921b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
13937b181629SMatthias Ringwald 
1394843bae5dSMatthias Ringwald static uint8_t l2cap_ertm_validate_local_config(uint8_t max_transmit, uint16_t retransmission_timeout_ms, uint16_t monitor_timeout_ms,
1395843bae5dSMatthias Ringwald     uint16_t local_mtu, uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size){
1396843bae5dSMatthias Ringwald 
13972b70d705SMatthias Ringwald     UNUSED(buffer);
13982b70d705SMatthias Ringwald     UNUSED(size);
13992b70d705SMatthias Ringwald 
14002b70d705SMatthias Ringwald     uint8_t result = ERROR_CODE_SUCCESS;
14012b70d705SMatthias Ringwald     if (max_transmit < 1){
14022b70d705SMatthias Ringwald         log_error("max_transmit must be >= 1");
14032b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
14042b70d705SMatthias Ringwald     }
14052b70d705SMatthias Ringwald     if (retransmission_timeout_ms < 2000){
14062b70d705SMatthias Ringwald         log_error("retransmission_timeout_ms must be >= 2000 ms");
14072b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
14082b70d705SMatthias Ringwald     }
14092b70d705SMatthias Ringwald     if (monitor_timeout_ms < 12000){
14102b70d705SMatthias Ringwald         log_error("monitor_timeout_ms must be >= 12000 ms");
14112b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
14122b70d705SMatthias Ringwald     }
1413843bae5dSMatthias Ringwald     if (local_mtu < 48){
1414843bae5dSMatthias Ringwald         log_error("local_mtu must be >= 48");
1415843bae5dSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
1416843bae5dSMatthias Ringwald     }
14172b70d705SMatthias Ringwald     if (num_rx_buffers < 1){
14182b70d705SMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
14192b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
14202b70d705SMatthias Ringwald     }
14212b70d705SMatthias Ringwald     if (num_tx_buffers < 1){
14222b70d705SMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
14232b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
14242b70d705SMatthias Ringwald     }
14252b70d705SMatthias Ringwald     return result;
14262b70d705SMatthias Ringwald }
14272b70d705SMatthias Ringwald 
1428843bae5dSMatthias Ringwald static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, int ertm_mandatory, uint8_t max_transmit, uint16_t retransmission_timeout_ms,
1429843bae5dSMatthias 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){
14307b181629SMatthias Ringwald 
14317b181629SMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
14327b181629SMatthias Ringwald     channel->ertm_mandatory = ertm_mandatory;
1433bbc0a9e7SMatthias Ringwald     channel->local_max_transmit = max_transmit;
1434bbc0a9e7SMatthias Ringwald     channel->local_retransmission_timeout_ms = retransmission_timeout_ms;
1435bbc0a9e7SMatthias Ringwald     channel->local_monitor_timeout_ms = monitor_timeout_ms;
1436843bae5dSMatthias Ringwald     channel->local_mtu = local_mtu;
14377b181629SMatthias Ringwald     channel->num_rx_buffers = num_rx_buffers;
14387b181629SMatthias Ringwald     channel->num_tx_buffers = num_tx_buffers;
14397b181629SMatthias Ringwald 
1440843bae5dSMatthias Ringwald     // align buffer to 16-byte boundary, just in case
1441843bae5dSMatthias Ringwald     int bytes_till_alignment = 16 - (((uintptr_t) buffer) & 0x0f);
1442843bae5dSMatthias Ringwald     buffer += bytes_till_alignment;
1443843bae5dSMatthias Ringwald     size   -= bytes_till_alignment;
1444843bae5dSMatthias Ringwald 
1445843bae5dSMatthias Ringwald     // setup state buffers
14467b181629SMatthias Ringwald     uint32_t pos = 0;
14477b181629SMatthias Ringwald     channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) &buffer[pos];
14487b181629SMatthias Ringwald     pos += num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
14497b181629SMatthias Ringwald     channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) &buffer[pos];
14507b181629SMatthias Ringwald     pos += num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
1451843bae5dSMatthias Ringwald 
1452843bae5dSMatthias Ringwald     // setup reassembly buffer
1453843bae5dSMatthias Ringwald     channel->reassembly_buffer = &buffer[pos];
1454843bae5dSMatthias Ringwald     pos += local_mtu;
1455843bae5dSMatthias Ringwald 
1456843bae5dSMatthias Ringwald     // divide rest of data equally
1457843bae5dSMatthias Ringwald     channel->local_mps = (size - pos) / (num_rx_buffers + num_tx_buffers);
1458843bae5dSMatthias Ringwald     log_info("Local MPS: %u", channel->local_mtu);
14597b181629SMatthias Ringwald     channel->rx_packets_data = &buffer[pos];
14607b181629SMatthias Ringwald     pos += num_rx_buffers * channel->local_mtu;
14617b181629SMatthias Ringwald     channel->tx_packets_data = &buffer[pos];
14627b181629SMatthias Ringwald }
14637b181629SMatthias Ringwald 
1464501329faSMatthias Ringwald uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
1465501329faSMatthias Ringwald     int ertm_mandatory, uint8_t max_transmit, uint16_t retransmission_timeout_ms, uint16_t monitor_timeout_ms,
1466843bae5dSMatthias 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){
1467501329faSMatthias Ringwald 
1468843bae5dSMatthias Ringwald     log_info("L2CAP_CREATE_CHANNEL addr %s, psm 0x%x, local mtu %u", bd_addr_to_str(address), psm, local_mtu);
14691b9cb13dSMatthias Ringwald 
14702b70d705SMatthias Ringwald     // validate local config
1471843bae5dSMatthias 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);
14722b70d705SMatthias Ringwald     if (result) return result;
14732b70d705SMatthias Ringwald 
1474501329faSMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
14751b9cb13dSMatthias Ringwald     if (!channel) {
14761b9cb13dSMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
14771b9cb13dSMatthias Ringwald     }
14781b9cb13dSMatthias Ringwald 
14797b181629SMatthias Ringwald     // configure ERTM
14807b181629SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_mandatory, max_transmit, retransmission_timeout_ms,
1481843bae5dSMatthias Ringwald         local_mtu, monitor_timeout_ms, num_tx_buffers, num_rx_buffers, buffer, size);
14821b9cb13dSMatthias Ringwald 
14831b9cb13dSMatthias Ringwald     // add to connections list
14841b9cb13dSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
14851b9cb13dSMatthias Ringwald 
14861b9cb13dSMatthias Ringwald     // store local_cid
14871b9cb13dSMatthias Ringwald     if (out_local_cid){
14881b9cb13dSMatthias Ringwald        *out_local_cid = channel->local_cid;
14891b9cb13dSMatthias Ringwald     }
14901b9cb13dSMatthias Ringwald 
14911b9cb13dSMatthias Ringwald     // check if hci connection is already usable
14921b9cb13dSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
14931b9cb13dSMatthias Ringwald     if (conn){
14941b9cb13dSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
14951b9cb13dSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
14961b9cb13dSMatthias Ringwald         // check if remote supported fearures are already received
14971b9cb13dSMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
14981b9cb13dSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
14991b9cb13dSMatthias Ringwald         }
15001b9cb13dSMatthias Ringwald     }
15011b9cb13dSMatthias Ringwald 
15021b9cb13dSMatthias Ringwald     l2cap_run();
15031b9cb13dSMatthias Ringwald 
15041b9cb13dSMatthias Ringwald     return 0;
15051b9cb13dSMatthias Ringwald }
15061b9cb13dSMatthias Ringwald #endif
15071b9cb13dSMatthias Ringwald 
1508ce8f182eSMatthias Ringwald void
1509ce8f182eSMatthias Ringwald l2cap_disconnect(uint16_t local_cid, uint8_t reason){
1510e0abb8e7S[email protected]     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
1511b35f641cSmatthias.ringwald     // find channel for local_cid
1512b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1513f62db1e3Smatthias.ringwald     if (channel) {
1514e7ff783cSmatthias.ringwald         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1515f62db1e3Smatthias.ringwald     }
15162cd0be45Smatthias.ringwald     // process
15172cd0be45Smatthias.ringwald     l2cap_run();
151843625864Smatthias.ringwald }
15191e6aba47Smatthias.ringwald 
1520afde0c52Smatthias.ringwald static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
1521665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1522665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1523665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1524665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1525058e3d6bSMatthias Ringwald         if ( bd_addr_cmp( channel->address, address) != 0) continue;
1526c22aecc9S[email protected]         // channel for this address found
1527c22aecc9S[email protected]         switch (channel->state){
1528c22aecc9S[email protected]             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
1529c22aecc9S[email protected]             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1530afde0c52Smatthias.ringwald                 // failure, forward error code
1531afde0c52Smatthias.ringwald                 l2cap_emit_channel_opened(channel, status);
1532afde0c52Smatthias.ringwald                 // discard channel
15339dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
1534665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1535d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
1536c22aecc9S[email protected]                 break;
1537c22aecc9S[email protected]             default:
1538c22aecc9S[email protected]                 break;
1539afde0c52Smatthias.ringwald         }
1540afde0c52Smatthias.ringwald     }
1541afde0c52Smatthias.ringwald }
1542afde0c52Smatthias.ringwald 
1543afde0c52Smatthias.ringwald static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
1544665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1545665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1546665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1547665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1548058e3d6bSMatthias Ringwald         if ( ! bd_addr_cmp( channel->address, address) ){
15492df5dadcS[email protected]             l2cap_handle_connection_complete(handle, channel);
1550afde0c52Smatthias.ringwald         }
1551afde0c52Smatthias.ringwald     }
15526fdcc387Smatthias.ringwald     // process
15536fdcc387Smatthias.ringwald     l2cap_run();
1554afde0c52Smatthias.ringwald }
155509e9d05bSMatthias Ringwald #endif
1556b448a0e7Smatthias.ringwald 
155733c40538SMatthias Ringwald static void l2cap_notify_channel_can_send(void){
155809e9d05bSMatthias Ringwald 
155909e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
156033c40538SMatthias Ringwald     btstack_linked_list_iterator_t it;
156133c40538SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
156233c40538SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
156333c40538SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
156433c40538SMatthias Ringwald         if (!channel->waiting_for_can_send_now) continue;
1565fc64f94aSMatthias Ringwald         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
156633c40538SMatthias Ringwald         channel->waiting_for_can_send_now = 0;
156734e7e577SMatthias Ringwald         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
156833c40538SMatthias Ringwald     }
156909e9d05bSMatthias Ringwald #endif
157044276248SMatthias Ringwald 
15712125de09SMatthias Ringwald     int i;
15722125de09SMatthias Ringwald     for (i=0;i<L2CAP_FIXED_CHANNEL_TABLE_SIZE;i++){
1573773c4106SMatthias Ringwald         if (!fixed_channels[i].callback) continue;
15742125de09SMatthias Ringwald         if (!fixed_channels[i].waiting_for_can_send_now) continue;
157535454696SMatthias Ringwald         int can_send = 0;
157634e7e577SMatthias Ringwald         if (l2cap_fixed_channel_table_index_is_le(i)){
157735454696SMatthias Ringwald #ifdef ENABLE_BLE
157834e7e577SMatthias Ringwald             can_send = hci_can_send_acl_le_packet_now();
157935454696SMatthias Ringwald #endif
158034e7e577SMatthias Ringwald         } else {
158135454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
158234e7e577SMatthias Ringwald             can_send = hci_can_send_acl_classic_packet_now();
158335454696SMatthias Ringwald #endif
158434e7e577SMatthias Ringwald         }
158534e7e577SMatthias Ringwald         if (!can_send) continue;
158634e7e577SMatthias Ringwald         fixed_channels[i].waiting_for_can_send_now = 0;
158734e7e577SMatthias Ringwald         l2cap_emit_can_send_now(fixed_channels[i].callback, l2cap_fixed_channel_table_channel_id_for_index(i));
15882125de09SMatthias Ringwald     }
158933c40538SMatthias Ringwald }
159033c40538SMatthias Ringwald 
1591d9a7306aSMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
1592afde0c52Smatthias.ringwald 
15939ec2630cSMatthias Ringwald     UNUSED(packet_type);
15949ec2630cSMatthias Ringwald     UNUSED(cid);
15959ec2630cSMatthias Ringwald     UNUSED(size);
15969ec2630cSMatthias Ringwald 
1597afde0c52Smatthias.ringwald     bd_addr_t address;
1598afde0c52Smatthias.ringwald     hci_con_handle_t handle;
15992d00edd4Smatthias.ringwald     int hci_con_used;
160009e9d05bSMatthias Ringwald     btstack_linked_list_iterator_t it;
160109e9d05bSMatthias Ringwald 
160209e9d05bSMatthias Ringwald     // avoid unused warnings
1603f3963406SMatthias Ringwald     UNUSED(address);
1604f3963406SMatthias Ringwald     UNUSED(hci_con_used);
1605f3963406SMatthias Ringwald     UNUSED(it);
1606f22209dfSMatthias Ringwald     UNUSED(handle);
1607afde0c52Smatthias.ringwald 
16080e2df43fSMatthias Ringwald     switch(hci_event_packet_get_type(packet)){
1609afde0c52Smatthias.ringwald 
161009e9d05bSMatthias Ringwald         // Notify channel packet handler if they can send now
161109e9d05bSMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
161209e9d05bSMatthias Ringwald         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
161309e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
161409e9d05bSMatthias Ringwald             l2cap_notify_channel_can_send();
161509e9d05bSMatthias Ringwald             break;
161609e9d05bSMatthias Ringwald 
161709e9d05bSMatthias Ringwald         case HCI_EVENT_COMMAND_STATUS:
161809e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
161909e9d05bSMatthias Ringwald             break;
162009e9d05bSMatthias Ringwald 
162109e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1622afde0c52Smatthias.ringwald         // handle connection complete events
1623afde0c52Smatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
1624724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], address);
1625afde0c52Smatthias.ringwald             if (packet[2] == 0){
1626f8fbdce0SMatthias Ringwald                 handle = little_endian_read_16(packet, 3);
1627afde0c52Smatthias.ringwald                 l2cap_handle_connection_success_for_addr(address, handle);
1628afde0c52Smatthias.ringwald             } else {
1629afde0c52Smatthias.ringwald                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
1630afde0c52Smatthias.ringwald             }
1631afde0c52Smatthias.ringwald             break;
1632afde0c52Smatthias.ringwald 
1633afde0c52Smatthias.ringwald         // handle successful create connection cancel command
1634afde0c52Smatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
1635073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
1636afde0c52Smatthias.ringwald                 if (packet[5] == 0){
1637724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[6], address);
1638afde0c52Smatthias.ringwald                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
1639afde0c52Smatthias.ringwald                     l2cap_handle_connection_failed_for_addr(address, 0x16);
164003cfbabcSmatthias.ringwald                 }
16411e6aba47Smatthias.ringwald             }
164239d59809Smatthias.ringwald             l2cap_run();    // try sending signaling packets first
164339d59809Smatthias.ringwald             break;
164409e9d05bSMatthias Ringwald #endif
164527a923d0Smatthias.ringwald 
16461e6aba47Smatthias.ringwald         // handle disconnection complete events
1647afde0c52Smatthias.ringwald         case HCI_EVENT_DISCONNECTION_COMPLETE:
1648c22aecc9S[email protected]             // send l2cap disconnect events for all channels on this handle and free them
164909e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1650d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1651665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1652665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1653665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1654fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
165515ec09bbSmatthias.ringwald                 l2cap_emit_channel_closed(channel);
16569dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
1657665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1658d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
165927a923d0Smatthias.ringwald             }
166009e9d05bSMatthias Ringwald #endif
1661a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1662d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1663991fea48SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1664991fea48SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1665991fea48SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1666991fea48SMatthias Ringwald                 if (channel->con_handle != handle) continue;
1667991fea48SMatthias Ringwald                 l2cap_emit_channel_closed(channel);
1668991fea48SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1669991fea48SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
1670991fea48SMatthias Ringwald             }
1671991fea48SMatthias Ringwald #endif
1672afde0c52Smatthias.ringwald             break;
1673fcadd0caSmatthias.ringwald 
1674ee091cf1Smatthias.ringwald         // HCI Connection Timeouts
167509e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1676afde0c52Smatthias.ringwald         case L2CAP_EVENT_TIMEOUT_CHECK:
1677f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
1678bd04d84aSMatthias Ringwald             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
167980ca58a0Smatthias.ringwald             if (hci_authentication_active_for_handle(handle)) break;
16802d00edd4Smatthias.ringwald             hci_con_used = 0;
1681665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1682665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1683665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1684fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
16852d00edd4Smatthias.ringwald                 hci_con_used = 1;
1686c22aecc9S[email protected]                 break;
1687ee091cf1Smatthias.ringwald             }
16882d00edd4Smatthias.ringwald             if (hci_con_used) break;
1689d94d3cafS[email protected]             if (!hci_can_send_command_packet_now()) break;
16909edc8742Smatthias.ringwald             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
1691afde0c52Smatthias.ringwald             break;
1692ee091cf1Smatthias.ringwald 
1693df3354fcS[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1694f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1695665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1696665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1697665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1698fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
16992df5dadcS[email protected]                 l2cap_handle_remote_supported_features_received(channel);
1700df3354fcS[email protected]                 break;
1701df3354fcS[email protected]             }
1702c22aecc9S[email protected]             break;
1703df3354fcS[email protected] 
17045611a760SMatthias Ringwald         case GAP_EVENT_SECURITY_LEVEL:
1705f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
1706bd63148eS[email protected]             log_info("l2cap - security level update");
1707665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1708665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1709665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1710fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
17115533f01eS[email protected] 
1712bd63148eS[email protected]                 log_info("l2cap - state %u", channel->state);
1713bd63148eS[email protected] 
1714e569dfd9SMatthias Ringwald                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
17155533f01eS[email protected]                 gap_security_level_t required_level = channel->required_security_level;
17165533f01eS[email protected] 
1717df3354fcS[email protected]                 switch (channel->state){
1718df3354fcS[email protected]                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
17195533f01eS[email protected]                         if (actual_level >= required_level){
172052606043SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
172152606043SMatthias Ringwald                             // we need to know if ERTM is supported before sending a config response
172252606043SMatthias Ringwald                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
172352606043SMatthias Ringwald                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
172452606043SMatthias Ringwald                             channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
172552606043SMatthias Ringwald #else
1726f85a9399S[email protected]                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
172744276248SMatthias Ringwald                             l2cap_emit_incoming_connection(channel);
172852606043SMatthias Ringwald #endif
17291eb2563eS[email protected]                         } else {
1730775ecc36SMatthias Ringwald                             channel->reason = 0x0003; // security block
17311eb2563eS[email protected]                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
17321eb2563eS[email protected]                         }
1733df3354fcS[email protected]                         break;
1734df3354fcS[email protected] 
1735df3354fcS[email protected]                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
17365533f01eS[email protected]                         if (actual_level >= required_level){
17371b9cb13dSMatthias Ringwald                             l2cap_ready_to_connect(channel);
1738df3354fcS[email protected]                         } else {
1739df3354fcS[email protected]                             // disconnnect, authentication not good enough
1740df3354fcS[email protected]                             hci_disconnect_security_block(handle);
1741df3354fcS[email protected]                         }
1742df3354fcS[email protected]                         break;
1743df3354fcS[email protected] 
1744df3354fcS[email protected]                     default:
1745df3354fcS[email protected]                         break;
1746df3354fcS[email protected]                 }
1747f85a9399S[email protected]             }
1748f85a9399S[email protected]             break;
174909e9d05bSMatthias Ringwald #endif
1750f85a9399S[email protected] 
1751afde0c52Smatthias.ringwald         default:
1752afde0c52Smatthias.ringwald             break;
1753afde0c52Smatthias.ringwald     }
1754afde0c52Smatthias.ringwald 
1755bd63148eS[email protected]     l2cap_run();
17561e6aba47Smatthias.ringwald }
17571e6aba47Smatthias.ringwald 
1758e74c5f58SMatthias 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){
17594cf56b4aSmatthias.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."
17602b360848Smatthias.ringwald     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
17612b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].handle = handle;
17622b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].code = code;
17632b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].sig_id = sig_id;
1764e74c5f58SMatthias Ringwald         signaling_responses[signaling_responses_pending].cid = cid;
17652b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].data = data;
17662b360848Smatthias.ringwald         signaling_responses_pending++;
17672b360848Smatthias.ringwald         l2cap_run();
17682b360848Smatthias.ringwald     }
17692b360848Smatthias.ringwald }
17702b360848Smatthias.ringwald 
177109e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
177209e9d05bSMatthias Ringwald static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
177309e9d05bSMatthias Ringwald     channel->remote_sig_id = identifier;
177409e9d05bSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
177509e9d05bSMatthias Ringwald     l2cap_run();
177609e9d05bSMatthias Ringwald }
177709e9d05bSMatthias Ringwald 
1778b35f641cSmatthias.ringwald static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
1779645658c9Smatthias.ringwald 
17809da54300S[email protected]     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
1781645658c9Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
1782645658c9Smatthias.ringwald     if (!service) {
1783645658c9Smatthias.ringwald         // 0x0002 PSM not supported
1784e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
1785645658c9Smatthias.ringwald         return;
1786645658c9Smatthias.ringwald     }
1787645658c9Smatthias.ringwald 
17885061f3afS[email protected]     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
1789645658c9Smatthias.ringwald     if (!hci_connection) {
17902b360848Smatthias.ringwald         //
17919da54300S[email protected]         log_error("no hci_connection for handle %u", handle);
1792645658c9Smatthias.ringwald         return;
1793645658c9Smatthias.ringwald     }
17942bd8b7e7S[email protected] 
1795645658c9Smatthias.ringwald     // alloc structure
17969da54300S[email protected]     // log_info("l2cap_handle_connection_request register channel");
1797da144af5SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, hci_connection->address, BD_ADDR_TYPE_CLASSIC,
1798da144af5SMatthias Ringwald     psm, service->mtu, service->required_security_level);
17992b360848Smatthias.ringwald     if (!channel){
18002b360848Smatthias.ringwald         // 0x0004 No resources available
1801e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
18022b360848Smatthias.ringwald         return;
18032b360848Smatthias.ringwald     }
1804da144af5SMatthias Ringwald 
1805fc64f94aSMatthias Ringwald     channel->con_handle = handle;
1806b35f641cSmatthias.ringwald     channel->remote_cid = source_cid;
1807b1988dceSmatthias.ringwald     channel->remote_sig_id = sig_id;
1808645658c9Smatthias.ringwald 
1809f53da564S[email protected]     // limit local mtu to max acl packet length - l2cap header
18102985cb84Smatthias.ringwald     if (channel->local_mtu > l2cap_max_mtu()) {
18112985cb84Smatthias.ringwald         channel->local_mtu = l2cap_max_mtu();
18129775e25bSmatthias.ringwald     }
18139775e25bSmatthias.ringwald 
1814645658c9Smatthias.ringwald     // set initial state
1815df3354fcS[email protected]     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
1816a24785d0SMatthias Ringwald     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
1817e405ae81Smatthias.ringwald 
1818645658c9Smatthias.ringwald     // add to connections list
1819665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1820645658c9Smatthias.ringwald 
1821f85a9399S[email protected]     // assert security requirements
18221eb2563eS[email protected]     gap_request_security_level(handle, channel->required_security_level);
1823e405ae81Smatthias.ringwald }
1824645658c9Smatthias.ringwald 
1825ce8f182eSMatthias Ringwald void l2cap_accept_connection(uint16_t local_cid){
1826e0abb8e7S[email protected]     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
1827b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1828e405ae81Smatthias.ringwald     if (!channel) {
1829ce8f182eSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
1830e405ae81Smatthias.ringwald         return;
1831e405ae81Smatthias.ringwald     }
1832e405ae81Smatthias.ringwald 
183343ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
183443ec931dSMatthias Ringwald     // configure L2CAP Basic mode
183543ec931dSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
183643ec931dSMatthias Ringwald #endif
183743ec931dSMatthias Ringwald 
1838552d92a1Smatthias.ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
1839e405ae81Smatthias.ringwald 
1840552d92a1Smatthias.ringwald     // process
1841552d92a1Smatthias.ringwald     l2cap_run();
1842e405ae81Smatthias.ringwald }
1843645658c9Smatthias.ringwald 
184443ec931dSMatthias Ringwald 
184543ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1846843bae5dSMatthias Ringwald uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, int ertm_mandatory, uint8_t max_transmit, uint16_t retransmission_timeout_ms,
1847843bae5dSMatthias 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){
1848501329faSMatthias Ringwald 
184943ec931dSMatthias Ringwald     log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
185043ec931dSMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
185143ec931dSMatthias Ringwald     if (!channel) {
185243ec931dSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
18532b70d705SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
185443ec931dSMatthias Ringwald     }
185543ec931dSMatthias Ringwald 
18562b70d705SMatthias Ringwald     // validate local config
1857843bae5dSMatthias 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);
18582b70d705SMatthias Ringwald     if (result) return result;
18592b70d705SMatthias Ringwald 
186043ec931dSMatthias Ringwald     // configure L2CAP ERTM
1861843bae5dSMatthias 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);
186243ec931dSMatthias Ringwald 
18637b181629SMatthias Ringwald     // continue
186443ec931dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
186543ec931dSMatthias Ringwald 
186643ec931dSMatthias Ringwald     // process
186743ec931dSMatthias Ringwald     l2cap_run();
18682b70d705SMatthias Ringwald 
18692b70d705SMatthias Ringwald     return ERROR_CODE_SUCCESS;
187043ec931dSMatthias Ringwald }
18712a424812SMatthias Ringwald 
187267a3a5b7SMatthias Ringwald uint8_t l2cap_ertm_set_busy(uint16_t local_cid){
18738f1c9639SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
18748f1c9639SMatthias Ringwald     if (!channel) {
18758f1c9639SMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
18768f1c9639SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
18778f1c9639SMatthias Ringwald     }
18782bea1b8dSMatthias Ringwald     if (!channel->local_busy){
18792bea1b8dSMatthias Ringwald         channel->local_busy = 1;
18808f1c9639SMatthias Ringwald         channel->send_supervisor_frame_receiver_not_ready = 1;
18818f1c9639SMatthias Ringwald         l2cap_run();
18822bea1b8dSMatthias Ringwald     }
188367a3a5b7SMatthias Ringwald     return ERROR_CODE_SUCCESS;
188467a3a5b7SMatthias Ringwald }
188567a3a5b7SMatthias Ringwald 
188667a3a5b7SMatthias Ringwald uint8_t l2cap_ertm_set_ready(uint16_t local_cid){
18872bea1b8dSMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
18882bea1b8dSMatthias Ringwald     if (!channel) {
18892bea1b8dSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
18902bea1b8dSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
18912bea1b8dSMatthias Ringwald     }
18922bea1b8dSMatthias Ringwald     if (channel->local_busy){
18932bea1b8dSMatthias Ringwald         channel->local_busy = 0;
18942bea1b8dSMatthias Ringwald         channel->send_supervisor_frame_receiver_ready_poll = 1;
18952bea1b8dSMatthias Ringwald         l2cap_run();
18962bea1b8dSMatthias Ringwald     }
189767a3a5b7SMatthias Ringwald     return ERROR_CODE_SUCCESS;
189867a3a5b7SMatthias Ringwald }
189967a3a5b7SMatthias Ringwald 
19002a424812SMatthias Ringwald static void l2cap_ertm_handle_req_seq(l2cap_channel_t * l2cap_channel, uint8_t req_seq){
19012a424812SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
1902bc4521b7SMatthias Ringwald     while (1){
19032a424812SMatthias Ringwald         tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
1904bc4521b7SMatthias Ringwald         // calc delta
1905bc4521b7SMatthias Ringwald         int delta = (req_seq - tx_state->tx_seq) & 0x03f;
1906bc4521b7SMatthias Ringwald         if (delta == 0) break;  // all packets acknowledged
1907bc4521b7SMatthias Ringwald         if (delta > l2cap_channel->remote_tx_window_size) break;
1908bc4521b7SMatthias Ringwald 
1909bc4521b7SMatthias Ringwald         log_info("RR seq %u => packet with tx_seq %u done", req_seq, tx_state->tx_seq);
1910bc4521b7SMatthias Ringwald 
191162041d70SMatthias Ringwald         // stop retransmission timer
191262041d70SMatthias Ringwald         btstack_run_loop_remove_timer(&tx_state->retransmission_timer);
19132a424812SMatthias Ringwald         l2cap_channel->tx_read_index++;
19142a424812SMatthias Ringwald         if (l2cap_channel->tx_read_index >= l2cap_channel->num_rx_buffers){
19152a424812SMatthias Ringwald             l2cap_channel->tx_read_index = 0;
19162a424812SMatthias Ringwald         }
1917bc4521b7SMatthias Ringwald 
1918bc4521b7SMatthias Ringwald         // no unack packages
1919bc4521b7SMatthias Ringwald         if (l2cap_channel->tx_read_index == l2cap_channel->tx_write_index) break;
19202a424812SMatthias Ringwald     }
19212a424812SMatthias Ringwald }
192267a3a5b7SMatthias Ringwald 
19237b7901d8SMatthias Ringwald static l2cap_ertm_tx_packet_state_t * l2cap_ertm_get_tx_state(l2cap_channel_t * l2cap_channel, uint8_t tx_seq){
19247b7901d8SMatthias Ringwald     int i;
19257b7901d8SMatthias Ringwald     for (i=0;i<l2cap_channel->num_tx_buffers;i++){
19267b7901d8SMatthias Ringwald         l2cap_ertm_tx_packet_state_t * tx_state = &l2cap_channel->tx_packets_state[i];
19277b7901d8SMatthias Ringwald         if (tx_state->tx_seq == tx_seq) return tx_state;
19287b7901d8SMatthias Ringwald     }
19297b7901d8SMatthias Ringwald     return NULL;
19307b7901d8SMatthias Ringwald }
193143ec931dSMatthias Ringwald #endif
193243ec931dSMatthias Ringwald 
193343ec931dSMatthias Ringwald 
19347ef6a7bbSMatthias Ringwald void l2cap_decline_connection(uint16_t local_cid){
19357ef6a7bbSMatthias Ringwald     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
1936b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
1937e405ae81Smatthias.ringwald     if (!channel) {
1938ce8f182eSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
1939e405ae81Smatthias.ringwald         return;
1940e405ae81Smatthias.ringwald     }
1941e7ff783cSmatthias.ringwald     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
19427ef6a7bbSMatthias Ringwald     channel->reason = 0x04; // no resources available
1943e7ff783cSmatthias.ringwald     l2cap_run();
1944645658c9Smatthias.ringwald }
1945645658c9Smatthias.ringwald 
19467f02f414SMatthias Ringwald static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
1947b1988dceSmatthias.ringwald 
1948b1988dceSmatthias.ringwald     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1949b1988dceSmatthias.ringwald 
1950f8fbdce0SMatthias Ringwald     uint16_t flags = little_endian_read_16(command, 6);
195163a7246aSmatthias.ringwald     if (flags & 1) {
195263a7246aSmatthias.ringwald         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
195363a7246aSmatthias.ringwald     }
195463a7246aSmatthias.ringwald 
19552784b77dSmatthias.ringwald     // accept the other's configuration options
1956f8fbdce0SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
19573de7c0caSmatthias.ringwald     uint16_t pos     = 8;
19583de7c0caSmatthias.ringwald     while (pos < end_pos){
195963a7246aSmatthias.ringwald         uint8_t option_hint = command[pos] >> 7;
196063a7246aSmatthias.ringwald         uint8_t option_type = command[pos] & 0x7f;
19613844aeadSMatthias Ringwald         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
196263a7246aSmatthias.ringwald         pos++;
19631dc511deSmatthias.ringwald         uint8_t length = command[pos++];
19641dc511deSmatthias.ringwald         // MTU { type(8): 1, len(8):2, MTU(16) }
196563a7246aSmatthias.ringwald         if (option_type == 1 && length == 2){
1966f8fbdce0SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, pos);
19673844aeadSMatthias Ringwald             log_info("Remote MTU %u", channel->remote_mtu);
19689d139fbaSMatthias Ringwald             if (channel->remote_mtu > l2cap_max_mtu()){
19699d139fbaSMatthias Ringwald                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
19709d139fbaSMatthias Ringwald                 channel->remote_mtu = l2cap_max_mtu();
19719d139fbaSMatthias Ringwald             }
197263a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
197363a7246aSmatthias.ringwald         }
19740fe7a9d0S[email protected]         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
19750fe7a9d0S[email protected]         if (option_type == 2 && length == 2){
1976f8fbdce0SMatthias Ringwald             channel->flush_timeout = little_endian_read_16(command, pos);
19773844aeadSMatthias Ringwald             log_info("Flush timeout: %u ms", channel->flush_timeout);
19780fe7a9d0S[email protected]         }
1979f2fa388dSMatthias Ringwald 
19806dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
19816dca2a0cSMatthias Ringwald         // Retransmission and Flow Control Option
19826dca2a0cSMatthias Ringwald         if (option_type == 4 && length == 9){
19833232a1c6SMatthias Ringwald             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
1984ac8f1300SMatthias Ringwald             switch(channel->mode){
1985ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
198625cd60d3SMatthias Ringwald                     // Store remote config
1987bbc0a9e7SMatthias Ringwald                     channel->remote_tx_window_size = command[pos+1];
1988bbc0a9e7SMatthias Ringwald                     channel->remote_max_transmit   = command[pos+2];
1989bbc0a9e7SMatthias Ringwald                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
1990bbc0a9e7SMatthias Ringwald                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
19913844aeadSMatthias Ringwald                     channel->remote_mps = little_endian_read_16(command, pos + 7);
19923844aeadSMatthias Ringwald                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
1993bbc0a9e7SMatthias Ringwald                         channel->remote_tx_window_size,
1994bbc0a9e7SMatthias Ringwald                         channel->remote_max_transmit,
1995bbc0a9e7SMatthias Ringwald                         channel->remote_retransmission_timeout_ms,
19963844aeadSMatthias Ringwald                         channel->remote_monitor_timeout_ms,
19973844aeadSMatthias Ringwald                         channel->remote_mps);
199825cd60d3SMatthias Ringwald                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
199925cd60d3SMatthias Ringwald                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
200025cd60d3SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2001ac8f1300SMatthias Ringwald                     } else {
2002ac8f1300SMatthias Ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
2003ac8f1300SMatthias Ringwald                     }
2004ac8f1300SMatthias Ringwald                     break;
2005ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
2006ac8f1300SMatthias Ringwald                     switch (mode){
2007ac8f1300SMatthias Ringwald                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2008ac8f1300SMatthias Ringwald                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
2009ac8f1300SMatthias Ringwald                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
2010ac8f1300SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2011ac8f1300SMatthias Ringwald                             }
2012ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
2013ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
2014ac8f1300SMatthias Ringwald                             break;
2015ac8f1300SMatthias Ringwald                         default: // case L2CAP_CHANNEL_MODE_BASIC:
2016ac8f1300SMatthias Ringwald                             // TODO store and evaluate configuration
2017ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
2018ac8f1300SMatthias Ringwald                             break;
2019ac8f1300SMatthias Ringwald                     }
2020ac8f1300SMatthias Ringwald                     break;
2021ac8f1300SMatthias Ringwald                 default:
2022ac8f1300SMatthias Ringwald                     break;
2023ac8f1300SMatthias Ringwald             }
20243232a1c6SMatthias Ringwald         }
20256dca2a0cSMatthias Ringwald #endif
202663a7246aSmatthias.ringwald         // check for unknown options
202763a7246aSmatthias.ringwald         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
2028c177a91cS[email protected]             log_info("l2cap cid %u, unknown options", channel->local_cid);
202963a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
20301dc511deSmatthias.ringwald         }
20311dc511deSmatthias.ringwald         pos += length;
20321dc511deSmatthias.ringwald     }
20332784b77dSmatthias.ringwald }
20342784b77dSmatthias.ringwald 
2035f2fa388dSMatthias Ringwald static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
2036f2fa388dSMatthias Ringwald     log_info("l2cap_signaling_handle_configure_response");
20373232a1c6SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
20383232a1c6SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2039f2fa388dSMatthias Ringwald     uint16_t pos     = 10;
20403232a1c6SMatthias Ringwald     while (pos < end_pos){
20413232a1c6SMatthias Ringwald         uint8_t option_hint = command[pos] >> 7;
20423232a1c6SMatthias Ringwald         uint8_t option_type = command[pos] & 0x7f;
20433232a1c6SMatthias Ringwald         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
20443232a1c6SMatthias Ringwald         pos++;
20453232a1c6SMatthias Ringwald         uint8_t length = command[pos++];
20463232a1c6SMatthias Ringwald 
20473232a1c6SMatthias Ringwald         // Retransmission and Flow Control Option
20483232a1c6SMatthias Ringwald         if (option_type == 4 && length == 9){
2049ac8f1300SMatthias Ringwald             switch (channel->mode){
2050ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2051f2fa388dSMatthias Ringwald                     if (channel->ertm_mandatory){
2052ac8f1300SMatthias Ringwald                         // ??
2053f2fa388dSMatthias Ringwald                     } else {
2054ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
2055ac8f1300SMatthias Ringwald                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2056f2fa388dSMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
20573232a1c6SMatthias Ringwald                         }
20583232a1c6SMatthias Ringwald                     }
2059ac8f1300SMatthias Ringwald                     break;
2060ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
2061ac8f1300SMatthias Ringwald                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2062ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
2063ac8f1300SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2064ac8f1300SMatthias Ringwald                     }
2065ac8f1300SMatthias Ringwald                     break;
2066ac8f1300SMatthias Ringwald                 default:
2067ac8f1300SMatthias Ringwald                     break;
20683232a1c6SMatthias Ringwald             }
2069f2fa388dSMatthias Ringwald         }
20703232a1c6SMatthias Ringwald 
20713232a1c6SMatthias Ringwald         // check for unknown options
20723232a1c6SMatthias Ringwald         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
20733232a1c6SMatthias Ringwald             log_info("l2cap cid %u, unknown options", channel->local_cid);
20743232a1c6SMatthias Ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
20753232a1c6SMatthias Ringwald         }
20763232a1c6SMatthias Ringwald 
20773232a1c6SMatthias Ringwald         pos += length;
20783232a1c6SMatthias Ringwald     }
20793232a1c6SMatthias Ringwald #endif
20803232a1c6SMatthias Ringwald }
20813232a1c6SMatthias Ringwald 
2082fa8473a4Smatthias.ringwald static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
20839da54300S[email protected]     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
208473cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
208573cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
2086019f9b43SMatthias Ringwald     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
2087019f9b43SMatthias Ringwald     if (channel->state == L2CAP_STATE_OPEN) return 0;
2088fa8473a4Smatthias.ringwald     return 1;
2089fa8473a4Smatthias.ringwald }
2090fa8473a4Smatthias.ringwald 
2091fa8473a4Smatthias.ringwald 
20927f02f414SMatthias Ringwald static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
20931e6aba47Smatthias.ringwald 
209400d93d79Smatthias.ringwald     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
209500d93d79Smatthias.ringwald     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
209638e5900eSmatthias.ringwald     uint16_t result = 0;
20971e6aba47Smatthias.ringwald 
20989da54300S[email protected]     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
2099b35f641cSmatthias.ringwald 
21009a011532Smatthias.ringwald     // handle DISCONNECT REQUESTS seperately
21019a011532Smatthias.ringwald     if (code == DISCONNECTION_REQUEST){
21029a011532Smatthias.ringwald         switch (channel->state){
2103fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
21049a011532Smatthias.ringwald             case L2CAP_STATE_OPEN:
21052b83fb7dSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
21069a011532Smatthias.ringwald             case L2CAP_STATE_WAIT_DISCONNECT:
21079a011532Smatthias.ringwald                 l2cap_handle_disconnect_request(channel, identifier);
21089a011532Smatthias.ringwald                 break;
21099a011532Smatthias.ringwald 
21109a011532Smatthias.ringwald             default:
21119a011532Smatthias.ringwald                 // ignore in other states
21129a011532Smatthias.ringwald                 break;
21139a011532Smatthias.ringwald         }
21149a011532Smatthias.ringwald         return;
21159a011532Smatthias.ringwald     }
21169a011532Smatthias.ringwald 
211756081214Smatthias.ringwald     // @STATEMACHINE(l2cap)
21181e6aba47Smatthias.ringwald     switch (channel->state) {
21191e6aba47Smatthias.ringwald 
21201e6aba47Smatthias.ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
21211e6aba47Smatthias.ringwald             switch (code){
21221e6aba47Smatthias.ringwald                 case CONNECTION_RESPONSE:
21235932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2124f8fbdce0SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
212538e5900eSmatthias.ringwald                     switch (result) {
212638e5900eSmatthias.ringwald                         case 0:
2127169f8b28Smatthias.ringwald                             // successful connection
2128f8fbdce0SMatthias Ringwald                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2129fa8473a4Smatthias.ringwald                             channel->state = L2CAP_STATE_CONFIG;
213028ca2b46S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
213138e5900eSmatthias.ringwald                             break;
213238e5900eSmatthias.ringwald                         case 1:
21335932bd7cS[email protected]                             // connection pending. get some coffee, but start the ERTX
21345932bd7cS[email protected]                             l2cap_start_ertx(channel);
213538e5900eSmatthias.ringwald                             break;
213638e5900eSmatthias.ringwald                         default:
2137eb920dbeSmatthias.ringwald                             // channel closed
2138eb920dbeSmatthias.ringwald                             channel->state = L2CAP_STATE_CLOSED;
2139f32b992eSmatthias.ringwald                             // map l2cap connection response result to BTstack status enumeration
214038e5900eSmatthias.ringwald                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
2141eb920dbeSmatthias.ringwald 
2142eb920dbeSmatthias.ringwald                             // drop link key if security block
2143eb920dbeSmatthias.ringwald                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
214415a95bd5SMatthias Ringwald                                 gap_drop_link_key_for_bd_addr(channel->address);
2145eb920dbeSmatthias.ringwald                             }
2146eb920dbeSmatthias.ringwald 
2147eb920dbeSmatthias.ringwald                             // discard channel
2148665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2149d3a9df87Smatthias.ringwald                             btstack_memory_l2cap_channel_free(channel);
215038e5900eSmatthias.ringwald                             break;
21511e6aba47Smatthias.ringwald                     }
21521e6aba47Smatthias.ringwald                     break;
215338e5900eSmatthias.ringwald 
215438e5900eSmatthias.ringwald                 default:
21551e6aba47Smatthias.ringwald                     //@TODO: implement other signaling packets
215638e5900eSmatthias.ringwald                     break;
21571e6aba47Smatthias.ringwald             }
21581e6aba47Smatthias.ringwald             break;
21591e6aba47Smatthias.ringwald 
2160fa8473a4Smatthias.ringwald         case L2CAP_STATE_CONFIG:
2161f8fbdce0SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2162ae280e73Smatthias.ringwald             switch (code) {
2163ae280e73Smatthias.ringwald                 case CONFIGURE_REQUEST:
216428ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
2165ae280e73Smatthias.ringwald                     l2cap_signaling_handle_configure_request(channel, command);
216663a7246aSmatthias.ringwald                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
216763a7246aSmatthias.ringwald                         // only done if continuation not set
216863a7246aSmatthias.ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
216963a7246aSmatthias.ringwald                     }
2170ae280e73Smatthias.ringwald                     break;
21711e6aba47Smatthias.ringwald                 case CONFIGURE_RESPONSE:
21725932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2173f2fa388dSMatthias Ringwald                     l2cap_signaling_handle_configure_response(channel, result, command);
21745932bd7cS[email protected]                     switch (result){
21755932bd7cS[email protected]                         case 0: // success
21765932bd7cS[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
21775932bd7cS[email protected]                             break;
21785932bd7cS[email protected]                         case 4: // pending
21795932bd7cS[email protected]                             l2cap_start_ertx(channel);
21805932bd7cS[email protected]                             break;
21815932bd7cS[email protected]                         default:
2182a32d6a03SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2183a32d6a03SMatthias Ringwald                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
2184a32d6a03SMatthias Ringwald                                 // remote does not offer ertm but it's required
2185a32d6a03SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2186a32d6a03SMatthias Ringwald                                 break;
2187a32d6a03SMatthias Ringwald                             }
2188a32d6a03SMatthias Ringwald #endif
2189fe9d8984S[email protected]                             // retry on negative result
2190fe9d8984S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2191fe9d8984S[email protected]                             break;
2192fe9d8984S[email protected]                     }
21935a67bd4aSmatthias.ringwald                     break;
21945a67bd4aSmatthias.ringwald                 default:
21955a67bd4aSmatthias.ringwald                     break;
21961e6aba47Smatthias.ringwald             }
2197fa8473a4Smatthias.ringwald             if (l2cap_channel_ready_for_open(channel)){
2198fa8473a4Smatthias.ringwald                 // for open:
21995a67bd4aSmatthias.ringwald                 channel->state = L2CAP_STATE_OPEN;
2200fa8473a4Smatthias.ringwald                 l2cap_emit_channel_opened(channel, 0);
2201c8e4258aSmatthias.ringwald             }
2202c8e4258aSmatthias.ringwald             break;
2203f62db1e3Smatthias.ringwald 
2204f62db1e3Smatthias.ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
2205f62db1e3Smatthias.ringwald             switch (code) {
2206f62db1e3Smatthias.ringwald                 case DISCONNECTION_RESPONSE:
220727a923d0Smatthias.ringwald                     l2cap_finialize_channel_close(channel);
220827a923d0Smatthias.ringwald                     break;
22095a67bd4aSmatthias.ringwald                 default:
22105a67bd4aSmatthias.ringwald                     //@TODO: implement other signaling packets
22115a67bd4aSmatthias.ringwald                     break;
221227a923d0Smatthias.ringwald             }
221327a923d0Smatthias.ringwald             break;
221484836b65Smatthias.ringwald 
221584836b65Smatthias.ringwald         case L2CAP_STATE_CLOSED:
221684836b65Smatthias.ringwald             // @TODO handle incoming requests
221784836b65Smatthias.ringwald             break;
221884836b65Smatthias.ringwald 
221984836b65Smatthias.ringwald         case L2CAP_STATE_OPEN:
222084836b65Smatthias.ringwald             //@TODO: implement other signaling packets, e.g. re-configure
222184836b65Smatthias.ringwald             break;
222210642e45Smatthias.ringwald         default:
222310642e45Smatthias.ringwald             break;
222427a923d0Smatthias.ringwald     }
22259da54300S[email protected]     // log_info("new state %u", channel->state);
222627a923d0Smatthias.ringwald }
222727a923d0Smatthias.ringwald 
222800d93d79Smatthias.ringwald 
22297f02f414SMatthias Ringwald static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
223000d93d79Smatthias.ringwald 
22311b9cb13dSMatthias Ringwald     btstack_linked_list_iterator_t it;
22321b9cb13dSMatthias Ringwald 
223300d93d79Smatthias.ringwald     // get code, signalind identifier and command len
223400d93d79Smatthias.ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
223500d93d79Smatthias.ringwald     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
223600d93d79Smatthias.ringwald 
22371b9cb13dSMatthias Ringwald     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
22381b9cb13dSMatthias Ringwald     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_RESPONSE){
2239e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
224000d93d79Smatthias.ringwald         return;
224100d93d79Smatthias.ringwald     }
224200d93d79Smatthias.ringwald 
224300d93d79Smatthias.ringwald     // general commands without an assigned channel
224400d93d79Smatthias.ringwald     switch(code) {
224500d93d79Smatthias.ringwald 
224600d93d79Smatthias.ringwald         case CONNECTION_REQUEST: {
2247f8fbdce0SMatthias Ringwald             uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2248f8fbdce0SMatthias Ringwald             uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
224900d93d79Smatthias.ringwald             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
22502b83fb7dSmatthias.ringwald             return;
225100d93d79Smatthias.ringwald         }
225200d93d79Smatthias.ringwald 
22532b360848Smatthias.ringwald         case ECHO_REQUEST:
2254e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
22552b83fb7dSmatthias.ringwald             return;
225600d93d79Smatthias.ringwald 
225700d93d79Smatthias.ringwald         case INFORMATION_REQUEST: {
2258f8fbdce0SMatthias Ringwald             uint16_t infoType = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2259e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, infoType);
22602b83fb7dSmatthias.ringwald             return;
226100d93d79Smatthias.ringwald         }
226200d93d79Smatthias.ringwald 
22631b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
22641b9cb13dSMatthias Ringwald         case INFORMATION_RESPONSE: {
22651b9cb13dSMatthias Ringwald             hci_connection_t * connection = hci_connection_for_handle(handle);
22661b9cb13dSMatthias Ringwald             if (!connection) return;
22671b9cb13dSMatthias Ringwald             uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
22681b9cb13dSMatthias Ringwald             uint16_t result =  little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
22691b9cb13dSMatthias Ringwald             if (result != 0) return;
2270543b84e4SMatthias Ringwald             if (info_type != 0x02) return;
22711b9cb13dSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
22721b9cb13dSMatthias Ringwald             connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2273543b84e4SMatthias Ringwald             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
22741b9cb13dSMatthias Ringwald             // trigger connection request
22751b9cb13dSMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
22761b9cb13dSMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
22771b9cb13dSMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2278543b84e4SMatthias Ringwald                 if (channel->con_handle != handle) continue;
2279543b84e4SMatthias Ringwald                 // bail if ERTM was requested but is not supported
2280543b84e4SMatthias Ringwald                 if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2281f073f086SMatthias Ringwald                     if (channel->ertm_mandatory){
2282543b84e4SMatthias Ringwald                         // channel closed
2283543b84e4SMatthias Ringwald                         channel->state = L2CAP_STATE_CLOSED;
2284543b84e4SMatthias Ringwald                         // map l2cap connection response result to BTstack status enumeration
2285543b84e4SMatthias Ringwald                         l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTD);
2286543b84e4SMatthias Ringwald                         // discard channel
2287543b84e4SMatthias Ringwald                         btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2288543b84e4SMatthias Ringwald                         btstack_memory_l2cap_channel_free(channel);
2289543b84e4SMatthias Ringwald                         continue;
2290f073f086SMatthias Ringwald                     } else {
2291f073f086SMatthias Ringwald                         // fallback to Basic mode
2292f073f086SMatthias Ringwald                         channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2293f073f086SMatthias Ringwald                     }
2294543b84e4SMatthias Ringwald                 }
2295543b84e4SMatthias Ringwald                 // start connecting
22961b9cb13dSMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
22971b9cb13dSMatthias Ringwald                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
22981b9cb13dSMatthias Ringwald                 }
229952606043SMatthias Ringwald                 // respond to connection request
230052606043SMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
230152606043SMatthias Ringwald                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
230252606043SMatthias Ringwald                     l2cap_emit_incoming_connection(channel);
230352606043SMatthias Ringwald                 }
23041b9cb13dSMatthias Ringwald             }
23051b9cb13dSMatthias Ringwald             return;
23061b9cb13dSMatthias Ringwald         }
23071b9cb13dSMatthias Ringwald #endif
23081b9cb13dSMatthias Ringwald 
230900d93d79Smatthias.ringwald         default:
231000d93d79Smatthias.ringwald             break;
231100d93d79Smatthias.ringwald     }
231200d93d79Smatthias.ringwald 
231300d93d79Smatthias.ringwald 
231400d93d79Smatthias.ringwald     // Get potential destination CID
2315f8fbdce0SMatthias Ringwald     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
231600d93d79Smatthias.ringwald 
231700d93d79Smatthias.ringwald     // Find channel for this sig_id and connection handle
2318665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2319665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2320665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2321fc64f94aSMatthias Ringwald         if (channel->con_handle != handle) continue;
232200d93d79Smatthias.ringwald         if (code & 1) {
2323b1988dceSmatthias.ringwald             // match odd commands (responses) by previous signaling identifier
2324b1988dceSmatthias.ringwald             if (channel->local_sig_id == sig_id) {
232500d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
23264e32727eSmatthias.ringwald                 break;
232700d93d79Smatthias.ringwald             }
232800d93d79Smatthias.ringwald         } else {
2329b1988dceSmatthias.ringwald             // match even commands (requests) by local channel id
233000d93d79Smatthias.ringwald             if (channel->local_cid == dest_cid) {
233100d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
23324e32727eSmatthias.ringwald                 break;
233300d93d79Smatthias.ringwald             }
233400d93d79Smatthias.ringwald         }
233500d93d79Smatthias.ringwald     }
233600d93d79Smatthias.ringwald }
233709e9d05bSMatthias Ringwald #endif
233800d93d79Smatthias.ringwald 
2339e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
234009e9d05bSMatthias Ringwald 
234109e9d05bSMatthias Ringwald static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
234209e9d05bSMatthias Ringwald     uint8_t event[6];
234309e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
234409e9d05bSMatthias Ringwald     event[1] = 4;
234509e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
234609e9d05bSMatthias Ringwald     little_endian_store_16(event, 4, result);
234709e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
234809e9d05bSMatthias Ringwald     if (!l2cap_event_packet_handler) return;
234909e9d05bSMatthias Ringwald     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
235009e9d05bSMatthias Ringwald }
235109e9d05bSMatthias Ringwald 
2352c48b2a2cSMatthias Ringwald // @returns valid
2353c48b2a2cSMatthias Ringwald static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
2354e7d0c9aaSMatthias Ringwald     hci_connection_t * connection;
2355c48b2a2cSMatthias Ringwald     uint16_t result;
2356c48b2a2cSMatthias Ringwald     uint8_t  event[10];
235783fd9c76SMatthias Ringwald 
2358cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2359a3dc965aSMatthias Ringwald     btstack_linked_list_iterator_t it;
2360a3dc965aSMatthias Ringwald     l2cap_channel_t * channel;
2361a3dc965aSMatthias Ringwald     uint16_t local_cid;
236283fd9c76SMatthias Ringwald     uint16_t le_psm;
236363f0ac45SMatthias Ringwald     uint16_t new_credits;
236463f0ac45SMatthias Ringwald     uint16_t credits_before;
2365e7d0c9aaSMatthias Ringwald     l2cap_service_t * service;
236611cae19eSMilanka Ringwald     uint16_t source_cid;
236783fd9c76SMatthias Ringwald #endif
236800d93d79Smatthias.ringwald 
23691b8b8d05SMatthias Ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
237023017473SMatthias Ringwald     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u", code, sig_id);
23711b8b8d05SMatthias Ringwald 
23721b8b8d05SMatthias Ringwald     switch (code){
237300d93d79Smatthias.ringwald 
2374c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
2375c48b2a2cSMatthias Ringwald             result = little_endian_read_16(command, 4);
2376ccf076adS[email protected]             l2cap_emit_connection_parameter_update_response(handle, result);
2377ccf076adS[email protected]             break;
2378da886c03S[email protected] 
2379c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_REQUEST:
2380e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
2381da886c03S[email protected]             if (connection){
23826d91fb6cSMatthias Ringwald                 if (connection->role != HCI_ROLE_MASTER){
23836d91fb6cSMatthias Ringwald                     // reject command without notifying upper layer when not in master role
2384c48b2a2cSMatthias Ringwald                     return 0;
23856d91fb6cSMatthias Ringwald                 }
2386da886c03S[email protected]                 int update_parameter = 1;
2387a4c06b28SMatthias Ringwald                 le_connection_parameter_range_t existing_range;
23884ced4e8cSMatthias Ringwald                 gap_get_connection_parameter_range(&existing_range);
2389c48b2a2cSMatthias Ringwald                 uint16_t le_conn_interval_min = little_endian_read_16(command,8);
2390c48b2a2cSMatthias Ringwald                 uint16_t le_conn_interval_max = little_endian_read_16(command,10);
2391c48b2a2cSMatthias Ringwald                 uint16_t le_conn_latency = little_endian_read_16(command,12);
2392c48b2a2cSMatthias Ringwald                 uint16_t le_supervision_timeout = little_endian_read_16(command,14);
2393da886c03S[email protected] 
2394da886c03S[email protected]                 if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
2395da886c03S[email protected]                 if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
2396da886c03S[email protected] 
2397da886c03S[email protected]                 if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
2398da886c03S[email protected]                 if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
2399da886c03S[email protected] 
2400da886c03S[email protected]                 if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
2401da886c03S[email protected]                 if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
2402da886c03S[email protected] 
2403da886c03S[email protected]                 if (update_parameter){
2404da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
2405da886c03S[email protected]                     connection->le_conn_interval_min = le_conn_interval_min;
2406da886c03S[email protected]                     connection->le_conn_interval_max = le_conn_interval_max;
2407da886c03S[email protected]                     connection->le_conn_latency = le_conn_latency;
2408da886c03S[email protected]                     connection->le_supervision_timeout = le_supervision_timeout;
2409da886c03S[email protected]                 } else {
2410da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
2411da886c03S[email protected]                 }
2412c48b2a2cSMatthias Ringwald                 connection->le_con_param_update_identifier = sig_id;
2413da886c03S[email protected]             }
2414da886c03S[email protected] 
241533c40538SMatthias Ringwald             if (!l2cap_event_packet_handler) break;
2416c48b2a2cSMatthias Ringwald 
2417c48b2a2cSMatthias Ringwald             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
2418c48b2a2cSMatthias Ringwald             event[1] = 8;
2419c48b2a2cSMatthias Ringwald             memcpy(&event[2], &command[4], 8);
2420c48b2a2cSMatthias Ringwald             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
242133c40538SMatthias Ringwald             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
2422ccf076adS[email protected]             break;
2423c48b2a2cSMatthias Ringwald 
2424a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2425a3dc965aSMatthias Ringwald 
242663f0ac45SMatthias Ringwald         case COMMAND_REJECT:
242763f0ac45SMatthias Ringwald             // Find channel for this sig_id and connection handle
242863f0ac45SMatthias Ringwald             channel = NULL;
242963f0ac45SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
243063f0ac45SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
243163f0ac45SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
243263f0ac45SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
243363f0ac45SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
243463f0ac45SMatthias Ringwald                 channel = a_channel;
243563f0ac45SMatthias Ringwald                 break;
243663f0ac45SMatthias Ringwald             }
243763f0ac45SMatthias Ringwald             if (!channel) break;
243863f0ac45SMatthias Ringwald 
243963f0ac45SMatthias Ringwald             // if received while waiting for le connection response, assume legacy device
244063f0ac45SMatthias Ringwald             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
244163f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
244263f0ac45SMatthias Ringwald                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
244344276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0x0002);
244463f0ac45SMatthias Ringwald 
244563f0ac45SMatthias Ringwald                 // discard channel
244663f0ac45SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
244763f0ac45SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
244863f0ac45SMatthias Ringwald                 break;
244963f0ac45SMatthias Ringwald             }
245063f0ac45SMatthias Ringwald             break;
245163f0ac45SMatthias Ringwald 
2452e7d0c9aaSMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_REQUEST:
2453e7d0c9aaSMatthias Ringwald 
2454e7d0c9aaSMatthias Ringwald             // get hci connection, bail if not found (must not happen)
2455e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
2456e7d0c9aaSMatthias Ringwald             if (!connection) return 0;
2457e7d0c9aaSMatthias Ringwald 
2458e7d0c9aaSMatthias Ringwald             // check if service registered
2459e7d0c9aaSMatthias Ringwald             le_psm  = little_endian_read_16(command, 4);
2460e7d0c9aaSMatthias Ringwald             service = l2cap_le_get_service(le_psm);
246111cae19eSMilanka Ringwald             source_cid = little_endian_read_16(command, 6);
2462e7d0c9aaSMatthias Ringwald 
2463e7d0c9aaSMatthias Ringwald             if (service){
2464e7d0c9aaSMatthias Ringwald                 if (source_cid < 0x40){
2465e7d0c9aaSMatthias Ringwald                     // 0x0009 Connection refused - Invalid Source CID
2466e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
2467e7d0c9aaSMatthias Ringwald                     return 1;
2468e7d0c9aaSMatthias Ringwald                 }
2469e7d0c9aaSMatthias Ringwald 
2470e7d0c9aaSMatthias Ringwald                 // go through list of channels for this ACL connection and check if we get a match
2471e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2472e7d0c9aaSMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&it)){
24731b8b8d05SMatthias Ringwald                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
24741b8b8d05SMatthias Ringwald                     if (a_channel->con_handle != handle) continue;
24751b8b8d05SMatthias Ringwald                     if (a_channel->remote_cid != source_cid) continue;
2476e7d0c9aaSMatthias Ringwald                     // 0x000a Connection refused - Source CID already allocated
2477e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
2478e7d0c9aaSMatthias Ringwald                     return 1;
2479e7d0c9aaSMatthias Ringwald                 }
2480e7d0c9aaSMatthias Ringwald 
248183fd9c76SMatthias Ringwald                 // security: check encryption
248283fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_2){
248383fd9c76SMatthias Ringwald                     if (sm_encryption_key_size(handle) == 0){
248483fd9c76SMatthias Ringwald                         // 0x0008 Connection refused - insufficient encryption
2485e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
248683fd9c76SMatthias Ringwald                         return 1;
248783fd9c76SMatthias Ringwald                     }
248883fd9c76SMatthias Ringwald                     // anything less than 16 byte key size is insufficient
248983fd9c76SMatthias Ringwald                     if (sm_encryption_key_size(handle) < 16){
249083fd9c76SMatthias Ringwald                         // 0x0007 Connection refused – insufficient encryption key size
2491e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
249283fd9c76SMatthias Ringwald                         return 1;
249383fd9c76SMatthias Ringwald                     }
249483fd9c76SMatthias Ringwald                 }
249583fd9c76SMatthias Ringwald 
249683fd9c76SMatthias Ringwald                 // security: check authencation
249783fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_3){
249883fd9c76SMatthias Ringwald                     if (!sm_authenticated(handle)){
249983fd9c76SMatthias Ringwald                         // 0x0005 Connection refused – insufficient authentication
2500e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
250183fd9c76SMatthias Ringwald                         return 1;
250283fd9c76SMatthias Ringwald                     }
250383fd9c76SMatthias Ringwald                 }
250483fd9c76SMatthias Ringwald 
250583fd9c76SMatthias Ringwald                 // security: check authorization
250683fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_4){
250783fd9c76SMatthias Ringwald                     if (sm_authorization_state(handle) != AUTHORIZATION_GRANTED){
250883fd9c76SMatthias Ringwald                         // 0x0006 Connection refused – insufficient authorization
2509e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
251083fd9c76SMatthias Ringwald                         return 1;
251183fd9c76SMatthias Ringwald                     }
251283fd9c76SMatthias Ringwald                 }
2513e7d0c9aaSMatthias Ringwald 
2514e7d0c9aaSMatthias Ringwald                 // allocate channel
25151b8b8d05SMatthias Ringwald                 channel = l2cap_create_channel_entry(service->packet_handler, connection->address,
2516e7d0c9aaSMatthias Ringwald                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
2517e7d0c9aaSMatthias Ringwald                 if (!channel){
2518e7d0c9aaSMatthias Ringwald                     // 0x0004 Connection refused – no resources available
2519e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2520e7d0c9aaSMatthias Ringwald                     return 1;
2521e7d0c9aaSMatthias Ringwald                 }
2522e7d0c9aaSMatthias Ringwald 
2523e7d0c9aaSMatthias Ringwald                 channel->con_handle = handle;
2524e7d0c9aaSMatthias Ringwald                 channel->remote_cid = source_cid;
2525e7d0c9aaSMatthias Ringwald                 channel->remote_sig_id = sig_id;
25267f107edaSMatthias Ringwald                 channel->remote_mtu = little_endian_read_16(command, 8);
25277f107edaSMatthias Ringwald                 channel->remote_mps = little_endian_read_16(command, 10);
25287f107edaSMatthias Ringwald                 channel->credits_outgoing = little_endian_read_16(command, 12);
2529e7d0c9aaSMatthias Ringwald 
2530e7d0c9aaSMatthias Ringwald                 // set initial state
2531e7d0c9aaSMatthias Ringwald                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2532c99bb618SMatthias Ringwald                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
2533e7d0c9aaSMatthias Ringwald 
2534e7d0c9aaSMatthias Ringwald                 // add to connections list
2535e7d0c9aaSMatthias Ringwald                 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2536e7d0c9aaSMatthias Ringwald 
2537e7d0c9aaSMatthias Ringwald                 // post connection request event
253844276248SMatthias Ringwald                 l2cap_emit_le_incoming_connection(channel);
2539e7d0c9aaSMatthias Ringwald 
2540e7d0c9aaSMatthias Ringwald             } else {
2541e7d0c9aaSMatthias Ringwald                 // Connection refused – LE_PSM not supported
2542e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2543e7d0c9aaSMatthias Ringwald             }
2544e7d0c9aaSMatthias Ringwald             break;
25451b8b8d05SMatthias Ringwald 
25461b8b8d05SMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
25471b8b8d05SMatthias Ringwald             // Find channel for this sig_id and connection handle
25481b8b8d05SMatthias Ringwald             channel = NULL;
25491b8b8d05SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
25501b8b8d05SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
25511b8b8d05SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
25521b8b8d05SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
25531b8b8d05SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
25541b8b8d05SMatthias Ringwald                 channel = a_channel;
25551b8b8d05SMatthias Ringwald                 break;
25561b8b8d05SMatthias Ringwald             }
25571b8b8d05SMatthias Ringwald             if (!channel) break;
25581b8b8d05SMatthias Ringwald 
25591b8b8d05SMatthias Ringwald             // cid + 0
25601b8b8d05SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
25611b8b8d05SMatthias Ringwald             if (result){
25621b8b8d05SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
25631b8b8d05SMatthias Ringwald                 // map l2cap connection response result to BTstack status enumeration
256444276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, result);
25651b8b8d05SMatthias Ringwald 
25661b8b8d05SMatthias Ringwald                 // discard channel
256763f0ac45SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
25681b8b8d05SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
25691b8b8d05SMatthias Ringwald                 break;
25701b8b8d05SMatthias Ringwald             }
25711b8b8d05SMatthias Ringwald 
25721b8b8d05SMatthias Ringwald             // success
25731b8b8d05SMatthias Ringwald             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
25741b8b8d05SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
25751b8b8d05SMatthias Ringwald             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
25761b8b8d05SMatthias Ringwald             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
25771b8b8d05SMatthias Ringwald             channel->state = L2CAP_STATE_OPEN;
257844276248SMatthias Ringwald             l2cap_emit_le_channel_opened(channel, result);
25791b8b8d05SMatthias Ringwald             break;
25801b8b8d05SMatthias Ringwald 
258185aeef60SMatthias Ringwald         case LE_FLOW_CONTROL_CREDIT:
258285aeef60SMatthias Ringwald             // find channel
258385aeef60SMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
258485aeef60SMatthias Ringwald             channel = l2cap_le_get_channel_for_local_cid(local_cid);
258563f0ac45SMatthias Ringwald             if (!channel) {
258663f0ac45SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
258763f0ac45SMatthias Ringwald                 break;
258863f0ac45SMatthias Ringwald             }
258963f0ac45SMatthias Ringwald             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
259063f0ac45SMatthias Ringwald             credits_before = channel->credits_outgoing;
259163f0ac45SMatthias Ringwald             channel->credits_outgoing += new_credits;
259263f0ac45SMatthias Ringwald             // check for credit overrun
259363f0ac45SMatthias Ringwald             if (credits_before > channel->credits_outgoing){
259463f0ac45SMatthias Ringwald                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
259563f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
259663f0ac45SMatthias Ringwald                 break;
259763f0ac45SMatthias Ringwald             }
259863f0ac45SMatthias Ringwald             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
259985aeef60SMatthias Ringwald             break;
260085aeef60SMatthias Ringwald 
2601828a7f7aSMatthias Ringwald         case DISCONNECTION_REQUEST:
2602828a7f7aSMatthias Ringwald             // find channel
2603828a7f7aSMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
2604828a7f7aSMatthias Ringwald             channel = l2cap_le_get_channel_for_local_cid(local_cid);
260563f34e00SMatthias Ringwald             if (!channel) {
260663f34e00SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
260763f34e00SMatthias Ringwald                 break;
260863f34e00SMatthias Ringwald             }
2609828a7f7aSMatthias Ringwald             channel->remote_sig_id = sig_id;
2610828a7f7aSMatthias Ringwald             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
2611828a7f7aSMatthias Ringwald             break;
2612828a7f7aSMatthias Ringwald 
2613a3dc965aSMatthias Ringwald #endif
2614a3dc965aSMatthias Ringwald 
261563f0ac45SMatthias Ringwald         case DISCONNECTION_RESPONSE:
261663f0ac45SMatthias Ringwald             break;
261763f0ac45SMatthias Ringwald 
2618c48b2a2cSMatthias Ringwald         default:
2619c48b2a2cSMatthias Ringwald             // command unknown -> reject command
2620c48b2a2cSMatthias Ringwald             return 0;
2621ccf076adS[email protected]     }
2622c48b2a2cSMatthias Ringwald     return 1;
2623c48b2a2cSMatthias Ringwald }
2624e7d0c9aaSMatthias Ringwald #endif
2625c48b2a2cSMatthias Ringwald 
2626d48432d4SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2627*e32be409SMatthias 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){
2628d48432d4SMatthias Ringwald     switch (sar){
2629d48432d4SMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
2630*e32be409SMatthias Ringwald             // packet complete -> disapatch
2631*e32be409SMatthias Ringwald             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, payload, size);
2632d48432d4SMatthias Ringwald             break;
2633d48432d4SMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
2634d48432d4SMatthias Ringwald             // TODO: check if reassembly started
2635e8e9809fSMatthias Ringwald             // TODO: check sdu_len against local mtu
2636*e32be409SMatthias Ringwald             l2cap_channel->reassembly_sdu_length = little_endian_read_16(payload, 0);
2637*e32be409SMatthias Ringwald             payload += 2;
2638*e32be409SMatthias Ringwald             size    -= 2;
2639*e32be409SMatthias Ringwald             memcpy(&l2cap_channel->reassembly_buffer[0], payload, size);
2640*e32be409SMatthias Ringwald             l2cap_channel->reassembly_pos = size;
2641d48432d4SMatthias Ringwald             break;
2642d48432d4SMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
2643*e32be409SMatthias Ringwald             memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos], payload, size);
2644*e32be409SMatthias Ringwald             l2cap_channel->reassembly_pos += size;
2645*e32be409SMatthias Ringwald             break;
2646*e32be409SMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
2647*e32be409SMatthias Ringwald             memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos], payload, size);
2648*e32be409SMatthias Ringwald             l2cap_channel->reassembly_pos += size;
2649*e32be409SMatthias Ringwald             // packet complete -> disapatch
2650*e32be409SMatthias Ringwald             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->reassembly_buffer, l2cap_channel->reassembly_pos);
2651*e32be409SMatthias Ringwald             l2cap_channel->reassembly_pos = 0;
2652d48432d4SMatthias Ringwald             break;
2653d48432d4SMatthias Ringwald     }
2654d48432d4SMatthias Ringwald }
2655d48432d4SMatthias Ringwald #endif
2656d48432d4SMatthias Ringwald 
2657c48b2a2cSMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size ){
26589ec2630cSMatthias Ringwald     UNUSED(packet_type);
26599ec2630cSMatthias Ringwald     UNUSED(channel);
2660c48b2a2cSMatthias Ringwald 
266109e9d05bSMatthias Ringwald     l2cap_channel_t * l2cap_channel;
2662f3963406SMatthias Ringwald     UNUSED(l2cap_channel);
266309e9d05bSMatthias Ringwald 
2664c48b2a2cSMatthias Ringwald     // Get Channel ID
2665c48b2a2cSMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
2666c48b2a2cSMatthias Ringwald     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
2667c48b2a2cSMatthias Ringwald 
2668c48b2a2cSMatthias Ringwald     switch (channel_id) {
2669c48b2a2cSMatthias Ringwald 
267009e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2671c48b2a2cSMatthias Ringwald         case L2CAP_CID_SIGNALING: {
2672c48b2a2cSMatthias Ringwald             uint16_t command_offset = 8;
2673c48b2a2cSMatthias Ringwald             while (command_offset < size) {
2674c48b2a2cSMatthias Ringwald                 // handle signaling commands
2675c48b2a2cSMatthias Ringwald                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
2676c48b2a2cSMatthias Ringwald 
2677c48b2a2cSMatthias Ringwald                 // increment command_offset
2678c48b2a2cSMatthias Ringwald                 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2679c48b2a2cSMatthias Ringwald             }
2680c48b2a2cSMatthias Ringwald             break;
2681c48b2a2cSMatthias Ringwald         }
268209e9d05bSMatthias Ringwald #endif
2683c48b2a2cSMatthias Ringwald 
2684e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
2685e7d0c9aaSMatthias Ringwald         case L2CAP_CID_SIGNALING_LE: {
2686e7d0c9aaSMatthias Ringwald             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
2687e7d0c9aaSMatthias Ringwald             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
2688c48b2a2cSMatthias Ringwald             if (!valid){
2689e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2690ccf076adS[email protected]             }
2691ccf076adS[email protected]             break;
2692e7d0c9aaSMatthias Ringwald         }
2693e7d0c9aaSMatthias Ringwald #endif
2694c48b2a2cSMatthias Ringwald 
2695c48b2a2cSMatthias Ringwald         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
2696c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback) {
2697c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2698ccf076adS[email protected]             }
2699c48b2a2cSMatthias Ringwald             break;
2700c48b2a2cSMatthias Ringwald 
2701c48b2a2cSMatthias Ringwald         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
2702c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback) {
2703c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2704c48b2a2cSMatthias Ringwald             }
2705c48b2a2cSMatthias Ringwald             break;
2706c48b2a2cSMatthias Ringwald 
2707c48b2a2cSMatthias Ringwald         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
2708c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback) {
2709c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2710c48b2a2cSMatthias Ringwald             }
2711c48b2a2cSMatthias Ringwald             break;
27121bbc0b23S[email protected] 
271309e9d05bSMatthias Ringwald         default:
271409e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
271500d93d79Smatthias.ringwald             // Find channel for this channel_id and connection handle
271664e11ca9SMatthias Ringwald             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
2717d1fd2a88SMatthias Ringwald             if (l2cap_channel) {
271827e0774aSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
271927e0774aSMatthias Ringwald                 if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
272027e0774aSMatthias Ringwald 
272127e0774aSMatthias Ringwald                     // verify FCS
272227e0774aSMatthias Ringwald                     uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
272327e0774aSMatthias Ringwald                     uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
272427e0774aSMatthias Ringwald                     log_info("Packet FCS 0x%04x, calculated FCS 0x%04x", fcs_packet, fcs_calculated);
272527e0774aSMatthias Ringwald                     if (fcs_calculated != fcs_packet){
272627e0774aSMatthias Ringwald                         log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
272727e0774aSMatthias Ringwald                         // TODO: trigger retransmission or something like that
272827e0774aSMatthias Ringwald                         break;
272927e0774aSMatthias Ringwald                     }
273027e0774aSMatthias Ringwald 
273127e0774aSMatthias Ringwald                     // switch on packet type
273227e0774aSMatthias Ringwald                     uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
273338f62777SMatthias Ringwald                     uint8_t  req_seq = (control >> 8) & 0x3f;
27342bea1b8dSMatthias Ringwald                     int final = (control >> 7) & 0x01;
273527e0774aSMatthias Ringwald                     if (control & 1){
273627e0774aSMatthias Ringwald                         // S-Frame
273778cd8a22SMatthias Ringwald                         int poll  = (control >> 4) & 0x01;
2738bdbe2e49SMatthias Ringwald                         l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
27399ffcbce4SMatthias Ringwald                         log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
27407b7901d8SMatthias Ringwald                         l2cap_ertm_tx_packet_state_t * tx_state;
2741bdbe2e49SMatthias Ringwald                         switch (s){
2742bdbe2e49SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
27439ffcbce4SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
27442a424812SMatthias Ringwald                                 l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
27453233d8abSMatthias Ringwald                                 if (poll && final){
27463233d8abSMatthias Ringwald                                     // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
27473233d8abSMatthias Ringwald                                     log_error("P=F=1 in S-Frame");
27483233d8abSMatthias Ringwald                                     break;
27493233d8abSMatthias Ringwald                                 }
275078cd8a22SMatthias Ringwald                                 if (poll){
2751d2afdd38SMatthias Ringwald                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
2752d2afdd38SMatthias Ringwald                                     l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
275378cd8a22SMatthias Ringwald                                 }
27543233d8abSMatthias Ringwald                                 if (final){
27553233d8abSMatthias Ringwald                                     // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
27563233d8abSMatthias Ringwald                                     l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
27573233d8abSMatthias Ringwald                                 }
2758bdbe2e49SMatthias Ringwald                                 break;
27599ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
27609ffcbce4SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
27619ffcbce4SMatthias Ringwald                                 l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
27629ffcbce4SMatthias Ringwald                                 // rsetart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_handle_req_seq)
27639ffcbce4SMatthias Ringwald                                 l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
27649ffcbce4SMatthias Ringwald                                 break;
27659ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
27669ffcbce4SMatthias Ringwald                                 log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
27679ffcbce4SMatthias Ringwald                                 break;
27689ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
27697b7901d8SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
27707b7901d8SMatthias Ringwald                                 if (poll){
27717b7901d8SMatthias Ringwald                                     l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
27727b7901d8SMatthias Ringwald                                 }
27737b7901d8SMatthias Ringwald                                 // find requested i-frame
27747b7901d8SMatthias Ringwald                                 tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
27757b7901d8SMatthias Ringwald                                 if (tx_state){
27767b7901d8SMatthias Ringwald                                     log_info("Retransmission for tx_seq %u requested", req_seq);
2777d2afdd38SMatthias Ringwald                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
27787b7901d8SMatthias Ringwald                                     tx_state->retransmission_requested = 1;
27797b7901d8SMatthias Ringwald                                     l2cap_channel->srej_active = 1;
27807b7901d8SMatthias Ringwald                                 }
27819ffcbce4SMatthias Ringwald                                 break;
2782bdbe2e49SMatthias Ringwald                             default:
2783bdbe2e49SMatthias Ringwald                                 break;
2784bdbe2e49SMatthias Ringwald                         }
278527e0774aSMatthias Ringwald                         break;
278627e0774aSMatthias Ringwald                     } else {
278727e0774aSMatthias Ringwald                         // I-Frame
278827e0774aSMatthias Ringwald                         // get control
278927e0774aSMatthias Ringwald                         l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
279038f62777SMatthias Ringwald                         uint8_t tx_seq = (control >> 1) & 0x3f;
279138f62777SMatthias Ringwald                         log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
2792e8e9809fSMatthias Ringwald                         log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
279338f62777SMatthias Ringwald                         log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
27942a424812SMatthias Ringwald                         l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
279511b576c5SMatthias Ringwald                         if (final){
279611b576c5SMatthias Ringwald                             // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
279711b576c5SMatthias Ringwald                             l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
279811b576c5SMatthias Ringwald                         }
279938f62777SMatthias Ringwald                         // check ordering
280038f62777SMatthias Ringwald                         if (l2cap_channel->expected_tx_seq == tx_seq){
280138f62777SMatthias Ringwald                             log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
2802c7309e8dSMatthias Ringwald                             l2cap_channel->req_seq = (tx_seq+1) & 0x3f;
2803d84e866fSMatthias Ringwald                             l2cap_channel->send_supervisor_frame_receiver_ready = 1;
280438f62777SMatthias Ringwald                             l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
2805d48432d4SMatthias Ringwald 
2806*e32be409SMatthias Ringwald                             // process SDU
2807*e32be409SMatthias Ringwald                             l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, &packet[COMPLETE_L2CAP_HEADER+2], size-(COMPLETE_L2CAP_HEADER+2));
2808d48432d4SMatthias Ringwald 
2809c7309e8dSMatthias Ringwald                         } else {
2810df2191a7SMatthias Ringwald                             int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
2811df2191a7SMatthias Ringwald                             if (delta < 2){
2812df2191a7SMatthias Ringwald                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
2813df2191a7SMatthias Ringwald                                 l2cap_channel->send_supervisor_frame_selective_reject = 1;
2814df2191a7SMatthias Ringwald                             } else {
2815df2191a7SMatthias Ringwald                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
2816c7309e8dSMatthias Ringwald                                 l2cap_channel->send_supervisor_frame_reject = 1;
281727e0774aSMatthias Ringwald                             }
281838f62777SMatthias Ringwald                         }
2819df2191a7SMatthias Ringwald                     }
282027e0774aSMatthias Ringwald                     break;
282127e0774aSMatthias Ringwald                 }
282227e0774aSMatthias Ringwald #endif
28233d50b4baSMatthias Ringwald                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
282400d93d79Smatthias.ringwald             }
282509e9d05bSMatthias Ringwald #endif
2826a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
282764e11ca9SMatthias Ringwald             l2cap_channel = l2cap_le_get_channel_for_local_cid(channel_id);
282864e11ca9SMatthias Ringwald             if (l2cap_channel) {
282985aeef60SMatthias Ringwald                 // credit counting
283085aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming == 0){
283185aeef60SMatthias Ringwald                     log_error("LE Data Channel packet received but no incoming credits");
283285aeef60SMatthias Ringwald                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
283385aeef60SMatthias Ringwald                     break;
283485aeef60SMatthias Ringwald                 }
283585aeef60SMatthias Ringwald                 l2cap_channel->credits_incoming--;
283685aeef60SMatthias Ringwald 
283785aeef60SMatthias Ringwald                 // automatic credits
283885aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){
283985aeef60SMatthias Ringwald                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
284085aeef60SMatthias Ringwald                 }
284185aeef60SMatthias Ringwald 
2842cd529728SMatthias Ringwald                 // first fragment
2843cd529728SMatthias Ringwald                 uint16_t pos = 0;
2844cd529728SMatthias Ringwald                 if (!l2cap_channel->receive_sdu_len){
2845cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
2846cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_pos = 0;
2847cd529728SMatthias Ringwald                     pos  += 2;
2848cd529728SMatthias Ringwald                     size -= 2;
2849cd529728SMatthias Ringwald                 }
2850cd529728SMatthias Ringwald                 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], size-COMPLETE_L2CAP_HEADER);
2851cd529728SMatthias Ringwald                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
2852cd529728SMatthias Ringwald                 // done?
285363f0ac45SMatthias Ringwald                 log_info("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
2854cd529728SMatthias Ringwald                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
2855cd529728SMatthias Ringwald                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
2856cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = 0;
2857cd529728SMatthias Ringwald                 }
285863f0ac45SMatthias Ringwald             } else {
285963f0ac45SMatthias Ringwald                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
286064e11ca9SMatthias Ringwald             }
286164e11ca9SMatthias Ringwald #endif
28625652b5ffS[email protected]             break;
28635652b5ffS[email protected]     }
286400d93d79Smatthias.ringwald 
28651eb2563eS[email protected]     l2cap_run();
28662718e2e7Smatthias.ringwald }
286700d93d79Smatthias.ringwald 
286809e9d05bSMatthias Ringwald // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
286909e9d05bSMatthias Ringwald void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
287009e9d05bSMatthias Ringwald     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
287109e9d05bSMatthias Ringwald     if (index < 0) return;
287209e9d05bSMatthias Ringwald     fixed_channels[index].callback = the_packet_handler;
287309e9d05bSMatthias Ringwald }
287409e9d05bSMatthias Ringwald 
287509e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
287615ec09bbSmatthias.ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
287727a923d0Smatthias.ringwald void l2cap_finialize_channel_close(l2cap_channel_t * channel){
2878f62db1e3Smatthias.ringwald     channel->state = L2CAP_STATE_CLOSED;
2879f62db1e3Smatthias.ringwald     l2cap_emit_channel_closed(channel);
2880f62db1e3Smatthias.ringwald     // discard channel
28819dcb2fb2S[email protected]     l2cap_stop_rtx(channel);
2882665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2883d3a9df87Smatthias.ringwald     btstack_memory_l2cap_channel_free(channel);
2884c8e4258aSmatthias.ringwald }
28851e6aba47Smatthias.ringwald 
28868f2a52f4SMatthias Ringwald static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
2887665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
2888665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, services);
2889665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2890665d90f2SMatthias Ringwald         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
28919d9bbc01Smatthias.ringwald         if ( service->psm == psm){
28929d9bbc01Smatthias.ringwald             return service;
28939d9bbc01Smatthias.ringwald         };
28949d9bbc01Smatthias.ringwald     }
28959d9bbc01Smatthias.ringwald     return NULL;
28969d9bbc01Smatthias.ringwald }
28979d9bbc01Smatthias.ringwald 
28987192e786SMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
28997192e786SMatthias Ringwald     return l2cap_get_service_internal(&l2cap_services, psm);
29007192e786SMatthias Ringwald }
29017192e786SMatthias Ringwald 
2902e0abb8e7S[email protected] 
2903be2053a6SMatthias 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){
2904be2053a6SMatthias Ringwald 
2905be2053a6SMatthias Ringwald     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
2906e0abb8e7S[email protected] 
29074bb582b6Smatthias.ringwald     // check for alread registered psm
29089d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
2909277abc2cSmatthias.ringwald     if (service) {
2910be2053a6SMatthias Ringwald         log_error("l2cap_register_service: PSM %u already registered", psm);
2911be2053a6SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
2912277abc2cSmatthias.ringwald     }
29139d9bbc01Smatthias.ringwald 
29144bb582b6Smatthias.ringwald     // alloc structure
2915bb69aaaeS[email protected]     service = btstack_memory_l2cap_service_get();
2916277abc2cSmatthias.ringwald     if (!service) {
2917be2053a6SMatthias Ringwald         log_error("l2cap_register_service: no memory for l2cap_service_t");
2918be2053a6SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
2919277abc2cSmatthias.ringwald     }
29209d9bbc01Smatthias.ringwald 
29219d9bbc01Smatthias.ringwald     // fill in
29229d9bbc01Smatthias.ringwald     service->psm = psm;
29239d9bbc01Smatthias.ringwald     service->mtu = mtu;
292405ae8de3SMatthias Ringwald     service->packet_handler = service_packet_handler;
2925df3354fcS[email protected]     service->required_security_level = security_level;
29269d9bbc01Smatthias.ringwald 
29279d9bbc01Smatthias.ringwald     // add to services list
2928665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
2929c0e866bfSmatthias.ringwald 
2930c0e866bfSmatthias.ringwald     // enable page scan
293115a95bd5SMatthias Ringwald     gap_connectable_control(1);
29325842b6d9Smatthias.ringwald 
2933be2053a6SMatthias Ringwald     return 0;
29349d9bbc01Smatthias.ringwald }
29359d9bbc01Smatthias.ringwald 
29367e8856ebSMatthias Ringwald uint8_t l2cap_unregister_service(uint16_t psm){
2937e0abb8e7S[email protected] 
2938e0abb8e7S[email protected]     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
2939e0abb8e7S[email protected] 
29409d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
29417e8856ebSMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2942665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
2943d3a9df87Smatthias.ringwald     btstack_memory_l2cap_service_free(service);
2944c0e866bfSmatthias.ringwald 
2945c0e866bfSmatthias.ringwald     // disable page scan when no services registered
29467e8856ebSMatthias Ringwald     if (btstack_linked_list_empty(&l2cap_services)) {
294715a95bd5SMatthias Ringwald         gap_connectable_control(0);
29489d9bbc01Smatthias.ringwald     }
29497e8856ebSMatthias Ringwald     return 0;
29507e8856ebSMatthias Ringwald }
295109e9d05bSMatthias Ringwald #endif
29529d9bbc01Smatthias.ringwald 
29537192e786SMatthias Ringwald 
2954cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
295583fd9c76SMatthias Ringwald 
295657be49d6SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
295757be49d6SMatthias Ringwald     if (!channel->waiting_for_can_send_now) return;
295857be49d6SMatthias Ringwald     if (channel->send_sdu_buffer) return;
295957be49d6SMatthias Ringwald     channel->waiting_for_can_send_now = 0;
296057be49d6SMatthias Ringwald     log_info("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
296157be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
296257be49d6SMatthias Ringwald }
296357be49d6SMatthias Ringwald 
296457be49d6SMatthias Ringwald // 1BH2222
296557be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
296657be49d6SMatthias 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",
296757be49d6SMatthias Ringwald              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
296857be49d6SMatthias Ringwald     uint8_t event[19];
296957be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
297057be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
297157be49d6SMatthias Ringwald     event[2] = channel->address_type;
297257be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
297357be49d6SMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
297457be49d6SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
297557be49d6SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
297657be49d6SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
297757be49d6SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_mtu);
297857be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
297957be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
298057be49d6SMatthias Ringwald }
298157be49d6SMatthias Ringwald // 11BH22222
298257be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
298357be49d6SMatthias 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",
298457be49d6SMatthias Ringwald              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
298557be49d6SMatthias Ringwald              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
2986c99bb618SMatthias Ringwald     uint8_t event[23];
298757be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
298857be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
298957be49d6SMatthias Ringwald     event[2] = status;
299057be49d6SMatthias Ringwald     event[3] = channel->address_type;
299157be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[4]);
299257be49d6SMatthias Ringwald     little_endian_store_16(event, 10, channel->con_handle);
2993c99bb618SMatthias Ringwald     event[12] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
2994c99bb618SMatthias Ringwald     little_endian_store_16(event, 13, channel->psm);
2995c99bb618SMatthias Ringwald     little_endian_store_16(event, 15, channel->local_cid);
2996c99bb618SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_cid);
2997c99bb618SMatthias Ringwald     little_endian_store_16(event, 19, channel->local_mtu);
2998c99bb618SMatthias Ringwald     little_endian_store_16(event, 21, channel->remote_mtu);
299957be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
300057be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
300157be49d6SMatthias Ringwald }
300257be49d6SMatthias Ringwald 
300357be49d6SMatthias Ringwald static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid){
300457be49d6SMatthias Ringwald     btstack_linked_list_iterator_t it;
300557be49d6SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
300657be49d6SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
300757be49d6SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
300857be49d6SMatthias Ringwald         if ( channel->local_cid == local_cid) {
300957be49d6SMatthias Ringwald             return channel;
301057be49d6SMatthias Ringwald         }
301157be49d6SMatthias Ringwald     }
301257be49d6SMatthias Ringwald     return NULL;
301357be49d6SMatthias Ringwald }
301457be49d6SMatthias Ringwald 
301557be49d6SMatthias Ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
301657be49d6SMatthias Ringwald void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
301757be49d6SMatthias Ringwald     channel->state = L2CAP_STATE_CLOSED;
301857be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
301957be49d6SMatthias Ringwald     // discard channel
302057be49d6SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
302157be49d6SMatthias Ringwald     btstack_memory_l2cap_channel_free(channel);
302257be49d6SMatthias Ringwald }
302357be49d6SMatthias Ringwald 
3024e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
3025e7d0c9aaSMatthias Ringwald     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
30267192e786SMatthias Ringwald }
3027efedfb4cSMatthias Ringwald 
3028da144af5SMatthias Ringwald uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
30297192e786SMatthias Ringwald 
3030da144af5SMatthias Ringwald     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
30317192e786SMatthias Ringwald 
30327192e786SMatthias Ringwald     // check for alread registered psm
30337192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
30347192e786SMatthias Ringwald     if (service) {
3035da144af5SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
30367192e786SMatthias Ringwald     }
30377192e786SMatthias Ringwald 
30387192e786SMatthias Ringwald     // alloc structure
30397192e786SMatthias Ringwald     service = btstack_memory_l2cap_service_get();
30407192e786SMatthias Ringwald     if (!service) {
30417192e786SMatthias Ringwald         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
3042da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
30437192e786SMatthias Ringwald     }
30447192e786SMatthias Ringwald 
30457192e786SMatthias Ringwald     // fill in
30467192e786SMatthias Ringwald     service->psm = psm;
3047da144af5SMatthias Ringwald     service->mtu = 0;
30487192e786SMatthias Ringwald     service->packet_handler = packet_handler;
30497192e786SMatthias Ringwald     service->required_security_level = security_level;
30507192e786SMatthias Ringwald 
30517192e786SMatthias Ringwald     // add to services list
3052665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
30537192e786SMatthias Ringwald 
30547192e786SMatthias Ringwald     // done
3055da144af5SMatthias Ringwald     return 0;
30567192e786SMatthias Ringwald }
30577192e786SMatthias Ringwald 
3058da144af5SMatthias Ringwald uint8_t l2cap_le_unregister_service(uint16_t psm) {
30597192e786SMatthias Ringwald     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
30607192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
30619367f9b0SMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3062da144af5SMatthias Ringwald 
3063665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
30647192e786SMatthias Ringwald     btstack_memory_l2cap_service_free(service);
3065da144af5SMatthias Ringwald     return 0;
30667192e786SMatthias Ringwald }
3067da144af5SMatthias Ringwald 
3068da144af5SMatthias Ringwald uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
3069e7d0c9aaSMatthias Ringwald     // get channel
3070e7d0c9aaSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3071e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3072e7d0c9aaSMatthias Ringwald 
3073e7d0c9aaSMatthias Ringwald     // validate state
3074e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3075e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
3076e7d0c9aaSMatthias Ringwald     }
3077e7d0c9aaSMatthias Ringwald 
3078efedfb4cSMatthias Ringwald     // set state accept connection
307923017473SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
308023017473SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
308123017473SMatthias Ringwald     channel->local_mtu = mtu;
308285aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
308385aeef60SMatthias Ringwald     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
308485aeef60SMatthias Ringwald 
308585aeef60SMatthias Ringwald     // test
308663f0ac45SMatthias Ringwald     // channel->new_credits_incoming = 1;
3087e7d0c9aaSMatthias Ringwald 
3088e7d0c9aaSMatthias Ringwald     // go
3089e7d0c9aaSMatthias Ringwald     l2cap_run();
3090da144af5SMatthias Ringwald     return 0;
3091da144af5SMatthias Ringwald }
3092da144af5SMatthias Ringwald 
3093da144af5SMatthias Ringwald /**
3094da144af5SMatthias Ringwald  * @brief Deny incoming LE Data Channel connection due to resource constraints
3095da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3096da144af5SMatthias Ringwald  */
3097da144af5SMatthias Ringwald 
3098da144af5SMatthias Ringwald uint8_t l2cap_le_decline_connection(uint16_t local_cid){
3099e7d0c9aaSMatthias Ringwald     // get channel
3100e7d0c9aaSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3101e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3102e7d0c9aaSMatthias Ringwald 
3103e7d0c9aaSMatthias Ringwald     // validate state
3104e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3105e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
3106e7d0c9aaSMatthias Ringwald     }
3107e7d0c9aaSMatthias Ringwald 
3108efedfb4cSMatthias Ringwald     // set state decline connection
3109e7d0c9aaSMatthias Ringwald     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
3110e7d0c9aaSMatthias Ringwald     channel->reason = 0x04; // no resources available
3111e7d0c9aaSMatthias Ringwald     l2cap_run();
3112da144af5SMatthias Ringwald     return 0;
3113da144af5SMatthias Ringwald }
3114da144af5SMatthias Ringwald 
31157dafa750SMatthias Ringwald uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
3116da144af5SMatthias Ringwald     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
3117efedfb4cSMatthias Ringwald     uint16_t * out_local_cid) {
3118efedfb4cSMatthias Ringwald 
31197dafa750SMatthias Ringwald     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
3120da144af5SMatthias Ringwald 
31217dafa750SMatthias Ringwald 
31227dafa750SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
31237dafa750SMatthias Ringwald     if (!connection) {
31247dafa750SMatthias Ringwald         log_error("no hci_connection for handle 0x%04x", con_handle);
31257dafa750SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
31267dafa750SMatthias Ringwald     }
31277dafa750SMatthias Ringwald 
31287dafa750SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, connection->address, connection->address_type, psm, mtu, security_level);
3129da144af5SMatthias Ringwald     if (!channel) {
3130da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
3131da144af5SMatthias Ringwald     }
3132e7d0c9aaSMatthias Ringwald     log_info("l2cap_le_create_channel %p", channel);
3133da144af5SMatthias Ringwald 
3134da144af5SMatthias Ringwald     // store local_cid
3135da144af5SMatthias Ringwald     if (out_local_cid){
3136da144af5SMatthias Ringwald        *out_local_cid = channel->local_cid;
3137da144af5SMatthias Ringwald     }
3138da144af5SMatthias Ringwald 
31397dafa750SMatthias Ringwald     // provide buffer
31407dafa750SMatthias Ringwald     channel->con_handle = con_handle;
3141cd529728SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
31427dafa750SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
314385aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
314485aeef60SMatthias Ringwald     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
314585aeef60SMatthias Ringwald 
3146efedfb4cSMatthias Ringwald     // add to connections list
3147efedfb4cSMatthias Ringwald     btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
3148efedfb4cSMatthias Ringwald 
31497dafa750SMatthias Ringwald     // go
315063f0ac45SMatthias Ringwald     l2cap_run();
3151da144af5SMatthias Ringwald     return 0;
3152da144af5SMatthias Ringwald }
3153da144af5SMatthias Ringwald 
3154da144af5SMatthias Ringwald /**
3155da144af5SMatthias Ringwald  * @brief Provide credtis for LE Data Channel
3156da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3157da144af5SMatthias Ringwald  * @param credits               Number additional credits for peer
3158da144af5SMatthias Ringwald  */
315964e11ca9SMatthias Ringwald uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
316063f0ac45SMatthias Ringwald 
316163f0ac45SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
316263f0ac45SMatthias Ringwald     if (!channel) {
316363f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
316463f0ac45SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
316563f0ac45SMatthias Ringwald     }
316663f0ac45SMatthias Ringwald 
3167efedfb4cSMatthias Ringwald     // check state
316863f0ac45SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN){
316963f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
317063f0ac45SMatthias Ringwald     }
317163f0ac45SMatthias Ringwald 
317263f0ac45SMatthias Ringwald     // assert incoming credits + credits <= 0xffff
317363f0ac45SMatthias Ringwald     uint32_t total_credits = channel->credits_incoming;
317463f0ac45SMatthias Ringwald     total_credits += channel->new_credits_incoming;
317563f0ac45SMatthias Ringwald     total_credits += credits;
317663f0ac45SMatthias Ringwald     if (total_credits > 0xffff){
317763f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
317863f0ac45SMatthias Ringwald             channel->new_credits_incoming, credits);
317963f0ac45SMatthias Ringwald     }
318063f0ac45SMatthias Ringwald 
3181efedfb4cSMatthias Ringwald     // set credits_granted
318263f0ac45SMatthias Ringwald     channel->new_credits_incoming += credits;
318363f0ac45SMatthias Ringwald 
318463f0ac45SMatthias Ringwald     // go
318563f0ac45SMatthias Ringwald     l2cap_run();
3186da144af5SMatthias Ringwald     return 0;
3187da144af5SMatthias Ringwald }
3188da144af5SMatthias Ringwald 
3189da144af5SMatthias Ringwald /**
3190da144af5SMatthias Ringwald  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
3191da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3192da144af5SMatthias Ringwald  */
319364e11ca9SMatthias Ringwald int l2cap_le_can_send_now(uint16_t local_cid){
319444276248SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
319544276248SMatthias Ringwald     if (!channel) {
319644276248SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
3197da144af5SMatthias Ringwald         return 0;
3198da144af5SMatthias Ringwald     }
3199da144af5SMatthias Ringwald 
320044276248SMatthias Ringwald     // check state
320144276248SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN) return 0;
320244276248SMatthias Ringwald 
320344276248SMatthias Ringwald     // check queue
320444276248SMatthias Ringwald     if (channel->send_sdu_buffer) return 0;
320544276248SMatthias Ringwald 
320644276248SMatthias Ringwald     // fine, go ahead
320744276248SMatthias Ringwald     return 1;
320844276248SMatthias Ringwald }
320944276248SMatthias Ringwald 
3210da144af5SMatthias Ringwald /**
3211da144af5SMatthias Ringwald  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
3212da144af5SMatthias Ringwald  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
3213da144af5SMatthias Ringwald  *       so packet handler should be ready to handle it
3214da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3215da144af5SMatthias Ringwald  */
321664e11ca9SMatthias Ringwald uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
321744276248SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
321844276248SMatthias Ringwald     if (!channel) {
321944276248SMatthias Ringwald         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
322044276248SMatthias Ringwald         return 0;
322144276248SMatthias Ringwald     }
322244276248SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
322344276248SMatthias Ringwald     l2cap_le_notify_channel_can_send(channel);
3224da144af5SMatthias Ringwald     return 0;
3225da144af5SMatthias Ringwald }
3226da144af5SMatthias Ringwald 
3227da144af5SMatthias Ringwald /**
3228da144af5SMatthias Ringwald  * @brief Send data via LE Data Channel
3229da144af5SMatthias Ringwald  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
3230da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3231da144af5SMatthias Ringwald  * @param data                  data to send
3232da144af5SMatthias Ringwald  * @param size                  data size
3233da144af5SMatthias Ringwald  */
323464e11ca9SMatthias Ringwald uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
323564e11ca9SMatthias Ringwald 
323664e11ca9SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
323764e11ca9SMatthias Ringwald     if (!channel) {
323864e11ca9SMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
3239828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
324064e11ca9SMatthias Ringwald     }
324164e11ca9SMatthias Ringwald 
324264e11ca9SMatthias Ringwald     if (len > channel->remote_mtu){
324364e11ca9SMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
324464e11ca9SMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
324564e11ca9SMatthias Ringwald     }
324664e11ca9SMatthias Ringwald 
32477f107edaSMatthias Ringwald     if (channel->send_sdu_buffer){
324864e11ca9SMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
324964e11ca9SMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
325064e11ca9SMatthias Ringwald     }
325164e11ca9SMatthias Ringwald 
32527f107edaSMatthias Ringwald     channel->send_sdu_buffer = data;
32537f107edaSMatthias Ringwald     channel->send_sdu_len    = len;
32547f107edaSMatthias Ringwald     channel->send_sdu_pos    = 0;
325564e11ca9SMatthias Ringwald 
32567f107edaSMatthias Ringwald     l2cap_run();
32577f107edaSMatthias Ringwald     return 0;
3258da144af5SMatthias Ringwald }
3259da144af5SMatthias Ringwald 
3260da144af5SMatthias Ringwald /**
3261da144af5SMatthias Ringwald  * @brief Disconnect from LE Data Channel
3262da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3263da144af5SMatthias Ringwald  */
3264828a7f7aSMatthias Ringwald uint8_t l2cap_le_disconnect(uint16_t local_cid)
3265da144af5SMatthias Ringwald {
3266828a7f7aSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3267828a7f7aSMatthias Ringwald     if (!channel) {
3268828a7f7aSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
3269828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3270828a7f7aSMatthias Ringwald     }
3271828a7f7aSMatthias Ringwald 
3272828a7f7aSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3273828a7f7aSMatthias Ringwald     l2cap_run();
3274da144af5SMatthias Ringwald     return 0;
3275da144af5SMatthias Ringwald }
3276da144af5SMatthias Ringwald 
32777f02f414SMatthias Ringwald #endif
3278