xref: /btstack/src/l2cap.c (revision f85ade6bf64b3001df9ae83fa533f2a54c161494)
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);
1100*f85ade6bSMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT, 0, channel->set_final_bit_after_packet_with_poll_bit_set, channel->expected_tx_seq);
1101*f85ade6bSMatthias Ringwald             channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1102df2191a7SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
1103df2191a7SMatthias Ringwald             continue;
1104df2191a7SMatthias Ringwald         }
11057b7901d8SMatthias Ringwald 
11067b7901d8SMatthias Ringwald         if (channel->srej_active){
11077b7901d8SMatthias Ringwald             int i;
11087b7901d8SMatthias Ringwald             for (i=0;i<channel->num_tx_buffers;i++){
11097b7901d8SMatthias Ringwald                 l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
11107b7901d8SMatthias Ringwald                 if (tx_state->retransmission_requested) {
11117b7901d8SMatthias Ringwald                     tx_state->retransmission_requested = 0;
1112d2afdd38SMatthias Ringwald                     uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set;
1113d2afdd38SMatthias Ringwald                     channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1114d2afdd38SMatthias Ringwald                     l2cap_ertm_send_information_frame(channel, i, final);
11157b7901d8SMatthias Ringwald                     break;
11167b7901d8SMatthias Ringwald                 }
11177b7901d8SMatthias Ringwald             }
11187b7901d8SMatthias Ringwald             if (i == channel->num_tx_buffers){
11197b7901d8SMatthias Ringwald                 // no retransmission request found
11207b7901d8SMatthias Ringwald                 channel->srej_active = 0;
11217b7901d8SMatthias Ringwald             } else {
11227b7901d8SMatthias Ringwald                 // packet was sent
11237b7901d8SMatthias Ringwald                 continue;
11247b7901d8SMatthias Ringwald             }
11257b7901d8SMatthias Ringwald         }
112638f62777SMatthias Ringwald #endif
112738f62777SMatthias Ringwald 
11282cd0be45Smatthias.ringwald     }
112909e9d05bSMatthias Ringwald #endif
1130da886c03S[email protected] 
1131cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1132efedfb4cSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1133efedfb4cSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
11347f107edaSMatthias Ringwald         uint8_t  * acl_buffer;
11357f107edaSMatthias Ringwald         uint8_t  * l2cap_payload;
11367f107edaSMatthias Ringwald         uint16_t pos;
11377f107edaSMatthias Ringwald         uint16_t payload_size;
1138efedfb4cSMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1139efedfb4cSMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1140efedfb4cSMatthias Ringwald         switch (channel->state){
11415cb87675SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
11425cb87675SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
11435cb87675SMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
11445cb87675SMatthias Ringwald                 // le psm, source cid, mtu, mps, initial credits
11451b8b8d05SMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
114663f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
114763f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
114863f0ac45SMatthias 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);
11495cb87675SMatthias Ringwald                 break;
115023017473SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
115123017473SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
115223017473SMatthias Ringwald                 // TODO: support larger MPS
115323017473SMatthias Ringwald                 channel->state = L2CAP_STATE_OPEN;
115463f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
115563f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
115663f0ac45SMatthias 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);
115764e11ca9SMatthias Ringwald                 // notify client
115844276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0);
115923017473SMatthias Ringwald                 break;
1160e7d0c9aaSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
1161e7d0c9aaSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1162e7d0c9aaSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
116363f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
1164e7d0c9aaSMatthias Ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1165e7d0c9aaSMatthias Ringwald                 l2cap_stop_rtx(channel);
1166e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1167e7d0c9aaSMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
1168e7d0c9aaSMatthias Ringwald                 break;
11697f107edaSMatthias Ringwald             case L2CAP_STATE_OPEN:
117085aeef60SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
117185aeef60SMatthias Ringwald 
117285aeef60SMatthias Ringwald                 // send credits
117385aeef60SMatthias Ringwald                 if (channel->new_credits_incoming){
117485aeef60SMatthias Ringwald                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
117585aeef60SMatthias Ringwald                     channel->local_sig_id = l2cap_next_sig_id();
117685aeef60SMatthias Ringwald                     uint16_t new_credits = channel->new_credits_incoming;
117785aeef60SMatthias Ringwald                     channel->new_credits_incoming = 0;
117885aeef60SMatthias Ringwald                     channel->credits_incoming += new_credits;
117985aeef60SMatthias Ringwald                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
118085aeef60SMatthias Ringwald                     break;
118185aeef60SMatthias Ringwald                 }
118285aeef60SMatthias Ringwald 
118385aeef60SMatthias Ringwald                 // send data
11847f107edaSMatthias Ringwald                 if (!channel->send_sdu_buffer) break;
11857f107edaSMatthias Ringwald                 if (!channel->credits_outgoing) break;
118685aeef60SMatthias Ringwald 
11877f107edaSMatthias Ringwald                 // send part of SDU
11887f107edaSMatthias Ringwald                 hci_reserve_packet_buffer();
11897f107edaSMatthias Ringwald                 acl_buffer = hci_get_outgoing_packet_buffer();
11907f107edaSMatthias Ringwald                 l2cap_payload = acl_buffer + 8;
11917f107edaSMatthias Ringwald                 pos = 0;
11927f107edaSMatthias Ringwald                 if (!channel->send_sdu_pos){
11937f107edaSMatthias Ringwald                     // store SDU len
11947f107edaSMatthias Ringwald                     channel->send_sdu_pos += 2;
11957f107edaSMatthias Ringwald                     little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
11967f107edaSMatthias Ringwald                     pos += 2;
11977f107edaSMatthias Ringwald                 }
11987f107edaSMatthias Ringwald                 payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
119985aeef60SMatthias Ringwald                 log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
12007f107edaSMatthias Ringwald                 memcpy(&l2cap_payload[pos], &channel->send_sdu_buffer[channel->send_sdu_pos-2], payload_size); // -2 for virtual SDU len
12017f107edaSMatthias Ringwald                 pos += payload_size;
12027f107edaSMatthias Ringwald                 channel->send_sdu_pos += payload_size;
1203f511cefaSMatthias Ringwald                 l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
12047f107edaSMatthias Ringwald                 // done
12057f107edaSMatthias Ringwald 
120685aeef60SMatthias Ringwald                 channel->credits_outgoing--;
12077f107edaSMatthias Ringwald 
12087f107edaSMatthias Ringwald                 if (channel->send_sdu_pos >= channel->send_sdu_len + 2){
12097f107edaSMatthias Ringwald                     channel->send_sdu_buffer = NULL;
121044276248SMatthias Ringwald                     // send done event
121144276248SMatthias Ringwald                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
121244276248SMatthias Ringwald                     // inform about can send now
121344276248SMatthias Ringwald                     l2cap_le_notify_channel_can_send(channel);
12147f107edaSMatthias Ringwald                 }
12157f107edaSMatthias Ringwald                 hci_send_acl_packet_buffer(8 + pos);
12167f107edaSMatthias Ringwald                 break;
1217828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1218828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1219828a7f7aSMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
1220828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1221828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1222828a7f7aSMatthias Ringwald                 break;
1223828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1224828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1225828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1226828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1227828a7f7aSMatthias Ringwald                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
1228828a7f7aSMatthias Ringwald                 break;
1229efedfb4cSMatthias Ringwald             default:
1230efedfb4cSMatthias Ringwald                 break;
1231efedfb4cSMatthias Ringwald         }
1232efedfb4cSMatthias Ringwald     }
123309e9d05bSMatthias Ringwald #endif
1234efedfb4cSMatthias Ringwald 
123509e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
1236da886c03S[email protected]     // send l2cap con paramter update if necessary
1237da886c03S[email protected]     hci_connections_get_iterator(&it);
1238665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
1239665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
12405d14fa8fSMatthias Ringwald         if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue;
1241b68d7bc3SMatthias Ringwald         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
1242da886c03S[email protected]         switch (connection->le_con_parameter_update_state){
1243b68d7bc3SMatthias Ringwald             case CON_PARAMETER_UPDATE_SEND_REQUEST:
1244b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1245b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier,
1246b68d7bc3SMatthias Ringwald                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
1247b68d7bc3SMatthias Ringwald                 break;
1248da886c03S[email protected]             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
1249b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
1250b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
1251da886c03S[email protected]                 break;
1252da886c03S[email protected]             case CON_PARAMETER_UPDATE_DENY:
1253b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1254b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
1255da886c03S[email protected]                 break;
1256da886c03S[email protected]             default:
1257da886c03S[email protected]                 break;
1258da886c03S[email protected]         }
1259da886c03S[email protected]     }
12604d7157c3S[email protected] #endif
1261da886c03S[email protected] 
126222c29ab4SMatthias Ringwald     // log_info("l2cap_run: exit");
12632cd0be45Smatthias.ringwald }
12642cd0be45Smatthias.ringwald 
126509e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1266fc64f94aSMatthias Ringwald static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
12672df5dadcS[email protected]     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
12685533f01eS[email protected]         log_info("l2cap_handle_connection_complete expected state");
12692df5dadcS[email protected]         // success, start l2cap handshake
1270fc64f94aSMatthias Ringwald         channel->con_handle = con_handle;
12712df5dadcS[email protected]         // check remote SSP feature first
12722df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
12732df5dadcS[email protected]     }
12742df5dadcS[email protected] }
12752df5dadcS[email protected] 
12761b9cb13dSMatthias Ringwald static void l2cap_ready_to_connect(l2cap_channel_t * channel){
12771b9cb13dSMatthias Ringwald 
12781b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
127927e0774aSMatthias Ringwald     // assumption: outgoing connection
12801b9cb13dSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
12811b9cb13dSMatthias Ringwald     if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
12821b9cb13dSMatthias Ringwald         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
12831b9cb13dSMatthias Ringwald         channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
12841b9cb13dSMatthias Ringwald         return;
12851b9cb13dSMatthias Ringwald     }
12861b9cb13dSMatthias Ringwald #endif
12871b9cb13dSMatthias Ringwald 
12881b9cb13dSMatthias Ringwald     // fine, go ahead
12891b9cb13dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
12901b9cb13dSMatthias Ringwald }
12911b9cb13dSMatthias Ringwald 
12922df5dadcS[email protected] static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
12932df5dadcS[email protected]     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
12942df5dadcS[email protected] 
12952df5dadcS[email protected]     // we have been waiting for remote supported features, if both support SSP,
1296ac301f95S[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));
1297fc64f94aSMatthias Ringwald     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
12982df5dadcS[email protected]         // request security level 2
12992df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
1300fc64f94aSMatthias Ringwald         gap_request_security_level(channel->con_handle, LEVEL_2);
13012df5dadcS[email protected]         return;
13022df5dadcS[email protected]     }
13031b9cb13dSMatthias Ringwald 
13041b9cb13dSMatthias Ringwald     l2cap_ready_to_connect(channel);
13052df5dadcS[email protected] }
130609e9d05bSMatthias Ringwald #endif
13072df5dadcS[email protected] 
130809e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
1309da144af5SMatthias 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,
1310da144af5SMatthias Ringwald     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
1311da144af5SMatthias Ringwald 
1312da144af5SMatthias Ringwald     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1313da144af5SMatthias Ringwald     if (!channel) {
1314da144af5SMatthias Ringwald         return NULL;
1315da144af5SMatthias Ringwald     }
1316da144af5SMatthias Ringwald 
1317da144af5SMatthias Ringwald      // Init memory (make valgrind happy)
1318da144af5SMatthias Ringwald     memset(channel, 0, sizeof(l2cap_channel_t));
1319da144af5SMatthias Ringwald 
1320da144af5SMatthias Ringwald     // fill in
1321da144af5SMatthias Ringwald     channel->packet_handler = packet_handler;
1322da144af5SMatthias Ringwald     bd_addr_copy(channel->address, address);
1323da144af5SMatthias Ringwald     channel->address_type = address_type;
1324da144af5SMatthias Ringwald     channel->psm = psm;
1325da144af5SMatthias Ringwald     channel->local_mtu  = local_mtu;
1326da144af5SMatthias Ringwald     channel->remote_mtu = L2CAP_MINIMAL_MTU;
1327da144af5SMatthias Ringwald     channel->required_security_level = security_level;
1328da144af5SMatthias Ringwald 
1329da144af5SMatthias Ringwald     //
1330da144af5SMatthias Ringwald     channel->local_cid = l2cap_next_local_cid();
1331da144af5SMatthias Ringwald     channel->con_handle = 0;
1332da144af5SMatthias Ringwald 
1333da144af5SMatthias Ringwald     // set initial state
1334da144af5SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
1335da144af5SMatthias Ringwald     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
1336da144af5SMatthias Ringwald     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
1337da144af5SMatthias Ringwald     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
133838f62777SMatthias Ringwald 
1339da144af5SMatthias Ringwald     return channel;
1340da144af5SMatthias Ringwald }
134109e9d05bSMatthias Ringwald #endif
134209e9d05bSMatthias Ringwald 
134309e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1344da144af5SMatthias Ringwald 
13459077cb15SMatthias Ringwald /**
13469077cb15SMatthias Ringwald  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
13479077cb15SMatthias Ringwald  * @param packet_handler
13489077cb15SMatthias Ringwald  * @param address
13499077cb15SMatthias Ringwald  * @param psm
13509077cb15SMatthias Ringwald  * @param mtu
13519077cb15SMatthias Ringwald  * @param local_cid
13529077cb15SMatthias Ringwald  */
13539077cb15SMatthias Ringwald 
13549d139fbaSMatthias 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){
13559d139fbaSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
13569d139fbaSMatthias Ringwald     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1357da144af5SMatthias Ringwald 
13589d139fbaSMatthias 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);
1359da144af5SMatthias Ringwald 
1360da144af5SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
1361fc64f94aSMatthias Ringwald     if (!channel) {
13629077cb15SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
13639077cb15SMatthias Ringwald     }
13649077cb15SMatthias Ringwald 
13651b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
13661b9cb13dSMatthias Ringwald     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
13671b9cb13dSMatthias Ringwald #endif
13681b9cb13dSMatthias Ringwald 
13699077cb15SMatthias Ringwald     // add to connections list
1370fc64f94aSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
13719077cb15SMatthias Ringwald 
13729077cb15SMatthias Ringwald     // store local_cid
13739077cb15SMatthias Ringwald     if (out_local_cid){
1374fc64f94aSMatthias Ringwald        *out_local_cid = channel->local_cid;
13759077cb15SMatthias Ringwald     }
13769077cb15SMatthias Ringwald 
13779077cb15SMatthias Ringwald     // check if hci connection is already usable
13789077cb15SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
13799077cb15SMatthias Ringwald     if (conn){
1380add0254bSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
1381fc64f94aSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
13829077cb15SMatthias Ringwald         // check if remote supported fearures are already received
13839077cb15SMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
1384fc64f94aSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
13859077cb15SMatthias Ringwald         }
13869077cb15SMatthias Ringwald     }
13879077cb15SMatthias Ringwald 
13889077cb15SMatthias Ringwald     l2cap_run();
13899077cb15SMatthias Ringwald 
13909077cb15SMatthias Ringwald     return 0;
13919077cb15SMatthias Ringwald }
13929077cb15SMatthias Ringwald 
13931b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
13947b181629SMatthias Ringwald 
1395843bae5dSMatthias Ringwald static uint8_t l2cap_ertm_validate_local_config(uint8_t max_transmit, uint16_t retransmission_timeout_ms, uint16_t monitor_timeout_ms,
1396843bae5dSMatthias Ringwald     uint16_t local_mtu, uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size){
1397843bae5dSMatthias Ringwald 
13982b70d705SMatthias Ringwald     UNUSED(buffer);
13992b70d705SMatthias Ringwald     UNUSED(size);
14002b70d705SMatthias Ringwald 
14012b70d705SMatthias Ringwald     uint8_t result = ERROR_CODE_SUCCESS;
14022b70d705SMatthias Ringwald     if (max_transmit < 1){
14032b70d705SMatthias Ringwald         log_error("max_transmit must be >= 1");
14042b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
14052b70d705SMatthias Ringwald     }
14062b70d705SMatthias Ringwald     if (retransmission_timeout_ms < 2000){
14072b70d705SMatthias Ringwald         log_error("retransmission_timeout_ms must be >= 2000 ms");
14082b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
14092b70d705SMatthias Ringwald     }
14102b70d705SMatthias Ringwald     if (monitor_timeout_ms < 12000){
14112b70d705SMatthias Ringwald         log_error("monitor_timeout_ms must be >= 12000 ms");
14122b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
14132b70d705SMatthias Ringwald     }
1414843bae5dSMatthias Ringwald     if (local_mtu < 48){
1415843bae5dSMatthias Ringwald         log_error("local_mtu must be >= 48");
1416843bae5dSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
1417843bae5dSMatthias Ringwald     }
14182b70d705SMatthias Ringwald     if (num_rx_buffers < 1){
14192b70d705SMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
14202b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
14212b70d705SMatthias Ringwald     }
14222b70d705SMatthias Ringwald     if (num_tx_buffers < 1){
14232b70d705SMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
14242b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
14252b70d705SMatthias Ringwald     }
14262b70d705SMatthias Ringwald     return result;
14272b70d705SMatthias Ringwald }
14282b70d705SMatthias Ringwald 
1429843bae5dSMatthias Ringwald static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, int ertm_mandatory, uint8_t max_transmit, uint16_t retransmission_timeout_ms,
1430843bae5dSMatthias 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){
14317b181629SMatthias Ringwald 
14327b181629SMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
14337b181629SMatthias Ringwald     channel->ertm_mandatory = ertm_mandatory;
1434bbc0a9e7SMatthias Ringwald     channel->local_max_transmit = max_transmit;
1435bbc0a9e7SMatthias Ringwald     channel->local_retransmission_timeout_ms = retransmission_timeout_ms;
1436bbc0a9e7SMatthias Ringwald     channel->local_monitor_timeout_ms = monitor_timeout_ms;
1437843bae5dSMatthias Ringwald     channel->local_mtu = local_mtu;
14387b181629SMatthias Ringwald     channel->num_rx_buffers = num_rx_buffers;
14397b181629SMatthias Ringwald     channel->num_tx_buffers = num_tx_buffers;
14407b181629SMatthias Ringwald 
1441843bae5dSMatthias Ringwald     // align buffer to 16-byte boundary, just in case
1442843bae5dSMatthias Ringwald     int bytes_till_alignment = 16 - (((uintptr_t) buffer) & 0x0f);
1443843bae5dSMatthias Ringwald     buffer += bytes_till_alignment;
1444843bae5dSMatthias Ringwald     size   -= bytes_till_alignment;
1445843bae5dSMatthias Ringwald 
1446843bae5dSMatthias Ringwald     // setup state buffers
14477b181629SMatthias Ringwald     uint32_t pos = 0;
14487b181629SMatthias Ringwald     channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) &buffer[pos];
14497b181629SMatthias Ringwald     pos += num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
14507b181629SMatthias Ringwald     channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) &buffer[pos];
14517b181629SMatthias Ringwald     pos += num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
1452843bae5dSMatthias Ringwald 
1453843bae5dSMatthias Ringwald     // setup reassembly buffer
1454843bae5dSMatthias Ringwald     channel->reassembly_buffer = &buffer[pos];
1455843bae5dSMatthias Ringwald     pos += local_mtu;
1456843bae5dSMatthias Ringwald 
1457843bae5dSMatthias Ringwald     // divide rest of data equally
1458843bae5dSMatthias Ringwald     channel->local_mps = (size - pos) / (num_rx_buffers + num_tx_buffers);
1459843bae5dSMatthias Ringwald     log_info("Local MPS: %u", channel->local_mtu);
14607b181629SMatthias Ringwald     channel->rx_packets_data = &buffer[pos];
14617b181629SMatthias Ringwald     pos += num_rx_buffers * channel->local_mtu;
14627b181629SMatthias Ringwald     channel->tx_packets_data = &buffer[pos];
14637b181629SMatthias Ringwald }
14647b181629SMatthias Ringwald 
1465501329faSMatthias Ringwald uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
1466501329faSMatthias Ringwald     int ertm_mandatory, uint8_t max_transmit, uint16_t retransmission_timeout_ms, uint16_t monitor_timeout_ms,
1467843bae5dSMatthias 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){
1468501329faSMatthias Ringwald 
1469843bae5dSMatthias Ringwald     log_info("L2CAP_CREATE_CHANNEL addr %s, psm 0x%x, local mtu %u", bd_addr_to_str(address), psm, local_mtu);
14701b9cb13dSMatthias Ringwald 
14712b70d705SMatthias Ringwald     // validate local config
1472843bae5dSMatthias 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);
14732b70d705SMatthias Ringwald     if (result) return result;
14742b70d705SMatthias Ringwald 
1475501329faSMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
14761b9cb13dSMatthias Ringwald     if (!channel) {
14771b9cb13dSMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
14781b9cb13dSMatthias Ringwald     }
14791b9cb13dSMatthias Ringwald 
14807b181629SMatthias Ringwald     // configure ERTM
14817b181629SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_mandatory, max_transmit, retransmission_timeout_ms,
1482843bae5dSMatthias Ringwald         local_mtu, monitor_timeout_ms, num_tx_buffers, num_rx_buffers, buffer, size);
14831b9cb13dSMatthias Ringwald 
14841b9cb13dSMatthias Ringwald     // add to connections list
14851b9cb13dSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
14861b9cb13dSMatthias Ringwald 
14871b9cb13dSMatthias Ringwald     // store local_cid
14881b9cb13dSMatthias Ringwald     if (out_local_cid){
14891b9cb13dSMatthias Ringwald        *out_local_cid = channel->local_cid;
14901b9cb13dSMatthias Ringwald     }
14911b9cb13dSMatthias Ringwald 
14921b9cb13dSMatthias Ringwald     // check if hci connection is already usable
14931b9cb13dSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
14941b9cb13dSMatthias Ringwald     if (conn){
14951b9cb13dSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
14961b9cb13dSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
14971b9cb13dSMatthias Ringwald         // check if remote supported fearures are already received
14981b9cb13dSMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
14991b9cb13dSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
15001b9cb13dSMatthias Ringwald         }
15011b9cb13dSMatthias Ringwald     }
15021b9cb13dSMatthias Ringwald 
15031b9cb13dSMatthias Ringwald     l2cap_run();
15041b9cb13dSMatthias Ringwald 
15051b9cb13dSMatthias Ringwald     return 0;
15061b9cb13dSMatthias Ringwald }
15071b9cb13dSMatthias Ringwald #endif
15081b9cb13dSMatthias Ringwald 
1509ce8f182eSMatthias Ringwald void
1510ce8f182eSMatthias Ringwald l2cap_disconnect(uint16_t local_cid, uint8_t reason){
1511e0abb8e7S[email protected]     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
1512b35f641cSmatthias.ringwald     // find channel for local_cid
1513b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1514f62db1e3Smatthias.ringwald     if (channel) {
1515e7ff783cSmatthias.ringwald         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1516f62db1e3Smatthias.ringwald     }
15172cd0be45Smatthias.ringwald     // process
15182cd0be45Smatthias.ringwald     l2cap_run();
151943625864Smatthias.ringwald }
15201e6aba47Smatthias.ringwald 
1521afde0c52Smatthias.ringwald static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
1522665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1523665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1524665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1525665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1526058e3d6bSMatthias Ringwald         if ( bd_addr_cmp( channel->address, address) != 0) continue;
1527c22aecc9S[email protected]         // channel for this address found
1528c22aecc9S[email protected]         switch (channel->state){
1529c22aecc9S[email protected]             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
1530c22aecc9S[email protected]             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1531afde0c52Smatthias.ringwald                 // failure, forward error code
1532afde0c52Smatthias.ringwald                 l2cap_emit_channel_opened(channel, status);
1533afde0c52Smatthias.ringwald                 // discard channel
15349dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
1535665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1536d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
1537c22aecc9S[email protected]                 break;
1538c22aecc9S[email protected]             default:
1539c22aecc9S[email protected]                 break;
1540afde0c52Smatthias.ringwald         }
1541afde0c52Smatthias.ringwald     }
1542afde0c52Smatthias.ringwald }
1543afde0c52Smatthias.ringwald 
1544afde0c52Smatthias.ringwald static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
1545665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1546665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1547665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1548665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1549058e3d6bSMatthias Ringwald         if ( ! bd_addr_cmp( channel->address, address) ){
15502df5dadcS[email protected]             l2cap_handle_connection_complete(handle, channel);
1551afde0c52Smatthias.ringwald         }
1552afde0c52Smatthias.ringwald     }
15536fdcc387Smatthias.ringwald     // process
15546fdcc387Smatthias.ringwald     l2cap_run();
1555afde0c52Smatthias.ringwald }
155609e9d05bSMatthias Ringwald #endif
1557b448a0e7Smatthias.ringwald 
155833c40538SMatthias Ringwald static void l2cap_notify_channel_can_send(void){
155909e9d05bSMatthias Ringwald 
156009e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
156133c40538SMatthias Ringwald     btstack_linked_list_iterator_t it;
156233c40538SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
156333c40538SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
156433c40538SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
156533c40538SMatthias Ringwald         if (!channel->waiting_for_can_send_now) continue;
1566fc64f94aSMatthias Ringwald         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
156733c40538SMatthias Ringwald         channel->waiting_for_can_send_now = 0;
156834e7e577SMatthias Ringwald         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
156933c40538SMatthias Ringwald     }
157009e9d05bSMatthias Ringwald #endif
157144276248SMatthias Ringwald 
15722125de09SMatthias Ringwald     int i;
15732125de09SMatthias Ringwald     for (i=0;i<L2CAP_FIXED_CHANNEL_TABLE_SIZE;i++){
1574773c4106SMatthias Ringwald         if (!fixed_channels[i].callback) continue;
15752125de09SMatthias Ringwald         if (!fixed_channels[i].waiting_for_can_send_now) continue;
157635454696SMatthias Ringwald         int can_send = 0;
157734e7e577SMatthias Ringwald         if (l2cap_fixed_channel_table_index_is_le(i)){
157835454696SMatthias Ringwald #ifdef ENABLE_BLE
157934e7e577SMatthias Ringwald             can_send = hci_can_send_acl_le_packet_now();
158035454696SMatthias Ringwald #endif
158134e7e577SMatthias Ringwald         } else {
158235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
158334e7e577SMatthias Ringwald             can_send = hci_can_send_acl_classic_packet_now();
158435454696SMatthias Ringwald #endif
158534e7e577SMatthias Ringwald         }
158634e7e577SMatthias Ringwald         if (!can_send) continue;
158734e7e577SMatthias Ringwald         fixed_channels[i].waiting_for_can_send_now = 0;
158834e7e577SMatthias Ringwald         l2cap_emit_can_send_now(fixed_channels[i].callback, l2cap_fixed_channel_table_channel_id_for_index(i));
15892125de09SMatthias Ringwald     }
159033c40538SMatthias Ringwald }
159133c40538SMatthias Ringwald 
1592d9a7306aSMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
1593afde0c52Smatthias.ringwald 
15949ec2630cSMatthias Ringwald     UNUSED(packet_type);
15959ec2630cSMatthias Ringwald     UNUSED(cid);
15969ec2630cSMatthias Ringwald     UNUSED(size);
15979ec2630cSMatthias Ringwald 
1598afde0c52Smatthias.ringwald     bd_addr_t address;
1599afde0c52Smatthias.ringwald     hci_con_handle_t handle;
16002d00edd4Smatthias.ringwald     int hci_con_used;
160109e9d05bSMatthias Ringwald     btstack_linked_list_iterator_t it;
160209e9d05bSMatthias Ringwald 
160309e9d05bSMatthias Ringwald     // avoid unused warnings
1604f3963406SMatthias Ringwald     UNUSED(address);
1605f3963406SMatthias Ringwald     UNUSED(hci_con_used);
1606f3963406SMatthias Ringwald     UNUSED(it);
1607f22209dfSMatthias Ringwald     UNUSED(handle);
1608afde0c52Smatthias.ringwald 
16090e2df43fSMatthias Ringwald     switch(hci_event_packet_get_type(packet)){
1610afde0c52Smatthias.ringwald 
161109e9d05bSMatthias Ringwald         // Notify channel packet handler if they can send now
161209e9d05bSMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
161309e9d05bSMatthias Ringwald         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
161409e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
161509e9d05bSMatthias Ringwald             l2cap_notify_channel_can_send();
161609e9d05bSMatthias Ringwald             break;
161709e9d05bSMatthias Ringwald 
161809e9d05bSMatthias Ringwald         case HCI_EVENT_COMMAND_STATUS:
161909e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
162009e9d05bSMatthias Ringwald             break;
162109e9d05bSMatthias Ringwald 
162209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1623afde0c52Smatthias.ringwald         // handle connection complete events
1624afde0c52Smatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
1625724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], address);
1626afde0c52Smatthias.ringwald             if (packet[2] == 0){
1627f8fbdce0SMatthias Ringwald                 handle = little_endian_read_16(packet, 3);
1628afde0c52Smatthias.ringwald                 l2cap_handle_connection_success_for_addr(address, handle);
1629afde0c52Smatthias.ringwald             } else {
1630afde0c52Smatthias.ringwald                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
1631afde0c52Smatthias.ringwald             }
1632afde0c52Smatthias.ringwald             break;
1633afde0c52Smatthias.ringwald 
1634afde0c52Smatthias.ringwald         // handle successful create connection cancel command
1635afde0c52Smatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
1636073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
1637afde0c52Smatthias.ringwald                 if (packet[5] == 0){
1638724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[6], address);
1639afde0c52Smatthias.ringwald                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
1640afde0c52Smatthias.ringwald                     l2cap_handle_connection_failed_for_addr(address, 0x16);
164103cfbabcSmatthias.ringwald                 }
16421e6aba47Smatthias.ringwald             }
164339d59809Smatthias.ringwald             l2cap_run();    // try sending signaling packets first
164439d59809Smatthias.ringwald             break;
164509e9d05bSMatthias Ringwald #endif
164627a923d0Smatthias.ringwald 
16471e6aba47Smatthias.ringwald         // handle disconnection complete events
1648afde0c52Smatthias.ringwald         case HCI_EVENT_DISCONNECTION_COMPLETE:
1649c22aecc9S[email protected]             // send l2cap disconnect events for all channels on this handle and free them
165009e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1651d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1652665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1653665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1654665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1655fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
165615ec09bbSmatthias.ringwald                 l2cap_emit_channel_closed(channel);
16579dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
1658665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1659d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
166027a923d0Smatthias.ringwald             }
166109e9d05bSMatthias Ringwald #endif
1662a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1663d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1664991fea48SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1665991fea48SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1666991fea48SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1667991fea48SMatthias Ringwald                 if (channel->con_handle != handle) continue;
1668991fea48SMatthias Ringwald                 l2cap_emit_channel_closed(channel);
1669991fea48SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1670991fea48SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
1671991fea48SMatthias Ringwald             }
1672991fea48SMatthias Ringwald #endif
1673afde0c52Smatthias.ringwald             break;
1674fcadd0caSmatthias.ringwald 
1675ee091cf1Smatthias.ringwald         // HCI Connection Timeouts
167609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1677afde0c52Smatthias.ringwald         case L2CAP_EVENT_TIMEOUT_CHECK:
1678f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
1679bd04d84aSMatthias Ringwald             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
168080ca58a0Smatthias.ringwald             if (hci_authentication_active_for_handle(handle)) break;
16812d00edd4Smatthias.ringwald             hci_con_used = 0;
1682665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1683665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1684665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1685fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
16862d00edd4Smatthias.ringwald                 hci_con_used = 1;
1687c22aecc9S[email protected]                 break;
1688ee091cf1Smatthias.ringwald             }
16892d00edd4Smatthias.ringwald             if (hci_con_used) break;
1690d94d3cafS[email protected]             if (!hci_can_send_command_packet_now()) break;
16919edc8742Smatthias.ringwald             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
1692afde0c52Smatthias.ringwald             break;
1693ee091cf1Smatthias.ringwald 
1694df3354fcS[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1695f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1696665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1697665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1698665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1699fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
17002df5dadcS[email protected]                 l2cap_handle_remote_supported_features_received(channel);
1701df3354fcS[email protected]                 break;
1702df3354fcS[email protected]             }
1703c22aecc9S[email protected]             break;
1704df3354fcS[email protected] 
17055611a760SMatthias Ringwald         case GAP_EVENT_SECURITY_LEVEL:
1706f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
1707bd63148eS[email protected]             log_info("l2cap - security level update");
1708665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1709665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1710665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1711fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
17125533f01eS[email protected] 
1713bd63148eS[email protected]                 log_info("l2cap - state %u", channel->state);
1714bd63148eS[email protected] 
1715e569dfd9SMatthias Ringwald                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
17165533f01eS[email protected]                 gap_security_level_t required_level = channel->required_security_level;
17175533f01eS[email protected] 
1718df3354fcS[email protected]                 switch (channel->state){
1719df3354fcS[email protected]                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
17205533f01eS[email protected]                         if (actual_level >= required_level){
172152606043SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
172252606043SMatthias Ringwald                             // we need to know if ERTM is supported before sending a config response
172352606043SMatthias Ringwald                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
172452606043SMatthias Ringwald                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
172552606043SMatthias Ringwald                             channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
172652606043SMatthias Ringwald #else
1727f85a9399S[email protected]                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
172844276248SMatthias Ringwald                             l2cap_emit_incoming_connection(channel);
172952606043SMatthias Ringwald #endif
17301eb2563eS[email protected]                         } else {
1731775ecc36SMatthias Ringwald                             channel->reason = 0x0003; // security block
17321eb2563eS[email protected]                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
17331eb2563eS[email protected]                         }
1734df3354fcS[email protected]                         break;
1735df3354fcS[email protected] 
1736df3354fcS[email protected]                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
17375533f01eS[email protected]                         if (actual_level >= required_level){
17381b9cb13dSMatthias Ringwald                             l2cap_ready_to_connect(channel);
1739df3354fcS[email protected]                         } else {
1740df3354fcS[email protected]                             // disconnnect, authentication not good enough
1741df3354fcS[email protected]                             hci_disconnect_security_block(handle);
1742df3354fcS[email protected]                         }
1743df3354fcS[email protected]                         break;
1744df3354fcS[email protected] 
1745df3354fcS[email protected]                     default:
1746df3354fcS[email protected]                         break;
1747df3354fcS[email protected]                 }
1748f85a9399S[email protected]             }
1749f85a9399S[email protected]             break;
175009e9d05bSMatthias Ringwald #endif
1751f85a9399S[email protected] 
1752afde0c52Smatthias.ringwald         default:
1753afde0c52Smatthias.ringwald             break;
1754afde0c52Smatthias.ringwald     }
1755afde0c52Smatthias.ringwald 
1756bd63148eS[email protected]     l2cap_run();
17571e6aba47Smatthias.ringwald }
17581e6aba47Smatthias.ringwald 
1759e74c5f58SMatthias 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){
17604cf56b4aSmatthias.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."
17612b360848Smatthias.ringwald     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
17622b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].handle = handle;
17632b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].code = code;
17642b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].sig_id = sig_id;
1765e74c5f58SMatthias Ringwald         signaling_responses[signaling_responses_pending].cid = cid;
17662b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].data = data;
17672b360848Smatthias.ringwald         signaling_responses_pending++;
17682b360848Smatthias.ringwald         l2cap_run();
17692b360848Smatthias.ringwald     }
17702b360848Smatthias.ringwald }
17712b360848Smatthias.ringwald 
177209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
177309e9d05bSMatthias Ringwald static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
177409e9d05bSMatthias Ringwald     channel->remote_sig_id = identifier;
177509e9d05bSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
177609e9d05bSMatthias Ringwald     l2cap_run();
177709e9d05bSMatthias Ringwald }
177809e9d05bSMatthias Ringwald 
1779b35f641cSmatthias.ringwald static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
1780645658c9Smatthias.ringwald 
17819da54300S[email protected]     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
1782645658c9Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
1783645658c9Smatthias.ringwald     if (!service) {
1784645658c9Smatthias.ringwald         // 0x0002 PSM not supported
1785e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
1786645658c9Smatthias.ringwald         return;
1787645658c9Smatthias.ringwald     }
1788645658c9Smatthias.ringwald 
17895061f3afS[email protected]     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
1790645658c9Smatthias.ringwald     if (!hci_connection) {
17912b360848Smatthias.ringwald         //
17929da54300S[email protected]         log_error("no hci_connection for handle %u", handle);
1793645658c9Smatthias.ringwald         return;
1794645658c9Smatthias.ringwald     }
17952bd8b7e7S[email protected] 
1796645658c9Smatthias.ringwald     // alloc structure
17979da54300S[email protected]     // log_info("l2cap_handle_connection_request register channel");
1798da144af5SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, hci_connection->address, BD_ADDR_TYPE_CLASSIC,
1799da144af5SMatthias Ringwald     psm, service->mtu, service->required_security_level);
18002b360848Smatthias.ringwald     if (!channel){
18012b360848Smatthias.ringwald         // 0x0004 No resources available
1802e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
18032b360848Smatthias.ringwald         return;
18042b360848Smatthias.ringwald     }
1805da144af5SMatthias Ringwald 
1806fc64f94aSMatthias Ringwald     channel->con_handle = handle;
1807b35f641cSmatthias.ringwald     channel->remote_cid = source_cid;
1808b1988dceSmatthias.ringwald     channel->remote_sig_id = sig_id;
1809645658c9Smatthias.ringwald 
1810f53da564S[email protected]     // limit local mtu to max acl packet length - l2cap header
18112985cb84Smatthias.ringwald     if (channel->local_mtu > l2cap_max_mtu()) {
18122985cb84Smatthias.ringwald         channel->local_mtu = l2cap_max_mtu();
18139775e25bSmatthias.ringwald     }
18149775e25bSmatthias.ringwald 
1815645658c9Smatthias.ringwald     // set initial state
1816df3354fcS[email protected]     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
1817a24785d0SMatthias Ringwald     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
1818e405ae81Smatthias.ringwald 
1819645658c9Smatthias.ringwald     // add to connections list
1820665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1821645658c9Smatthias.ringwald 
1822f85a9399S[email protected]     // assert security requirements
18231eb2563eS[email protected]     gap_request_security_level(handle, channel->required_security_level);
1824e405ae81Smatthias.ringwald }
1825645658c9Smatthias.ringwald 
1826ce8f182eSMatthias Ringwald void l2cap_accept_connection(uint16_t local_cid){
1827e0abb8e7S[email protected]     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
1828b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1829e405ae81Smatthias.ringwald     if (!channel) {
1830ce8f182eSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
1831e405ae81Smatthias.ringwald         return;
1832e405ae81Smatthias.ringwald     }
1833e405ae81Smatthias.ringwald 
183443ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
183543ec931dSMatthias Ringwald     // configure L2CAP Basic mode
183643ec931dSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
183743ec931dSMatthias Ringwald #endif
183843ec931dSMatthias Ringwald 
1839552d92a1Smatthias.ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
1840e405ae81Smatthias.ringwald 
1841552d92a1Smatthias.ringwald     // process
1842552d92a1Smatthias.ringwald     l2cap_run();
1843e405ae81Smatthias.ringwald }
1844645658c9Smatthias.ringwald 
184543ec931dSMatthias Ringwald 
184643ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1847843bae5dSMatthias Ringwald uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, int ertm_mandatory, uint8_t max_transmit, uint16_t retransmission_timeout_ms,
1848843bae5dSMatthias 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){
1849501329faSMatthias Ringwald 
185043ec931dSMatthias Ringwald     log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
185143ec931dSMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
185243ec931dSMatthias Ringwald     if (!channel) {
185343ec931dSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
18542b70d705SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
185543ec931dSMatthias Ringwald     }
185643ec931dSMatthias Ringwald 
18572b70d705SMatthias Ringwald     // validate local config
1858843bae5dSMatthias 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);
18592b70d705SMatthias Ringwald     if (result) return result;
18602b70d705SMatthias Ringwald 
186143ec931dSMatthias Ringwald     // configure L2CAP ERTM
1862843bae5dSMatthias 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);
186343ec931dSMatthias Ringwald 
18647b181629SMatthias Ringwald     // continue
186543ec931dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
186643ec931dSMatthias Ringwald 
186743ec931dSMatthias Ringwald     // process
186843ec931dSMatthias Ringwald     l2cap_run();
18692b70d705SMatthias Ringwald 
18702b70d705SMatthias Ringwald     return ERROR_CODE_SUCCESS;
187143ec931dSMatthias Ringwald }
18722a424812SMatthias Ringwald 
187367a3a5b7SMatthias Ringwald uint8_t l2cap_ertm_set_busy(uint16_t local_cid){
18748f1c9639SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
18758f1c9639SMatthias Ringwald     if (!channel) {
18768f1c9639SMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
18778f1c9639SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
18788f1c9639SMatthias Ringwald     }
18792bea1b8dSMatthias Ringwald     if (!channel->local_busy){
18802bea1b8dSMatthias Ringwald         channel->local_busy = 1;
18818f1c9639SMatthias Ringwald         channel->send_supervisor_frame_receiver_not_ready = 1;
18828f1c9639SMatthias Ringwald         l2cap_run();
18832bea1b8dSMatthias Ringwald     }
188467a3a5b7SMatthias Ringwald     return ERROR_CODE_SUCCESS;
188567a3a5b7SMatthias Ringwald }
188667a3a5b7SMatthias Ringwald 
188767a3a5b7SMatthias Ringwald uint8_t l2cap_ertm_set_ready(uint16_t local_cid){
18882bea1b8dSMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
18892bea1b8dSMatthias Ringwald     if (!channel) {
18902bea1b8dSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
18912bea1b8dSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
18922bea1b8dSMatthias Ringwald     }
18932bea1b8dSMatthias Ringwald     if (channel->local_busy){
18942bea1b8dSMatthias Ringwald         channel->local_busy = 0;
18952bea1b8dSMatthias Ringwald         channel->send_supervisor_frame_receiver_ready_poll = 1;
18962bea1b8dSMatthias Ringwald         l2cap_run();
18972bea1b8dSMatthias Ringwald     }
189867a3a5b7SMatthias Ringwald     return ERROR_CODE_SUCCESS;
189967a3a5b7SMatthias Ringwald }
190067a3a5b7SMatthias Ringwald 
19012a424812SMatthias Ringwald static void l2cap_ertm_handle_req_seq(l2cap_channel_t * l2cap_channel, uint8_t req_seq){
19022a424812SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
1903bc4521b7SMatthias Ringwald     while (1){
19042a424812SMatthias Ringwald         tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
1905bc4521b7SMatthias Ringwald         // calc delta
1906bc4521b7SMatthias Ringwald         int delta = (req_seq - tx_state->tx_seq) & 0x03f;
1907bc4521b7SMatthias Ringwald         if (delta == 0) break;  // all packets acknowledged
1908bc4521b7SMatthias Ringwald         if (delta > l2cap_channel->remote_tx_window_size) break;
1909bc4521b7SMatthias Ringwald 
1910bc4521b7SMatthias Ringwald         log_info("RR seq %u => packet with tx_seq %u done", req_seq, tx_state->tx_seq);
1911bc4521b7SMatthias Ringwald 
191262041d70SMatthias Ringwald         // stop retransmission timer
191362041d70SMatthias Ringwald         btstack_run_loop_remove_timer(&tx_state->retransmission_timer);
19142a424812SMatthias Ringwald         l2cap_channel->tx_read_index++;
19152a424812SMatthias Ringwald         if (l2cap_channel->tx_read_index >= l2cap_channel->num_rx_buffers){
19162a424812SMatthias Ringwald             l2cap_channel->tx_read_index = 0;
19172a424812SMatthias Ringwald         }
1918bc4521b7SMatthias Ringwald 
1919bc4521b7SMatthias Ringwald         // no unack packages
1920bc4521b7SMatthias Ringwald         if (l2cap_channel->tx_read_index == l2cap_channel->tx_write_index) break;
19212a424812SMatthias Ringwald     }
19222a424812SMatthias Ringwald }
192367a3a5b7SMatthias Ringwald 
19247b7901d8SMatthias Ringwald static l2cap_ertm_tx_packet_state_t * l2cap_ertm_get_tx_state(l2cap_channel_t * l2cap_channel, uint8_t tx_seq){
19257b7901d8SMatthias Ringwald     int i;
19267b7901d8SMatthias Ringwald     for (i=0;i<l2cap_channel->num_tx_buffers;i++){
19277b7901d8SMatthias Ringwald         l2cap_ertm_tx_packet_state_t * tx_state = &l2cap_channel->tx_packets_state[i];
19287b7901d8SMatthias Ringwald         if (tx_state->tx_seq == tx_seq) return tx_state;
19297b7901d8SMatthias Ringwald     }
19307b7901d8SMatthias Ringwald     return NULL;
19317b7901d8SMatthias Ringwald }
193243ec931dSMatthias Ringwald #endif
193343ec931dSMatthias Ringwald 
193443ec931dSMatthias Ringwald 
19357ef6a7bbSMatthias Ringwald void l2cap_decline_connection(uint16_t local_cid){
19367ef6a7bbSMatthias Ringwald     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
1937b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
1938e405ae81Smatthias.ringwald     if (!channel) {
1939ce8f182eSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
1940e405ae81Smatthias.ringwald         return;
1941e405ae81Smatthias.ringwald     }
1942e7ff783cSmatthias.ringwald     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
19437ef6a7bbSMatthias Ringwald     channel->reason = 0x04; // no resources available
1944e7ff783cSmatthias.ringwald     l2cap_run();
1945645658c9Smatthias.ringwald }
1946645658c9Smatthias.ringwald 
19477f02f414SMatthias Ringwald static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
1948b1988dceSmatthias.ringwald 
1949b1988dceSmatthias.ringwald     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1950b1988dceSmatthias.ringwald 
1951f8fbdce0SMatthias Ringwald     uint16_t flags = little_endian_read_16(command, 6);
195263a7246aSmatthias.ringwald     if (flags & 1) {
195363a7246aSmatthias.ringwald         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
195463a7246aSmatthias.ringwald     }
195563a7246aSmatthias.ringwald 
19562784b77dSmatthias.ringwald     // accept the other's configuration options
1957f8fbdce0SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
19583de7c0caSmatthias.ringwald     uint16_t pos     = 8;
19593de7c0caSmatthias.ringwald     while (pos < end_pos){
196063a7246aSmatthias.ringwald         uint8_t option_hint = command[pos] >> 7;
196163a7246aSmatthias.ringwald         uint8_t option_type = command[pos] & 0x7f;
19623844aeadSMatthias Ringwald         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
196363a7246aSmatthias.ringwald         pos++;
19641dc511deSmatthias.ringwald         uint8_t length = command[pos++];
19651dc511deSmatthias.ringwald         // MTU { type(8): 1, len(8):2, MTU(16) }
196663a7246aSmatthias.ringwald         if (option_type == 1 && length == 2){
1967f8fbdce0SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, pos);
19683844aeadSMatthias Ringwald             log_info("Remote MTU %u", channel->remote_mtu);
19699d139fbaSMatthias Ringwald             if (channel->remote_mtu > l2cap_max_mtu()){
19709d139fbaSMatthias Ringwald                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
19719d139fbaSMatthias Ringwald                 channel->remote_mtu = l2cap_max_mtu();
19729d139fbaSMatthias Ringwald             }
197363a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
197463a7246aSmatthias.ringwald         }
19750fe7a9d0S[email protected]         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
19760fe7a9d0S[email protected]         if (option_type == 2 && length == 2){
1977f8fbdce0SMatthias Ringwald             channel->flush_timeout = little_endian_read_16(command, pos);
19783844aeadSMatthias Ringwald             log_info("Flush timeout: %u ms", channel->flush_timeout);
19790fe7a9d0S[email protected]         }
1980f2fa388dSMatthias Ringwald 
19816dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
19826dca2a0cSMatthias Ringwald         // Retransmission and Flow Control Option
19836dca2a0cSMatthias Ringwald         if (option_type == 4 && length == 9){
19843232a1c6SMatthias Ringwald             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
1985ac8f1300SMatthias Ringwald             switch(channel->mode){
1986ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
198725cd60d3SMatthias Ringwald                     // Store remote config
1988bbc0a9e7SMatthias Ringwald                     channel->remote_tx_window_size = command[pos+1];
1989bbc0a9e7SMatthias Ringwald                     channel->remote_max_transmit   = command[pos+2];
1990bbc0a9e7SMatthias Ringwald                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
1991bbc0a9e7SMatthias Ringwald                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
19923844aeadSMatthias Ringwald                     channel->remote_mps = little_endian_read_16(command, pos + 7);
19933844aeadSMatthias Ringwald                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
1994bbc0a9e7SMatthias Ringwald                         channel->remote_tx_window_size,
1995bbc0a9e7SMatthias Ringwald                         channel->remote_max_transmit,
1996bbc0a9e7SMatthias Ringwald                         channel->remote_retransmission_timeout_ms,
19973844aeadSMatthias Ringwald                         channel->remote_monitor_timeout_ms,
19983844aeadSMatthias Ringwald                         channel->remote_mps);
199925cd60d3SMatthias Ringwald                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
200025cd60d3SMatthias Ringwald                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
200125cd60d3SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2002ac8f1300SMatthias Ringwald                     } else {
2003ac8f1300SMatthias Ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
2004ac8f1300SMatthias Ringwald                     }
2005ac8f1300SMatthias Ringwald                     break;
2006ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
2007ac8f1300SMatthias Ringwald                     switch (mode){
2008ac8f1300SMatthias Ringwald                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2009ac8f1300SMatthias Ringwald                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
2010ac8f1300SMatthias Ringwald                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
2011ac8f1300SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2012ac8f1300SMatthias Ringwald                             }
2013ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
2014ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
2015ac8f1300SMatthias Ringwald                             break;
2016ac8f1300SMatthias Ringwald                         default: // case L2CAP_CHANNEL_MODE_BASIC:
2017ac8f1300SMatthias Ringwald                             // TODO store and evaluate configuration
2018ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
2019ac8f1300SMatthias Ringwald                             break;
2020ac8f1300SMatthias Ringwald                     }
2021ac8f1300SMatthias Ringwald                     break;
2022ac8f1300SMatthias Ringwald                 default:
2023ac8f1300SMatthias Ringwald                     break;
2024ac8f1300SMatthias Ringwald             }
20253232a1c6SMatthias Ringwald         }
20266dca2a0cSMatthias Ringwald #endif
202763a7246aSmatthias.ringwald         // check for unknown options
202863a7246aSmatthias.ringwald         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
2029c177a91cS[email protected]             log_info("l2cap cid %u, unknown options", channel->local_cid);
203063a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
20311dc511deSmatthias.ringwald         }
20321dc511deSmatthias.ringwald         pos += length;
20331dc511deSmatthias.ringwald     }
20342784b77dSmatthias.ringwald }
20352784b77dSmatthias.ringwald 
2036f2fa388dSMatthias Ringwald static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
2037f2fa388dSMatthias Ringwald     log_info("l2cap_signaling_handle_configure_response");
20383232a1c6SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
20393232a1c6SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2040f2fa388dSMatthias Ringwald     uint16_t pos     = 10;
20413232a1c6SMatthias Ringwald     while (pos < end_pos){
20423232a1c6SMatthias Ringwald         uint8_t option_hint = command[pos] >> 7;
20433232a1c6SMatthias Ringwald         uint8_t option_type = command[pos] & 0x7f;
20443232a1c6SMatthias Ringwald         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
20453232a1c6SMatthias Ringwald         pos++;
20463232a1c6SMatthias Ringwald         uint8_t length = command[pos++];
20473232a1c6SMatthias Ringwald 
20483232a1c6SMatthias Ringwald         // Retransmission and Flow Control Option
20493232a1c6SMatthias Ringwald         if (option_type == 4 && length == 9){
2050ac8f1300SMatthias Ringwald             switch (channel->mode){
2051ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2052f2fa388dSMatthias Ringwald                     if (channel->ertm_mandatory){
2053ac8f1300SMatthias Ringwald                         // ??
2054f2fa388dSMatthias Ringwald                     } else {
2055ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
2056ac8f1300SMatthias Ringwald                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2057f2fa388dSMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
20583232a1c6SMatthias Ringwald                         }
20593232a1c6SMatthias Ringwald                     }
2060ac8f1300SMatthias Ringwald                     break;
2061ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
2062ac8f1300SMatthias Ringwald                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2063ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
2064ac8f1300SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2065ac8f1300SMatthias Ringwald                     }
2066ac8f1300SMatthias Ringwald                     break;
2067ac8f1300SMatthias Ringwald                 default:
2068ac8f1300SMatthias Ringwald                     break;
20693232a1c6SMatthias Ringwald             }
2070f2fa388dSMatthias Ringwald         }
20713232a1c6SMatthias Ringwald 
20723232a1c6SMatthias Ringwald         // check for unknown options
20733232a1c6SMatthias Ringwald         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
20743232a1c6SMatthias Ringwald             log_info("l2cap cid %u, unknown options", channel->local_cid);
20753232a1c6SMatthias Ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
20763232a1c6SMatthias Ringwald         }
20773232a1c6SMatthias Ringwald 
20783232a1c6SMatthias Ringwald         pos += length;
20793232a1c6SMatthias Ringwald     }
20803232a1c6SMatthias Ringwald #endif
20813232a1c6SMatthias Ringwald }
20823232a1c6SMatthias Ringwald 
2083fa8473a4Smatthias.ringwald static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
20849da54300S[email protected]     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
208573cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
208673cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
2087019f9b43SMatthias Ringwald     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
2088019f9b43SMatthias Ringwald     if (channel->state == L2CAP_STATE_OPEN) return 0;
2089fa8473a4Smatthias.ringwald     return 1;
2090fa8473a4Smatthias.ringwald }
2091fa8473a4Smatthias.ringwald 
2092fa8473a4Smatthias.ringwald 
20937f02f414SMatthias Ringwald static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
20941e6aba47Smatthias.ringwald 
209500d93d79Smatthias.ringwald     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
209600d93d79Smatthias.ringwald     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
209738e5900eSmatthias.ringwald     uint16_t result = 0;
20981e6aba47Smatthias.ringwald 
20999da54300S[email protected]     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
2100b35f641cSmatthias.ringwald 
21019a011532Smatthias.ringwald     // handle DISCONNECT REQUESTS seperately
21029a011532Smatthias.ringwald     if (code == DISCONNECTION_REQUEST){
21039a011532Smatthias.ringwald         switch (channel->state){
2104fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
21059a011532Smatthias.ringwald             case L2CAP_STATE_OPEN:
21062b83fb7dSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
21079a011532Smatthias.ringwald             case L2CAP_STATE_WAIT_DISCONNECT:
21089a011532Smatthias.ringwald                 l2cap_handle_disconnect_request(channel, identifier);
21099a011532Smatthias.ringwald                 break;
21109a011532Smatthias.ringwald 
21119a011532Smatthias.ringwald             default:
21129a011532Smatthias.ringwald                 // ignore in other states
21139a011532Smatthias.ringwald                 break;
21149a011532Smatthias.ringwald         }
21159a011532Smatthias.ringwald         return;
21169a011532Smatthias.ringwald     }
21179a011532Smatthias.ringwald 
211856081214Smatthias.ringwald     // @STATEMACHINE(l2cap)
21191e6aba47Smatthias.ringwald     switch (channel->state) {
21201e6aba47Smatthias.ringwald 
21211e6aba47Smatthias.ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
21221e6aba47Smatthias.ringwald             switch (code){
21231e6aba47Smatthias.ringwald                 case CONNECTION_RESPONSE:
21245932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2125f8fbdce0SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
212638e5900eSmatthias.ringwald                     switch (result) {
212738e5900eSmatthias.ringwald                         case 0:
2128169f8b28Smatthias.ringwald                             // successful connection
2129f8fbdce0SMatthias Ringwald                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2130fa8473a4Smatthias.ringwald                             channel->state = L2CAP_STATE_CONFIG;
213128ca2b46S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
213238e5900eSmatthias.ringwald                             break;
213338e5900eSmatthias.ringwald                         case 1:
21345932bd7cS[email protected]                             // connection pending. get some coffee, but start the ERTX
21355932bd7cS[email protected]                             l2cap_start_ertx(channel);
213638e5900eSmatthias.ringwald                             break;
213738e5900eSmatthias.ringwald                         default:
2138eb920dbeSmatthias.ringwald                             // channel closed
2139eb920dbeSmatthias.ringwald                             channel->state = L2CAP_STATE_CLOSED;
2140f32b992eSmatthias.ringwald                             // map l2cap connection response result to BTstack status enumeration
214138e5900eSmatthias.ringwald                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
2142eb920dbeSmatthias.ringwald 
2143eb920dbeSmatthias.ringwald                             // drop link key if security block
2144eb920dbeSmatthias.ringwald                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
214515a95bd5SMatthias Ringwald                                 gap_drop_link_key_for_bd_addr(channel->address);
2146eb920dbeSmatthias.ringwald                             }
2147eb920dbeSmatthias.ringwald 
2148eb920dbeSmatthias.ringwald                             // discard channel
2149665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2150d3a9df87Smatthias.ringwald                             btstack_memory_l2cap_channel_free(channel);
215138e5900eSmatthias.ringwald                             break;
21521e6aba47Smatthias.ringwald                     }
21531e6aba47Smatthias.ringwald                     break;
215438e5900eSmatthias.ringwald 
215538e5900eSmatthias.ringwald                 default:
21561e6aba47Smatthias.ringwald                     //@TODO: implement other signaling packets
215738e5900eSmatthias.ringwald                     break;
21581e6aba47Smatthias.ringwald             }
21591e6aba47Smatthias.ringwald             break;
21601e6aba47Smatthias.ringwald 
2161fa8473a4Smatthias.ringwald         case L2CAP_STATE_CONFIG:
2162f8fbdce0SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2163ae280e73Smatthias.ringwald             switch (code) {
2164ae280e73Smatthias.ringwald                 case CONFIGURE_REQUEST:
216528ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
2166ae280e73Smatthias.ringwald                     l2cap_signaling_handle_configure_request(channel, command);
216763a7246aSmatthias.ringwald                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
216863a7246aSmatthias.ringwald                         // only done if continuation not set
216963a7246aSmatthias.ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
217063a7246aSmatthias.ringwald                     }
2171ae280e73Smatthias.ringwald                     break;
21721e6aba47Smatthias.ringwald                 case CONFIGURE_RESPONSE:
21735932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2174f2fa388dSMatthias Ringwald                     l2cap_signaling_handle_configure_response(channel, result, command);
21755932bd7cS[email protected]                     switch (result){
21765932bd7cS[email protected]                         case 0: // success
21775932bd7cS[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
21785932bd7cS[email protected]                             break;
21795932bd7cS[email protected]                         case 4: // pending
21805932bd7cS[email protected]                             l2cap_start_ertx(channel);
21815932bd7cS[email protected]                             break;
21825932bd7cS[email protected]                         default:
2183a32d6a03SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2184a32d6a03SMatthias Ringwald                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
2185a32d6a03SMatthias Ringwald                                 // remote does not offer ertm but it's required
2186a32d6a03SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2187a32d6a03SMatthias Ringwald                                 break;
2188a32d6a03SMatthias Ringwald                             }
2189a32d6a03SMatthias Ringwald #endif
2190fe9d8984S[email protected]                             // retry on negative result
2191fe9d8984S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2192fe9d8984S[email protected]                             break;
2193fe9d8984S[email protected]                     }
21945a67bd4aSmatthias.ringwald                     break;
21955a67bd4aSmatthias.ringwald                 default:
21965a67bd4aSmatthias.ringwald                     break;
21971e6aba47Smatthias.ringwald             }
2198fa8473a4Smatthias.ringwald             if (l2cap_channel_ready_for_open(channel)){
2199fa8473a4Smatthias.ringwald                 // for open:
22005a67bd4aSmatthias.ringwald                 channel->state = L2CAP_STATE_OPEN;
2201fa8473a4Smatthias.ringwald                 l2cap_emit_channel_opened(channel, 0);
2202c8e4258aSmatthias.ringwald             }
2203c8e4258aSmatthias.ringwald             break;
2204f62db1e3Smatthias.ringwald 
2205f62db1e3Smatthias.ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
2206f62db1e3Smatthias.ringwald             switch (code) {
2207f62db1e3Smatthias.ringwald                 case DISCONNECTION_RESPONSE:
220827a923d0Smatthias.ringwald                     l2cap_finialize_channel_close(channel);
220927a923d0Smatthias.ringwald                     break;
22105a67bd4aSmatthias.ringwald                 default:
22115a67bd4aSmatthias.ringwald                     //@TODO: implement other signaling packets
22125a67bd4aSmatthias.ringwald                     break;
221327a923d0Smatthias.ringwald             }
221427a923d0Smatthias.ringwald             break;
221584836b65Smatthias.ringwald 
221684836b65Smatthias.ringwald         case L2CAP_STATE_CLOSED:
221784836b65Smatthias.ringwald             // @TODO handle incoming requests
221884836b65Smatthias.ringwald             break;
221984836b65Smatthias.ringwald 
222084836b65Smatthias.ringwald         case L2CAP_STATE_OPEN:
222184836b65Smatthias.ringwald             //@TODO: implement other signaling packets, e.g. re-configure
222284836b65Smatthias.ringwald             break;
222310642e45Smatthias.ringwald         default:
222410642e45Smatthias.ringwald             break;
222527a923d0Smatthias.ringwald     }
22269da54300S[email protected]     // log_info("new state %u", channel->state);
222727a923d0Smatthias.ringwald }
222827a923d0Smatthias.ringwald 
222900d93d79Smatthias.ringwald 
22307f02f414SMatthias Ringwald static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
223100d93d79Smatthias.ringwald 
22321b9cb13dSMatthias Ringwald     btstack_linked_list_iterator_t it;
22331b9cb13dSMatthias Ringwald 
223400d93d79Smatthias.ringwald     // get code, signalind identifier and command len
223500d93d79Smatthias.ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
223600d93d79Smatthias.ringwald     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
223700d93d79Smatthias.ringwald 
22381b9cb13dSMatthias Ringwald     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
22391b9cb13dSMatthias Ringwald     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_RESPONSE){
2240e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
224100d93d79Smatthias.ringwald         return;
224200d93d79Smatthias.ringwald     }
224300d93d79Smatthias.ringwald 
224400d93d79Smatthias.ringwald     // general commands without an assigned channel
224500d93d79Smatthias.ringwald     switch(code) {
224600d93d79Smatthias.ringwald 
224700d93d79Smatthias.ringwald         case CONNECTION_REQUEST: {
2248f8fbdce0SMatthias Ringwald             uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2249f8fbdce0SMatthias Ringwald             uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
225000d93d79Smatthias.ringwald             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
22512b83fb7dSmatthias.ringwald             return;
225200d93d79Smatthias.ringwald         }
225300d93d79Smatthias.ringwald 
22542b360848Smatthias.ringwald         case ECHO_REQUEST:
2255e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
22562b83fb7dSmatthias.ringwald             return;
225700d93d79Smatthias.ringwald 
225800d93d79Smatthias.ringwald         case INFORMATION_REQUEST: {
2259f8fbdce0SMatthias Ringwald             uint16_t infoType = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2260e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, infoType);
22612b83fb7dSmatthias.ringwald             return;
226200d93d79Smatthias.ringwald         }
226300d93d79Smatthias.ringwald 
22641b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
22651b9cb13dSMatthias Ringwald         case INFORMATION_RESPONSE: {
22661b9cb13dSMatthias Ringwald             hci_connection_t * connection = hci_connection_for_handle(handle);
22671b9cb13dSMatthias Ringwald             if (!connection) return;
22681b9cb13dSMatthias Ringwald             uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
22691b9cb13dSMatthias Ringwald             uint16_t result =  little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
22701b9cb13dSMatthias Ringwald             if (result != 0) return;
2271543b84e4SMatthias Ringwald             if (info_type != 0x02) return;
22721b9cb13dSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
22731b9cb13dSMatthias Ringwald             connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2274543b84e4SMatthias Ringwald             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
22751b9cb13dSMatthias Ringwald             // trigger connection request
22761b9cb13dSMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
22771b9cb13dSMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
22781b9cb13dSMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2279543b84e4SMatthias Ringwald                 if (channel->con_handle != handle) continue;
2280543b84e4SMatthias Ringwald                 // bail if ERTM was requested but is not supported
2281543b84e4SMatthias Ringwald                 if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2282f073f086SMatthias Ringwald                     if (channel->ertm_mandatory){
2283543b84e4SMatthias Ringwald                         // channel closed
2284543b84e4SMatthias Ringwald                         channel->state = L2CAP_STATE_CLOSED;
2285543b84e4SMatthias Ringwald                         // map l2cap connection response result to BTstack status enumeration
2286543b84e4SMatthias Ringwald                         l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTD);
2287543b84e4SMatthias Ringwald                         // discard channel
2288543b84e4SMatthias Ringwald                         btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2289543b84e4SMatthias Ringwald                         btstack_memory_l2cap_channel_free(channel);
2290543b84e4SMatthias Ringwald                         continue;
2291f073f086SMatthias Ringwald                     } else {
2292f073f086SMatthias Ringwald                         // fallback to Basic mode
2293f073f086SMatthias Ringwald                         channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2294f073f086SMatthias Ringwald                     }
2295543b84e4SMatthias Ringwald                 }
2296543b84e4SMatthias Ringwald                 // start connecting
22971b9cb13dSMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
22981b9cb13dSMatthias Ringwald                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
22991b9cb13dSMatthias Ringwald                 }
230052606043SMatthias Ringwald                 // respond to connection request
230152606043SMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
230252606043SMatthias Ringwald                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
230352606043SMatthias Ringwald                     l2cap_emit_incoming_connection(channel);
230452606043SMatthias Ringwald                 }
23051b9cb13dSMatthias Ringwald             }
23061b9cb13dSMatthias Ringwald             return;
23071b9cb13dSMatthias Ringwald         }
23081b9cb13dSMatthias Ringwald #endif
23091b9cb13dSMatthias Ringwald 
231000d93d79Smatthias.ringwald         default:
231100d93d79Smatthias.ringwald             break;
231200d93d79Smatthias.ringwald     }
231300d93d79Smatthias.ringwald 
231400d93d79Smatthias.ringwald 
231500d93d79Smatthias.ringwald     // Get potential destination CID
2316f8fbdce0SMatthias Ringwald     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
231700d93d79Smatthias.ringwald 
231800d93d79Smatthias.ringwald     // Find channel for this sig_id and connection handle
2319665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2320665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2321665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2322fc64f94aSMatthias Ringwald         if (channel->con_handle != handle) continue;
232300d93d79Smatthias.ringwald         if (code & 1) {
2324b1988dceSmatthias.ringwald             // match odd commands (responses) by previous signaling identifier
2325b1988dceSmatthias.ringwald             if (channel->local_sig_id == sig_id) {
232600d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
23274e32727eSmatthias.ringwald                 break;
232800d93d79Smatthias.ringwald             }
232900d93d79Smatthias.ringwald         } else {
2330b1988dceSmatthias.ringwald             // match even commands (requests) by local channel id
233100d93d79Smatthias.ringwald             if (channel->local_cid == dest_cid) {
233200d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
23334e32727eSmatthias.ringwald                 break;
233400d93d79Smatthias.ringwald             }
233500d93d79Smatthias.ringwald         }
233600d93d79Smatthias.ringwald     }
233700d93d79Smatthias.ringwald }
233809e9d05bSMatthias Ringwald #endif
233900d93d79Smatthias.ringwald 
2340e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
234109e9d05bSMatthias Ringwald 
234209e9d05bSMatthias Ringwald static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
234309e9d05bSMatthias Ringwald     uint8_t event[6];
234409e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
234509e9d05bSMatthias Ringwald     event[1] = 4;
234609e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
234709e9d05bSMatthias Ringwald     little_endian_store_16(event, 4, result);
234809e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
234909e9d05bSMatthias Ringwald     if (!l2cap_event_packet_handler) return;
235009e9d05bSMatthias Ringwald     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
235109e9d05bSMatthias Ringwald }
235209e9d05bSMatthias Ringwald 
2353c48b2a2cSMatthias Ringwald // @returns valid
2354c48b2a2cSMatthias Ringwald static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
2355e7d0c9aaSMatthias Ringwald     hci_connection_t * connection;
2356c48b2a2cSMatthias Ringwald     uint16_t result;
2357c48b2a2cSMatthias Ringwald     uint8_t  event[10];
235883fd9c76SMatthias Ringwald 
2359cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2360a3dc965aSMatthias Ringwald     btstack_linked_list_iterator_t it;
2361a3dc965aSMatthias Ringwald     l2cap_channel_t * channel;
2362a3dc965aSMatthias Ringwald     uint16_t local_cid;
236383fd9c76SMatthias Ringwald     uint16_t le_psm;
236463f0ac45SMatthias Ringwald     uint16_t new_credits;
236563f0ac45SMatthias Ringwald     uint16_t credits_before;
2366e7d0c9aaSMatthias Ringwald     l2cap_service_t * service;
236711cae19eSMilanka Ringwald     uint16_t source_cid;
236883fd9c76SMatthias Ringwald #endif
236900d93d79Smatthias.ringwald 
23701b8b8d05SMatthias Ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
237123017473SMatthias Ringwald     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u", code, sig_id);
23721b8b8d05SMatthias Ringwald 
23731b8b8d05SMatthias Ringwald     switch (code){
237400d93d79Smatthias.ringwald 
2375c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
2376c48b2a2cSMatthias Ringwald             result = little_endian_read_16(command, 4);
2377ccf076adS[email protected]             l2cap_emit_connection_parameter_update_response(handle, result);
2378ccf076adS[email protected]             break;
2379da886c03S[email protected] 
2380c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_REQUEST:
2381e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
2382da886c03S[email protected]             if (connection){
23836d91fb6cSMatthias Ringwald                 if (connection->role != HCI_ROLE_MASTER){
23846d91fb6cSMatthias Ringwald                     // reject command without notifying upper layer when not in master role
2385c48b2a2cSMatthias Ringwald                     return 0;
23866d91fb6cSMatthias Ringwald                 }
2387da886c03S[email protected]                 int update_parameter = 1;
2388a4c06b28SMatthias Ringwald                 le_connection_parameter_range_t existing_range;
23894ced4e8cSMatthias Ringwald                 gap_get_connection_parameter_range(&existing_range);
2390c48b2a2cSMatthias Ringwald                 uint16_t le_conn_interval_min = little_endian_read_16(command,8);
2391c48b2a2cSMatthias Ringwald                 uint16_t le_conn_interval_max = little_endian_read_16(command,10);
2392c48b2a2cSMatthias Ringwald                 uint16_t le_conn_latency = little_endian_read_16(command,12);
2393c48b2a2cSMatthias Ringwald                 uint16_t le_supervision_timeout = little_endian_read_16(command,14);
2394da886c03S[email protected] 
2395da886c03S[email protected]                 if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
2396da886c03S[email protected]                 if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
2397da886c03S[email protected] 
2398da886c03S[email protected]                 if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
2399da886c03S[email protected]                 if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
2400da886c03S[email protected] 
2401da886c03S[email protected]                 if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
2402da886c03S[email protected]                 if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
2403da886c03S[email protected] 
2404da886c03S[email protected]                 if (update_parameter){
2405da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
2406da886c03S[email protected]                     connection->le_conn_interval_min = le_conn_interval_min;
2407da886c03S[email protected]                     connection->le_conn_interval_max = le_conn_interval_max;
2408da886c03S[email protected]                     connection->le_conn_latency = le_conn_latency;
2409da886c03S[email protected]                     connection->le_supervision_timeout = le_supervision_timeout;
2410da886c03S[email protected]                 } else {
2411da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
2412da886c03S[email protected]                 }
2413c48b2a2cSMatthias Ringwald                 connection->le_con_param_update_identifier = sig_id;
2414da886c03S[email protected]             }
2415da886c03S[email protected] 
241633c40538SMatthias Ringwald             if (!l2cap_event_packet_handler) break;
2417c48b2a2cSMatthias Ringwald 
2418c48b2a2cSMatthias Ringwald             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
2419c48b2a2cSMatthias Ringwald             event[1] = 8;
2420c48b2a2cSMatthias Ringwald             memcpy(&event[2], &command[4], 8);
2421c48b2a2cSMatthias Ringwald             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
242233c40538SMatthias Ringwald             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
2423ccf076adS[email protected]             break;
2424c48b2a2cSMatthias Ringwald 
2425a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2426a3dc965aSMatthias Ringwald 
242763f0ac45SMatthias Ringwald         case COMMAND_REJECT:
242863f0ac45SMatthias Ringwald             // Find channel for this sig_id and connection handle
242963f0ac45SMatthias Ringwald             channel = NULL;
243063f0ac45SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
243163f0ac45SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
243263f0ac45SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
243363f0ac45SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
243463f0ac45SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
243563f0ac45SMatthias Ringwald                 channel = a_channel;
243663f0ac45SMatthias Ringwald                 break;
243763f0ac45SMatthias Ringwald             }
243863f0ac45SMatthias Ringwald             if (!channel) break;
243963f0ac45SMatthias Ringwald 
244063f0ac45SMatthias Ringwald             // if received while waiting for le connection response, assume legacy device
244163f0ac45SMatthias Ringwald             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
244263f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
244363f0ac45SMatthias Ringwald                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
244444276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0x0002);
244563f0ac45SMatthias Ringwald 
244663f0ac45SMatthias Ringwald                 // discard channel
244763f0ac45SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
244863f0ac45SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
244963f0ac45SMatthias Ringwald                 break;
245063f0ac45SMatthias Ringwald             }
245163f0ac45SMatthias Ringwald             break;
245263f0ac45SMatthias Ringwald 
2453e7d0c9aaSMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_REQUEST:
2454e7d0c9aaSMatthias Ringwald 
2455e7d0c9aaSMatthias Ringwald             // get hci connection, bail if not found (must not happen)
2456e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
2457e7d0c9aaSMatthias Ringwald             if (!connection) return 0;
2458e7d0c9aaSMatthias Ringwald 
2459e7d0c9aaSMatthias Ringwald             // check if service registered
2460e7d0c9aaSMatthias Ringwald             le_psm  = little_endian_read_16(command, 4);
2461e7d0c9aaSMatthias Ringwald             service = l2cap_le_get_service(le_psm);
246211cae19eSMilanka Ringwald             source_cid = little_endian_read_16(command, 6);
2463e7d0c9aaSMatthias Ringwald 
2464e7d0c9aaSMatthias Ringwald             if (service){
2465e7d0c9aaSMatthias Ringwald                 if (source_cid < 0x40){
2466e7d0c9aaSMatthias Ringwald                     // 0x0009 Connection refused - Invalid Source CID
2467e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
2468e7d0c9aaSMatthias Ringwald                     return 1;
2469e7d0c9aaSMatthias Ringwald                 }
2470e7d0c9aaSMatthias Ringwald 
2471e7d0c9aaSMatthias Ringwald                 // go through list of channels for this ACL connection and check if we get a match
2472e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2473e7d0c9aaSMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&it)){
24741b8b8d05SMatthias Ringwald                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
24751b8b8d05SMatthias Ringwald                     if (a_channel->con_handle != handle) continue;
24761b8b8d05SMatthias Ringwald                     if (a_channel->remote_cid != source_cid) continue;
2477e7d0c9aaSMatthias Ringwald                     // 0x000a Connection refused - Source CID already allocated
2478e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
2479e7d0c9aaSMatthias Ringwald                     return 1;
2480e7d0c9aaSMatthias Ringwald                 }
2481e7d0c9aaSMatthias Ringwald 
248283fd9c76SMatthias Ringwald                 // security: check encryption
248383fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_2){
248483fd9c76SMatthias Ringwald                     if (sm_encryption_key_size(handle) == 0){
248583fd9c76SMatthias Ringwald                         // 0x0008 Connection refused - insufficient encryption
2486e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
248783fd9c76SMatthias Ringwald                         return 1;
248883fd9c76SMatthias Ringwald                     }
248983fd9c76SMatthias Ringwald                     // anything less than 16 byte key size is insufficient
249083fd9c76SMatthias Ringwald                     if (sm_encryption_key_size(handle) < 16){
249183fd9c76SMatthias Ringwald                         // 0x0007 Connection refused – insufficient encryption key size
2492e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
249383fd9c76SMatthias Ringwald                         return 1;
249483fd9c76SMatthias Ringwald                     }
249583fd9c76SMatthias Ringwald                 }
249683fd9c76SMatthias Ringwald 
249783fd9c76SMatthias Ringwald                 // security: check authencation
249883fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_3){
249983fd9c76SMatthias Ringwald                     if (!sm_authenticated(handle)){
250083fd9c76SMatthias Ringwald                         // 0x0005 Connection refused – insufficient authentication
2501e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
250283fd9c76SMatthias Ringwald                         return 1;
250383fd9c76SMatthias Ringwald                     }
250483fd9c76SMatthias Ringwald                 }
250583fd9c76SMatthias Ringwald 
250683fd9c76SMatthias Ringwald                 // security: check authorization
250783fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_4){
250883fd9c76SMatthias Ringwald                     if (sm_authorization_state(handle) != AUTHORIZATION_GRANTED){
250983fd9c76SMatthias Ringwald                         // 0x0006 Connection refused – insufficient authorization
2510e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
251183fd9c76SMatthias Ringwald                         return 1;
251283fd9c76SMatthias Ringwald                     }
251383fd9c76SMatthias Ringwald                 }
2514e7d0c9aaSMatthias Ringwald 
2515e7d0c9aaSMatthias Ringwald                 // allocate channel
25161b8b8d05SMatthias Ringwald                 channel = l2cap_create_channel_entry(service->packet_handler, connection->address,
2517e7d0c9aaSMatthias Ringwald                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
2518e7d0c9aaSMatthias Ringwald                 if (!channel){
2519e7d0c9aaSMatthias Ringwald                     // 0x0004 Connection refused – no resources available
2520e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2521e7d0c9aaSMatthias Ringwald                     return 1;
2522e7d0c9aaSMatthias Ringwald                 }
2523e7d0c9aaSMatthias Ringwald 
2524e7d0c9aaSMatthias Ringwald                 channel->con_handle = handle;
2525e7d0c9aaSMatthias Ringwald                 channel->remote_cid = source_cid;
2526e7d0c9aaSMatthias Ringwald                 channel->remote_sig_id = sig_id;
25277f107edaSMatthias Ringwald                 channel->remote_mtu = little_endian_read_16(command, 8);
25287f107edaSMatthias Ringwald                 channel->remote_mps = little_endian_read_16(command, 10);
25297f107edaSMatthias Ringwald                 channel->credits_outgoing = little_endian_read_16(command, 12);
2530e7d0c9aaSMatthias Ringwald 
2531e7d0c9aaSMatthias Ringwald                 // set initial state
2532e7d0c9aaSMatthias Ringwald                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2533c99bb618SMatthias Ringwald                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
2534e7d0c9aaSMatthias Ringwald 
2535e7d0c9aaSMatthias Ringwald                 // add to connections list
2536e7d0c9aaSMatthias Ringwald                 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2537e7d0c9aaSMatthias Ringwald 
2538e7d0c9aaSMatthias Ringwald                 // post connection request event
253944276248SMatthias Ringwald                 l2cap_emit_le_incoming_connection(channel);
2540e7d0c9aaSMatthias Ringwald 
2541e7d0c9aaSMatthias Ringwald             } else {
2542e7d0c9aaSMatthias Ringwald                 // Connection refused – LE_PSM not supported
2543e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2544e7d0c9aaSMatthias Ringwald             }
2545e7d0c9aaSMatthias Ringwald             break;
25461b8b8d05SMatthias Ringwald 
25471b8b8d05SMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
25481b8b8d05SMatthias Ringwald             // Find channel for this sig_id and connection handle
25491b8b8d05SMatthias Ringwald             channel = NULL;
25501b8b8d05SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
25511b8b8d05SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
25521b8b8d05SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
25531b8b8d05SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
25541b8b8d05SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
25551b8b8d05SMatthias Ringwald                 channel = a_channel;
25561b8b8d05SMatthias Ringwald                 break;
25571b8b8d05SMatthias Ringwald             }
25581b8b8d05SMatthias Ringwald             if (!channel) break;
25591b8b8d05SMatthias Ringwald 
25601b8b8d05SMatthias Ringwald             // cid + 0
25611b8b8d05SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
25621b8b8d05SMatthias Ringwald             if (result){
25631b8b8d05SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
25641b8b8d05SMatthias Ringwald                 // map l2cap connection response result to BTstack status enumeration
256544276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, result);
25661b8b8d05SMatthias Ringwald 
25671b8b8d05SMatthias Ringwald                 // discard channel
256863f0ac45SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
25691b8b8d05SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
25701b8b8d05SMatthias Ringwald                 break;
25711b8b8d05SMatthias Ringwald             }
25721b8b8d05SMatthias Ringwald 
25731b8b8d05SMatthias Ringwald             // success
25741b8b8d05SMatthias Ringwald             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
25751b8b8d05SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
25761b8b8d05SMatthias Ringwald             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
25771b8b8d05SMatthias Ringwald             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
25781b8b8d05SMatthias Ringwald             channel->state = L2CAP_STATE_OPEN;
257944276248SMatthias Ringwald             l2cap_emit_le_channel_opened(channel, result);
25801b8b8d05SMatthias Ringwald             break;
25811b8b8d05SMatthias Ringwald 
258285aeef60SMatthias Ringwald         case LE_FLOW_CONTROL_CREDIT:
258385aeef60SMatthias Ringwald             // find channel
258485aeef60SMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
258585aeef60SMatthias Ringwald             channel = l2cap_le_get_channel_for_local_cid(local_cid);
258663f0ac45SMatthias Ringwald             if (!channel) {
258763f0ac45SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
258863f0ac45SMatthias Ringwald                 break;
258963f0ac45SMatthias Ringwald             }
259063f0ac45SMatthias Ringwald             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
259163f0ac45SMatthias Ringwald             credits_before = channel->credits_outgoing;
259263f0ac45SMatthias Ringwald             channel->credits_outgoing += new_credits;
259363f0ac45SMatthias Ringwald             // check for credit overrun
259463f0ac45SMatthias Ringwald             if (credits_before > channel->credits_outgoing){
259563f0ac45SMatthias Ringwald                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
259663f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
259763f0ac45SMatthias Ringwald                 break;
259863f0ac45SMatthias Ringwald             }
259963f0ac45SMatthias Ringwald             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
260085aeef60SMatthias Ringwald             break;
260185aeef60SMatthias Ringwald 
2602828a7f7aSMatthias Ringwald         case DISCONNECTION_REQUEST:
2603828a7f7aSMatthias Ringwald             // find channel
2604828a7f7aSMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
2605828a7f7aSMatthias Ringwald             channel = l2cap_le_get_channel_for_local_cid(local_cid);
260663f34e00SMatthias Ringwald             if (!channel) {
260763f34e00SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
260863f34e00SMatthias Ringwald                 break;
260963f34e00SMatthias Ringwald             }
2610828a7f7aSMatthias Ringwald             channel->remote_sig_id = sig_id;
2611828a7f7aSMatthias Ringwald             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
2612828a7f7aSMatthias Ringwald             break;
2613828a7f7aSMatthias Ringwald 
2614a3dc965aSMatthias Ringwald #endif
2615a3dc965aSMatthias Ringwald 
261663f0ac45SMatthias Ringwald         case DISCONNECTION_RESPONSE:
261763f0ac45SMatthias Ringwald             break;
261863f0ac45SMatthias Ringwald 
2619c48b2a2cSMatthias Ringwald         default:
2620c48b2a2cSMatthias Ringwald             // command unknown -> reject command
2621c48b2a2cSMatthias Ringwald             return 0;
2622ccf076adS[email protected]     }
2623c48b2a2cSMatthias Ringwald     return 1;
2624c48b2a2cSMatthias Ringwald }
2625e7d0c9aaSMatthias Ringwald #endif
2626c48b2a2cSMatthias Ringwald 
2627d48432d4SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
262870734707SMatthias Ringwald 
262970734707SMatthias Ringwald // @param delta number of frames in the future, >= 1
263070734707SMatthias Ringwald static void l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel_t * l2cap_channel, l2cap_segmentation_and_reassembly_t sar, int delta, uint8_t * payload, uint16_t size){
263170734707SMatthias Ringwald     log_info("Store SDU with delta %u", delta);
263270734707SMatthias Ringwald     // get rx state for packet to store
263370734707SMatthias Ringwald     int index = l2cap_channel->rx_store_index + delta - 1;
263470734707SMatthias Ringwald     if (index > l2cap_channel->num_rx_buffers){
263570734707SMatthias Ringwald         index -= l2cap_channel->num_rx_buffers;
263670734707SMatthias Ringwald     }
263770734707SMatthias Ringwald     log_info("Index of packet to store %u", index);
263870734707SMatthias Ringwald     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
263970734707SMatthias Ringwald     // check if buffer is free
264070734707SMatthias Ringwald     if (rx_state->valid){
264170734707SMatthias Ringwald         log_error("Packet buffer already used");
264270734707SMatthias Ringwald         return;
264370734707SMatthias Ringwald     }
264470734707SMatthias Ringwald     rx_state->valid = 1;
264570734707SMatthias Ringwald     rx_state->sar = sar;
264670734707SMatthias Ringwald     rx_state->len = size;
264770734707SMatthias Ringwald     uint8_t * rx_buffer = &l2cap_channel->rx_packets_data[index];
264870734707SMatthias Ringwald     memcpy(rx_buffer, payload, size);
264970734707SMatthias Ringwald }
265070734707SMatthias Ringwald 
2651e32be409SMatthias 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){
2652d48432d4SMatthias Ringwald     switch (sar){
2653d48432d4SMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
2654e32be409SMatthias Ringwald             // packet complete -> disapatch
2655e32be409SMatthias Ringwald             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, payload, size);
2656d48432d4SMatthias Ringwald             break;
2657d48432d4SMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
2658d48432d4SMatthias Ringwald             // TODO: check if reassembly started
2659e8e9809fSMatthias Ringwald             // TODO: check sdu_len against local mtu
2660e32be409SMatthias Ringwald             l2cap_channel->reassembly_sdu_length = little_endian_read_16(payload, 0);
2661e32be409SMatthias Ringwald             payload += 2;
2662e32be409SMatthias Ringwald             size    -= 2;
2663e32be409SMatthias Ringwald             memcpy(&l2cap_channel->reassembly_buffer[0], payload, size);
2664e32be409SMatthias Ringwald             l2cap_channel->reassembly_pos = size;
2665d48432d4SMatthias Ringwald             break;
2666d48432d4SMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
2667e32be409SMatthias Ringwald             memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos], payload, size);
2668e32be409SMatthias Ringwald             l2cap_channel->reassembly_pos += size;
2669e32be409SMatthias Ringwald             break;
2670e32be409SMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
2671e32be409SMatthias Ringwald             memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos], payload, size);
2672e32be409SMatthias Ringwald             l2cap_channel->reassembly_pos += size;
2673e32be409SMatthias Ringwald             // packet complete -> disapatch
2674e32be409SMatthias Ringwald             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->reassembly_buffer, l2cap_channel->reassembly_pos);
2675e32be409SMatthias Ringwald             l2cap_channel->reassembly_pos = 0;
2676d48432d4SMatthias Ringwald             break;
2677d48432d4SMatthias Ringwald     }
2678d48432d4SMatthias Ringwald }
2679d48432d4SMatthias Ringwald #endif
2680d48432d4SMatthias Ringwald 
2681c48b2a2cSMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size ){
26829ec2630cSMatthias Ringwald     UNUSED(packet_type);
26839ec2630cSMatthias Ringwald     UNUSED(channel);
2684c48b2a2cSMatthias Ringwald 
268509e9d05bSMatthias Ringwald     l2cap_channel_t * l2cap_channel;
2686f3963406SMatthias Ringwald     UNUSED(l2cap_channel);
268709e9d05bSMatthias Ringwald 
2688c48b2a2cSMatthias Ringwald     // Get Channel ID
2689c48b2a2cSMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
2690c48b2a2cSMatthias Ringwald     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
2691c48b2a2cSMatthias Ringwald 
2692c48b2a2cSMatthias Ringwald     switch (channel_id) {
2693c48b2a2cSMatthias Ringwald 
269409e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2695c48b2a2cSMatthias Ringwald         case L2CAP_CID_SIGNALING: {
2696c48b2a2cSMatthias Ringwald             uint16_t command_offset = 8;
2697c48b2a2cSMatthias Ringwald             while (command_offset < size) {
2698c48b2a2cSMatthias Ringwald                 // handle signaling commands
2699c48b2a2cSMatthias Ringwald                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
2700c48b2a2cSMatthias Ringwald 
2701c48b2a2cSMatthias Ringwald                 // increment command_offset
2702c48b2a2cSMatthias Ringwald                 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2703c48b2a2cSMatthias Ringwald             }
2704c48b2a2cSMatthias Ringwald             break;
2705c48b2a2cSMatthias Ringwald         }
270609e9d05bSMatthias Ringwald #endif
2707c48b2a2cSMatthias Ringwald 
2708e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
2709e7d0c9aaSMatthias Ringwald         case L2CAP_CID_SIGNALING_LE: {
2710e7d0c9aaSMatthias Ringwald             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
2711e7d0c9aaSMatthias Ringwald             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
2712c48b2a2cSMatthias Ringwald             if (!valid){
2713e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2714ccf076adS[email protected]             }
2715ccf076adS[email protected]             break;
2716e7d0c9aaSMatthias Ringwald         }
2717e7d0c9aaSMatthias Ringwald #endif
2718c48b2a2cSMatthias Ringwald 
2719c48b2a2cSMatthias Ringwald         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
2720c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback) {
2721c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2722ccf076adS[email protected]             }
2723c48b2a2cSMatthias Ringwald             break;
2724c48b2a2cSMatthias Ringwald 
2725c48b2a2cSMatthias Ringwald         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
2726c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback) {
2727c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2728c48b2a2cSMatthias Ringwald             }
2729c48b2a2cSMatthias Ringwald             break;
2730c48b2a2cSMatthias Ringwald 
2731c48b2a2cSMatthias Ringwald         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
2732c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback) {
2733c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2734c48b2a2cSMatthias Ringwald             }
2735c48b2a2cSMatthias Ringwald             break;
27361bbc0b23S[email protected] 
273709e9d05bSMatthias Ringwald         default:
273809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
273900d93d79Smatthias.ringwald             // Find channel for this channel_id and connection handle
274064e11ca9SMatthias Ringwald             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
2741d1fd2a88SMatthias Ringwald             if (l2cap_channel) {
274227e0774aSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
274327e0774aSMatthias Ringwald                 if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
274427e0774aSMatthias Ringwald 
274527e0774aSMatthias Ringwald                     // verify FCS
274627e0774aSMatthias Ringwald                     uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
274727e0774aSMatthias Ringwald                     uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
274827e0774aSMatthias Ringwald                     log_info("Packet FCS 0x%04x, calculated FCS 0x%04x", fcs_packet, fcs_calculated);
274927e0774aSMatthias Ringwald                     if (fcs_calculated != fcs_packet){
275027e0774aSMatthias Ringwald                         log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
275127e0774aSMatthias Ringwald                         // TODO: trigger retransmission or something like that
275227e0774aSMatthias Ringwald                         break;
275327e0774aSMatthias Ringwald                     }
275427e0774aSMatthias Ringwald 
275527e0774aSMatthias Ringwald                     // switch on packet type
275627e0774aSMatthias Ringwald                     uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
275738f62777SMatthias Ringwald                     uint8_t  req_seq = (control >> 8) & 0x3f;
27582bea1b8dSMatthias Ringwald                     int final = (control >> 7) & 0x01;
275927e0774aSMatthias Ringwald                     if (control & 1){
276027e0774aSMatthias Ringwald                         // S-Frame
276178cd8a22SMatthias Ringwald                         int poll  = (control >> 4) & 0x01;
2762bdbe2e49SMatthias Ringwald                         l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
27639ffcbce4SMatthias Ringwald                         log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
27647b7901d8SMatthias Ringwald                         l2cap_ertm_tx_packet_state_t * tx_state;
2765bdbe2e49SMatthias Ringwald                         switch (s){
2766bdbe2e49SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
27679ffcbce4SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
27682a424812SMatthias Ringwald                                 l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
27693233d8abSMatthias Ringwald                                 if (poll && final){
27703233d8abSMatthias Ringwald                                     // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
27713233d8abSMatthias Ringwald                                     log_error("P=F=1 in S-Frame");
27723233d8abSMatthias Ringwald                                     break;
27733233d8abSMatthias Ringwald                                 }
277478cd8a22SMatthias Ringwald                                 if (poll){
2775*f85ade6bSMatthias Ringwald                                     // check if we did request selective retransmission before <==> we have stored SDU segments
2776*f85ade6bSMatthias Ringwald                                     int i;
2777*f85ade6bSMatthias Ringwald                                     int num_stored_out_of_order_packets = 0;
2778*f85ade6bSMatthias Ringwald                                     for (i=0;i<l2cap_channel->num_rx_buffers;i++){
2779*f85ade6bSMatthias Ringwald                                         int index = l2cap_channel->rx_store_index + i;
2780*f85ade6bSMatthias Ringwald                                         if (index >= l2cap_channel->num_rx_buffers){
2781*f85ade6bSMatthias Ringwald                                             index -= l2cap_channel->num_rx_buffers;
2782*f85ade6bSMatthias Ringwald                                         }
2783*f85ade6bSMatthias Ringwald                                         l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
2784*f85ade6bSMatthias Ringwald                                         if (!rx_state->valid) continue;
2785*f85ade6bSMatthias Ringwald                                         num_stored_out_of_order_packets++;
2786*f85ade6bSMatthias Ringwald                                     }
2787*f85ade6bSMatthias Ringwald                                     if (num_stored_out_of_order_packets){
2788*f85ade6bSMatthias Ringwald                                         l2cap_channel->send_supervisor_frame_selective_reject = 1;
2789*f85ade6bSMatthias Ringwald                                     } else {
2790d2afdd38SMatthias Ringwald                                         l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
279178cd8a22SMatthias Ringwald                                     }
2792*f85ade6bSMatthias Ringwald                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
2793*f85ade6bSMatthias Ringwald                                 }
27943233d8abSMatthias Ringwald                                 if (final){
27953233d8abSMatthias Ringwald                                     // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
27963233d8abSMatthias Ringwald                                     l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
27973233d8abSMatthias Ringwald                                 }
2798bdbe2e49SMatthias Ringwald                                 break;
27999ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
28009ffcbce4SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
28019ffcbce4SMatthias Ringwald                                 l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
28029ffcbce4SMatthias Ringwald                                 // rsetart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_handle_req_seq)
28039ffcbce4SMatthias Ringwald                                 l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
28049ffcbce4SMatthias Ringwald                                 break;
28059ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
28069ffcbce4SMatthias Ringwald                                 log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
28079ffcbce4SMatthias Ringwald                                 break;
28089ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
28097b7901d8SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
28107b7901d8SMatthias Ringwald                                 if (poll){
28117b7901d8SMatthias Ringwald                                     l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
28127b7901d8SMatthias Ringwald                                 }
28137b7901d8SMatthias Ringwald                                 // find requested i-frame
28147b7901d8SMatthias Ringwald                                 tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
28157b7901d8SMatthias Ringwald                                 if (tx_state){
28167b7901d8SMatthias Ringwald                                     log_info("Retransmission for tx_seq %u requested", req_seq);
2817d2afdd38SMatthias Ringwald                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
28187b7901d8SMatthias Ringwald                                     tx_state->retransmission_requested = 1;
28197b7901d8SMatthias Ringwald                                     l2cap_channel->srej_active = 1;
28207b7901d8SMatthias Ringwald                                 }
28219ffcbce4SMatthias Ringwald                                 break;
2822bdbe2e49SMatthias Ringwald                             default:
2823bdbe2e49SMatthias Ringwald                                 break;
2824bdbe2e49SMatthias Ringwald                         }
282527e0774aSMatthias Ringwald                         break;
282627e0774aSMatthias Ringwald                     } else {
282727e0774aSMatthias Ringwald                         // I-Frame
282827e0774aSMatthias Ringwald                         // get control
282927e0774aSMatthias Ringwald                         l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
283038f62777SMatthias Ringwald                         uint8_t tx_seq = (control >> 1) & 0x3f;
283138f62777SMatthias Ringwald                         log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
2832e8e9809fSMatthias Ringwald                         log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
283338f62777SMatthias Ringwald                         log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
28342a424812SMatthias Ringwald                         l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
283511b576c5SMatthias Ringwald                         if (final){
283611b576c5SMatthias Ringwald                             // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
283711b576c5SMatthias Ringwald                             l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
283811b576c5SMatthias Ringwald                         }
283938f62777SMatthias Ringwald                         // check ordering
284038f62777SMatthias Ringwald                         if (l2cap_channel->expected_tx_seq == tx_seq){
284138f62777SMatthias Ringwald                             log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
284238f62777SMatthias Ringwald                             l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
2843*f85ade6bSMatthias Ringwald                             l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
2844d48432d4SMatthias Ringwald 
2845e32be409SMatthias Ringwald                             // process SDU
2846e32be409SMatthias Ringwald                             l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, &packet[COMPLETE_L2CAP_HEADER+2], size-(COMPLETE_L2CAP_HEADER+2));
2847d48432d4SMatthias Ringwald 
284870734707SMatthias Ringwald                             // process stored segments
284970734707SMatthias Ringwald                             while (1){
285070734707SMatthias Ringwald                                 int index = l2cap_channel->rx_store_index;
285170734707SMatthias Ringwald                                 l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
285270734707SMatthias Ringwald                                 if (!rx_state->valid) break;
2853*f85ade6bSMatthias Ringwald 
2854*f85ade6bSMatthias Ringwald                                 log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
2855*f85ade6bSMatthias Ringwald                                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
2856*f85ade6bSMatthias Ringwald                                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
2857*f85ade6bSMatthias Ringwald 
285870734707SMatthias Ringwald                                 rx_state->valid = 0;
285970734707SMatthias Ringwald                                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
2860*f85ade6bSMatthias Ringwald 
2861*f85ade6bSMatthias Ringwald                                 // update rx store index
286270734707SMatthias Ringwald                                 index++;
286370734707SMatthias Ringwald                                 if (index >= l2cap_channel->num_rx_buffers){
286470734707SMatthias Ringwald                                     index = 0;
286570734707SMatthias Ringwald                                 }
286670734707SMatthias Ringwald                                 l2cap_channel->rx_store_index = index;
286770734707SMatthias Ringwald                             }
286870734707SMatthias Ringwald 
2869*f85ade6bSMatthias Ringwald                             //
2870*f85ade6bSMatthias Ringwald                             l2cap_channel->send_supervisor_frame_receiver_ready = 1;
2871*f85ade6bSMatthias Ringwald 
2872c7309e8dSMatthias Ringwald                         } else {
2873df2191a7SMatthias Ringwald                             int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
2874df2191a7SMatthias Ringwald                             if (delta < 2){
287570734707SMatthias Ringwald                                 // store segment
287670734707SMatthias Ringwald                                 l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, &packet[COMPLETE_L2CAP_HEADER+2], size-(COMPLETE_L2CAP_HEADER+2));
287770734707SMatthias Ringwald 
2878df2191a7SMatthias Ringwald                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
2879df2191a7SMatthias Ringwald                                 l2cap_channel->send_supervisor_frame_selective_reject = 1;
2880df2191a7SMatthias Ringwald                             } else {
2881df2191a7SMatthias Ringwald                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
2882c7309e8dSMatthias Ringwald                                 l2cap_channel->send_supervisor_frame_reject = 1;
288327e0774aSMatthias Ringwald                             }
288438f62777SMatthias Ringwald                         }
2885df2191a7SMatthias Ringwald                     }
288627e0774aSMatthias Ringwald                     break;
288727e0774aSMatthias Ringwald                 }
288827e0774aSMatthias Ringwald #endif
28893d50b4baSMatthias Ringwald                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
289000d93d79Smatthias.ringwald             }
289109e9d05bSMatthias Ringwald #endif
2892a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
289364e11ca9SMatthias Ringwald             l2cap_channel = l2cap_le_get_channel_for_local_cid(channel_id);
289464e11ca9SMatthias Ringwald             if (l2cap_channel) {
289585aeef60SMatthias Ringwald                 // credit counting
289685aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming == 0){
289785aeef60SMatthias Ringwald                     log_error("LE Data Channel packet received but no incoming credits");
289885aeef60SMatthias Ringwald                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
289985aeef60SMatthias Ringwald                     break;
290085aeef60SMatthias Ringwald                 }
290185aeef60SMatthias Ringwald                 l2cap_channel->credits_incoming--;
290285aeef60SMatthias Ringwald 
290385aeef60SMatthias Ringwald                 // automatic credits
290485aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){
290585aeef60SMatthias Ringwald                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
290685aeef60SMatthias Ringwald                 }
290785aeef60SMatthias Ringwald 
2908cd529728SMatthias Ringwald                 // first fragment
2909cd529728SMatthias Ringwald                 uint16_t pos = 0;
2910cd529728SMatthias Ringwald                 if (!l2cap_channel->receive_sdu_len){
2911cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
2912cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_pos = 0;
2913cd529728SMatthias Ringwald                     pos  += 2;
2914cd529728SMatthias Ringwald                     size -= 2;
2915cd529728SMatthias Ringwald                 }
2916cd529728SMatthias Ringwald                 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], size-COMPLETE_L2CAP_HEADER);
2917cd529728SMatthias Ringwald                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
2918cd529728SMatthias Ringwald                 // done?
291963f0ac45SMatthias Ringwald                 log_info("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
2920cd529728SMatthias Ringwald                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
2921cd529728SMatthias Ringwald                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
2922cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = 0;
2923cd529728SMatthias Ringwald                 }
292463f0ac45SMatthias Ringwald             } else {
292563f0ac45SMatthias Ringwald                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
292664e11ca9SMatthias Ringwald             }
292764e11ca9SMatthias Ringwald #endif
29285652b5ffS[email protected]             break;
29295652b5ffS[email protected]     }
293000d93d79Smatthias.ringwald 
29311eb2563eS[email protected]     l2cap_run();
29322718e2e7Smatthias.ringwald }
293300d93d79Smatthias.ringwald 
293409e9d05bSMatthias Ringwald // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
293509e9d05bSMatthias Ringwald void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
293609e9d05bSMatthias Ringwald     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
293709e9d05bSMatthias Ringwald     if (index < 0) return;
293809e9d05bSMatthias Ringwald     fixed_channels[index].callback = the_packet_handler;
293909e9d05bSMatthias Ringwald }
294009e9d05bSMatthias Ringwald 
294109e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
294215ec09bbSmatthias.ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
294327a923d0Smatthias.ringwald void l2cap_finialize_channel_close(l2cap_channel_t * channel){
2944f62db1e3Smatthias.ringwald     channel->state = L2CAP_STATE_CLOSED;
2945f62db1e3Smatthias.ringwald     l2cap_emit_channel_closed(channel);
2946f62db1e3Smatthias.ringwald     // discard channel
29479dcb2fb2S[email protected]     l2cap_stop_rtx(channel);
2948665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2949d3a9df87Smatthias.ringwald     btstack_memory_l2cap_channel_free(channel);
2950c8e4258aSmatthias.ringwald }
29511e6aba47Smatthias.ringwald 
29528f2a52f4SMatthias Ringwald static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
2953665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
2954665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, services);
2955665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2956665d90f2SMatthias Ringwald         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
29579d9bbc01Smatthias.ringwald         if ( service->psm == psm){
29589d9bbc01Smatthias.ringwald             return service;
29599d9bbc01Smatthias.ringwald         };
29609d9bbc01Smatthias.ringwald     }
29619d9bbc01Smatthias.ringwald     return NULL;
29629d9bbc01Smatthias.ringwald }
29639d9bbc01Smatthias.ringwald 
29647192e786SMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
29657192e786SMatthias Ringwald     return l2cap_get_service_internal(&l2cap_services, psm);
29667192e786SMatthias Ringwald }
29677192e786SMatthias Ringwald 
2968e0abb8e7S[email protected] 
2969be2053a6SMatthias 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){
2970be2053a6SMatthias Ringwald 
2971be2053a6SMatthias Ringwald     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
2972e0abb8e7S[email protected] 
29734bb582b6Smatthias.ringwald     // check for alread registered psm
29749d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
2975277abc2cSmatthias.ringwald     if (service) {
2976be2053a6SMatthias Ringwald         log_error("l2cap_register_service: PSM %u already registered", psm);
2977be2053a6SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
2978277abc2cSmatthias.ringwald     }
29799d9bbc01Smatthias.ringwald 
29804bb582b6Smatthias.ringwald     // alloc structure
2981bb69aaaeS[email protected]     service = btstack_memory_l2cap_service_get();
2982277abc2cSmatthias.ringwald     if (!service) {
2983be2053a6SMatthias Ringwald         log_error("l2cap_register_service: no memory for l2cap_service_t");
2984be2053a6SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
2985277abc2cSmatthias.ringwald     }
29869d9bbc01Smatthias.ringwald 
29879d9bbc01Smatthias.ringwald     // fill in
29889d9bbc01Smatthias.ringwald     service->psm = psm;
29899d9bbc01Smatthias.ringwald     service->mtu = mtu;
299005ae8de3SMatthias Ringwald     service->packet_handler = service_packet_handler;
2991df3354fcS[email protected]     service->required_security_level = security_level;
29929d9bbc01Smatthias.ringwald 
29939d9bbc01Smatthias.ringwald     // add to services list
2994665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
2995c0e866bfSmatthias.ringwald 
2996c0e866bfSmatthias.ringwald     // enable page scan
299715a95bd5SMatthias Ringwald     gap_connectable_control(1);
29985842b6d9Smatthias.ringwald 
2999be2053a6SMatthias Ringwald     return 0;
30009d9bbc01Smatthias.ringwald }
30019d9bbc01Smatthias.ringwald 
30027e8856ebSMatthias Ringwald uint8_t l2cap_unregister_service(uint16_t psm){
3003e0abb8e7S[email protected] 
3004e0abb8e7S[email protected]     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
3005e0abb8e7S[email protected] 
30069d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
30077e8856ebSMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3008665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
3009d3a9df87Smatthias.ringwald     btstack_memory_l2cap_service_free(service);
3010c0e866bfSmatthias.ringwald 
3011c0e866bfSmatthias.ringwald     // disable page scan when no services registered
30127e8856ebSMatthias Ringwald     if (btstack_linked_list_empty(&l2cap_services)) {
301315a95bd5SMatthias Ringwald         gap_connectable_control(0);
30149d9bbc01Smatthias.ringwald     }
30157e8856ebSMatthias Ringwald     return 0;
30167e8856ebSMatthias Ringwald }
301709e9d05bSMatthias Ringwald #endif
30189d9bbc01Smatthias.ringwald 
30197192e786SMatthias Ringwald 
3020cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
302183fd9c76SMatthias Ringwald 
302257be49d6SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
302357be49d6SMatthias Ringwald     if (!channel->waiting_for_can_send_now) return;
302457be49d6SMatthias Ringwald     if (channel->send_sdu_buffer) return;
302557be49d6SMatthias Ringwald     channel->waiting_for_can_send_now = 0;
302657be49d6SMatthias Ringwald     log_info("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
302757be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
302857be49d6SMatthias Ringwald }
302957be49d6SMatthias Ringwald 
303057be49d6SMatthias Ringwald // 1BH2222
303157be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
303257be49d6SMatthias 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",
303357be49d6SMatthias Ringwald              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
303457be49d6SMatthias Ringwald     uint8_t event[19];
303557be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
303657be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
303757be49d6SMatthias Ringwald     event[2] = channel->address_type;
303857be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
303957be49d6SMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
304057be49d6SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
304157be49d6SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
304257be49d6SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
304357be49d6SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_mtu);
304457be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
304557be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
304657be49d6SMatthias Ringwald }
304757be49d6SMatthias Ringwald // 11BH22222
304857be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
304957be49d6SMatthias 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",
305057be49d6SMatthias Ringwald              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
305157be49d6SMatthias Ringwald              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
3052c99bb618SMatthias Ringwald     uint8_t event[23];
305357be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
305457be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
305557be49d6SMatthias Ringwald     event[2] = status;
305657be49d6SMatthias Ringwald     event[3] = channel->address_type;
305757be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[4]);
305857be49d6SMatthias Ringwald     little_endian_store_16(event, 10, channel->con_handle);
3059c99bb618SMatthias Ringwald     event[12] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
3060c99bb618SMatthias Ringwald     little_endian_store_16(event, 13, channel->psm);
3061c99bb618SMatthias Ringwald     little_endian_store_16(event, 15, channel->local_cid);
3062c99bb618SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_cid);
3063c99bb618SMatthias Ringwald     little_endian_store_16(event, 19, channel->local_mtu);
3064c99bb618SMatthias Ringwald     little_endian_store_16(event, 21, channel->remote_mtu);
306557be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
306657be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
306757be49d6SMatthias Ringwald }
306857be49d6SMatthias Ringwald 
306957be49d6SMatthias Ringwald static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid){
307057be49d6SMatthias Ringwald     btstack_linked_list_iterator_t it;
307157be49d6SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
307257be49d6SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
307357be49d6SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
307457be49d6SMatthias Ringwald         if ( channel->local_cid == local_cid) {
307557be49d6SMatthias Ringwald             return channel;
307657be49d6SMatthias Ringwald         }
307757be49d6SMatthias Ringwald     }
307857be49d6SMatthias Ringwald     return NULL;
307957be49d6SMatthias Ringwald }
308057be49d6SMatthias Ringwald 
308157be49d6SMatthias Ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
308257be49d6SMatthias Ringwald void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
308357be49d6SMatthias Ringwald     channel->state = L2CAP_STATE_CLOSED;
308457be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
308557be49d6SMatthias Ringwald     // discard channel
308657be49d6SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
308757be49d6SMatthias Ringwald     btstack_memory_l2cap_channel_free(channel);
308857be49d6SMatthias Ringwald }
308957be49d6SMatthias Ringwald 
3090e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
3091e7d0c9aaSMatthias Ringwald     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
30927192e786SMatthias Ringwald }
3093efedfb4cSMatthias Ringwald 
3094da144af5SMatthias Ringwald uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
30957192e786SMatthias Ringwald 
3096da144af5SMatthias Ringwald     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
30977192e786SMatthias Ringwald 
30987192e786SMatthias Ringwald     // check for alread registered psm
30997192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
31007192e786SMatthias Ringwald     if (service) {
3101da144af5SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
31027192e786SMatthias Ringwald     }
31037192e786SMatthias Ringwald 
31047192e786SMatthias Ringwald     // alloc structure
31057192e786SMatthias Ringwald     service = btstack_memory_l2cap_service_get();
31067192e786SMatthias Ringwald     if (!service) {
31077192e786SMatthias Ringwald         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
3108da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
31097192e786SMatthias Ringwald     }
31107192e786SMatthias Ringwald 
31117192e786SMatthias Ringwald     // fill in
31127192e786SMatthias Ringwald     service->psm = psm;
3113da144af5SMatthias Ringwald     service->mtu = 0;
31147192e786SMatthias Ringwald     service->packet_handler = packet_handler;
31157192e786SMatthias Ringwald     service->required_security_level = security_level;
31167192e786SMatthias Ringwald 
31177192e786SMatthias Ringwald     // add to services list
3118665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
31197192e786SMatthias Ringwald 
31207192e786SMatthias Ringwald     // done
3121da144af5SMatthias Ringwald     return 0;
31227192e786SMatthias Ringwald }
31237192e786SMatthias Ringwald 
3124da144af5SMatthias Ringwald uint8_t l2cap_le_unregister_service(uint16_t psm) {
31257192e786SMatthias Ringwald     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
31267192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
31279367f9b0SMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3128da144af5SMatthias Ringwald 
3129665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
31307192e786SMatthias Ringwald     btstack_memory_l2cap_service_free(service);
3131da144af5SMatthias Ringwald     return 0;
31327192e786SMatthias Ringwald }
3133da144af5SMatthias Ringwald 
3134da144af5SMatthias Ringwald uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
3135e7d0c9aaSMatthias Ringwald     // get channel
3136e7d0c9aaSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3137e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3138e7d0c9aaSMatthias Ringwald 
3139e7d0c9aaSMatthias Ringwald     // validate state
3140e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3141e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
3142e7d0c9aaSMatthias Ringwald     }
3143e7d0c9aaSMatthias Ringwald 
3144efedfb4cSMatthias Ringwald     // set state accept connection
314523017473SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
314623017473SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
314723017473SMatthias Ringwald     channel->local_mtu = mtu;
314885aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
314985aeef60SMatthias Ringwald     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
315085aeef60SMatthias Ringwald 
315185aeef60SMatthias Ringwald     // test
315263f0ac45SMatthias Ringwald     // channel->new_credits_incoming = 1;
3153e7d0c9aaSMatthias Ringwald 
3154e7d0c9aaSMatthias Ringwald     // go
3155e7d0c9aaSMatthias Ringwald     l2cap_run();
3156da144af5SMatthias Ringwald     return 0;
3157da144af5SMatthias Ringwald }
3158da144af5SMatthias Ringwald 
3159da144af5SMatthias Ringwald /**
3160da144af5SMatthias Ringwald  * @brief Deny incoming LE Data Channel connection due to resource constraints
3161da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3162da144af5SMatthias Ringwald  */
3163da144af5SMatthias Ringwald 
3164da144af5SMatthias Ringwald uint8_t l2cap_le_decline_connection(uint16_t local_cid){
3165e7d0c9aaSMatthias Ringwald     // get channel
3166e7d0c9aaSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3167e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3168e7d0c9aaSMatthias Ringwald 
3169e7d0c9aaSMatthias Ringwald     // validate state
3170e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3171e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
3172e7d0c9aaSMatthias Ringwald     }
3173e7d0c9aaSMatthias Ringwald 
3174efedfb4cSMatthias Ringwald     // set state decline connection
3175e7d0c9aaSMatthias Ringwald     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
3176e7d0c9aaSMatthias Ringwald     channel->reason = 0x04; // no resources available
3177e7d0c9aaSMatthias Ringwald     l2cap_run();
3178da144af5SMatthias Ringwald     return 0;
3179da144af5SMatthias Ringwald }
3180da144af5SMatthias Ringwald 
31817dafa750SMatthias Ringwald uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
3182da144af5SMatthias Ringwald     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
3183efedfb4cSMatthias Ringwald     uint16_t * out_local_cid) {
3184efedfb4cSMatthias Ringwald 
31857dafa750SMatthias Ringwald     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
3186da144af5SMatthias Ringwald 
31877dafa750SMatthias Ringwald 
31887dafa750SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
31897dafa750SMatthias Ringwald     if (!connection) {
31907dafa750SMatthias Ringwald         log_error("no hci_connection for handle 0x%04x", con_handle);
31917dafa750SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
31927dafa750SMatthias Ringwald     }
31937dafa750SMatthias Ringwald 
31947dafa750SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, connection->address, connection->address_type, psm, mtu, security_level);
3195da144af5SMatthias Ringwald     if (!channel) {
3196da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
3197da144af5SMatthias Ringwald     }
3198e7d0c9aaSMatthias Ringwald     log_info("l2cap_le_create_channel %p", channel);
3199da144af5SMatthias Ringwald 
3200da144af5SMatthias Ringwald     // store local_cid
3201da144af5SMatthias Ringwald     if (out_local_cid){
3202da144af5SMatthias Ringwald        *out_local_cid = channel->local_cid;
3203da144af5SMatthias Ringwald     }
3204da144af5SMatthias Ringwald 
32057dafa750SMatthias Ringwald     // provide buffer
32067dafa750SMatthias Ringwald     channel->con_handle = con_handle;
3207cd529728SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
32087dafa750SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
320985aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
321085aeef60SMatthias Ringwald     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
321185aeef60SMatthias Ringwald 
3212efedfb4cSMatthias Ringwald     // add to connections list
3213efedfb4cSMatthias Ringwald     btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
3214efedfb4cSMatthias Ringwald 
32157dafa750SMatthias Ringwald     // go
321663f0ac45SMatthias Ringwald     l2cap_run();
3217da144af5SMatthias Ringwald     return 0;
3218da144af5SMatthias Ringwald }
3219da144af5SMatthias Ringwald 
3220da144af5SMatthias Ringwald /**
3221da144af5SMatthias Ringwald  * @brief Provide credtis for LE Data Channel
3222da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3223da144af5SMatthias Ringwald  * @param credits               Number additional credits for peer
3224da144af5SMatthias Ringwald  */
322564e11ca9SMatthias Ringwald uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
322663f0ac45SMatthias Ringwald 
322763f0ac45SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
322863f0ac45SMatthias Ringwald     if (!channel) {
322963f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
323063f0ac45SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
323163f0ac45SMatthias Ringwald     }
323263f0ac45SMatthias Ringwald 
3233efedfb4cSMatthias Ringwald     // check state
323463f0ac45SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN){
323563f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
323663f0ac45SMatthias Ringwald     }
323763f0ac45SMatthias Ringwald 
323863f0ac45SMatthias Ringwald     // assert incoming credits + credits <= 0xffff
323963f0ac45SMatthias Ringwald     uint32_t total_credits = channel->credits_incoming;
324063f0ac45SMatthias Ringwald     total_credits += channel->new_credits_incoming;
324163f0ac45SMatthias Ringwald     total_credits += credits;
324263f0ac45SMatthias Ringwald     if (total_credits > 0xffff){
324363f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
324463f0ac45SMatthias Ringwald             channel->new_credits_incoming, credits);
324563f0ac45SMatthias Ringwald     }
324663f0ac45SMatthias Ringwald 
3247efedfb4cSMatthias Ringwald     // set credits_granted
324863f0ac45SMatthias Ringwald     channel->new_credits_incoming += credits;
324963f0ac45SMatthias Ringwald 
325063f0ac45SMatthias Ringwald     // go
325163f0ac45SMatthias Ringwald     l2cap_run();
3252da144af5SMatthias Ringwald     return 0;
3253da144af5SMatthias Ringwald }
3254da144af5SMatthias Ringwald 
3255da144af5SMatthias Ringwald /**
3256da144af5SMatthias Ringwald  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
3257da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3258da144af5SMatthias Ringwald  */
325964e11ca9SMatthias Ringwald int l2cap_le_can_send_now(uint16_t local_cid){
326044276248SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
326144276248SMatthias Ringwald     if (!channel) {
326244276248SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
3263da144af5SMatthias Ringwald         return 0;
3264da144af5SMatthias Ringwald     }
3265da144af5SMatthias Ringwald 
326644276248SMatthias Ringwald     // check state
326744276248SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN) return 0;
326844276248SMatthias Ringwald 
326944276248SMatthias Ringwald     // check queue
327044276248SMatthias Ringwald     if (channel->send_sdu_buffer) return 0;
327144276248SMatthias Ringwald 
327244276248SMatthias Ringwald     // fine, go ahead
327344276248SMatthias Ringwald     return 1;
327444276248SMatthias Ringwald }
327544276248SMatthias Ringwald 
3276da144af5SMatthias Ringwald /**
3277da144af5SMatthias Ringwald  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
3278da144af5SMatthias Ringwald  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
3279da144af5SMatthias Ringwald  *       so packet handler should be ready to handle it
3280da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3281da144af5SMatthias Ringwald  */
328264e11ca9SMatthias Ringwald uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
328344276248SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
328444276248SMatthias Ringwald     if (!channel) {
328544276248SMatthias Ringwald         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
328644276248SMatthias Ringwald         return 0;
328744276248SMatthias Ringwald     }
328844276248SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
328944276248SMatthias Ringwald     l2cap_le_notify_channel_can_send(channel);
3290da144af5SMatthias Ringwald     return 0;
3291da144af5SMatthias Ringwald }
3292da144af5SMatthias Ringwald 
3293da144af5SMatthias Ringwald /**
3294da144af5SMatthias Ringwald  * @brief Send data via LE Data Channel
3295da144af5SMatthias Ringwald  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
3296da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3297da144af5SMatthias Ringwald  * @param data                  data to send
3298da144af5SMatthias Ringwald  * @param size                  data size
3299da144af5SMatthias Ringwald  */
330064e11ca9SMatthias Ringwald uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
330164e11ca9SMatthias Ringwald 
330264e11ca9SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
330364e11ca9SMatthias Ringwald     if (!channel) {
330464e11ca9SMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
3305828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
330664e11ca9SMatthias Ringwald     }
330764e11ca9SMatthias Ringwald 
330864e11ca9SMatthias Ringwald     if (len > channel->remote_mtu){
330964e11ca9SMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
331064e11ca9SMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
331164e11ca9SMatthias Ringwald     }
331264e11ca9SMatthias Ringwald 
33137f107edaSMatthias Ringwald     if (channel->send_sdu_buffer){
331464e11ca9SMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
331564e11ca9SMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
331664e11ca9SMatthias Ringwald     }
331764e11ca9SMatthias Ringwald 
33187f107edaSMatthias Ringwald     channel->send_sdu_buffer = data;
33197f107edaSMatthias Ringwald     channel->send_sdu_len    = len;
33207f107edaSMatthias Ringwald     channel->send_sdu_pos    = 0;
332164e11ca9SMatthias Ringwald 
33227f107edaSMatthias Ringwald     l2cap_run();
33237f107edaSMatthias Ringwald     return 0;
3324da144af5SMatthias Ringwald }
3325da144af5SMatthias Ringwald 
3326da144af5SMatthias Ringwald /**
3327da144af5SMatthias Ringwald  * @brief Disconnect from LE Data Channel
3328da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3329da144af5SMatthias Ringwald  */
3330828a7f7aSMatthias Ringwald uint8_t l2cap_le_disconnect(uint16_t local_cid)
3331da144af5SMatthias Ringwald {
3332828a7f7aSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3333828a7f7aSMatthias Ringwald     if (!channel) {
3334828a7f7aSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
3335828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3336828a7f7aSMatthias Ringwald     }
3337828a7f7aSMatthias Ringwald 
3338828a7f7aSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3339828a7f7aSMatthias Ringwald     l2cap_run();
3340da144af5SMatthias Ringwald     return 0;
3341da144af5SMatthias Ringwald }
3342da144af5SMatthias Ringwald 
33437f02f414SMatthias Ringwald #endif
3344