xref: /btstack/src/l2cap.c (revision 7b7901d8619124fc91fdf824bdcf9c089e08e916)
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 
21385ddcd84SMatthias Ringwald     uint8_t test[] = {0x0E, 0x00, 0x40, 0x00, 0x02, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 };
21485ddcd84SMatthias Ringwald     printf("crc16: %04x\n", crc16_calc(test, sizeof(test)));
21585ddcd84SMatthias Ringwald 
21609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
217f5454fc6Smatthias.ringwald     l2cap_channels = NULL;
218f5454fc6Smatthias.ringwald     l2cap_services = NULL;
21909e9d05bSMatthias Ringwald     require_security_level2_for_outgoing_sdp = 0;
22009e9d05bSMatthias Ringwald #endif
221a3dc965aSMatthias Ringwald 
222a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2237192e786SMatthias Ringwald     l2cap_le_services = NULL;
2247192e786SMatthias Ringwald     l2cap_le_channels = NULL;
225a3dc965aSMatthias Ringwald #endif
226f5454fc6Smatthias.ringwald 
227d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
22833c40538SMatthias Ringwald     l2cap_event_packet_handler = NULL;
229d6ed9f9cSMatthias Ringwald #endif
2305628cf69SMatthias Ringwald     memset(fixed_channels, 0, sizeof(fixed_channels));
231f5454fc6Smatthias.ringwald 
232fcadd0caSmatthias.ringwald     //
2332718e2e7Smatthias.ringwald     // register callback with HCI
234fcadd0caSmatthias.ringwald     //
235d9a7306aSMatthias Ringwald     hci_event_callback_registration.callback = &l2cap_hci_event_handler;
236fb37a842SMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
237fb37a842SMatthias Ringwald 
238d9a7306aSMatthias Ringwald     hci_register_acl_packet_handler(&l2cap_acl_handler);
239fb37a842SMatthias Ringwald 
240be005ed6SMatthias Ringwald #ifdef ENABLE_CLASSIC
24115a95bd5SMatthias Ringwald     gap_connectable_control(0); // no services yet
242be005ed6SMatthias Ringwald #endif
243fcadd0caSmatthias.ringwald }
244fcadd0caSmatthias.ringwald 
245ffbf8201SMatthias Ringwald void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
246d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
24733c40538SMatthias Ringwald     l2cap_event_packet_handler = handler;
248d6ed9f9cSMatthias Ringwald #else
249d6ed9f9cSMatthias Ringwald     UNUSED(handler);
250d6ed9f9cSMatthias Ringwald #endif
2511e6aba47Smatthias.ringwald }
2521e6aba47Smatthias.ringwald 
25309e9d05bSMatthias Ringwald void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
2549ec2630cSMatthias Ringwald     UNUSED(con_handle);
2559ec2630cSMatthias Ringwald 
25609e9d05bSMatthias Ringwald     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
25709e9d05bSMatthias Ringwald     if (index < 0) return;
25809e9d05bSMatthias Ringwald     fixed_channels[index].waiting_for_can_send_now = 1;
25909e9d05bSMatthias Ringwald     l2cap_notify_channel_can_send();
26009e9d05bSMatthias Ringwald }
26109e9d05bSMatthias Ringwald 
26209e9d05bSMatthias Ringwald int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
2639ec2630cSMatthias Ringwald     UNUSED(channel_id);
2649ec2630cSMatthias Ringwald 
26509e9d05bSMatthias Ringwald     return hci_can_send_acl_packet_now(con_handle);
26609e9d05bSMatthias Ringwald }
26709e9d05bSMatthias Ringwald 
26809e9d05bSMatthias Ringwald uint8_t *l2cap_get_outgoing_buffer(void){
26909e9d05bSMatthias Ringwald     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
27009e9d05bSMatthias Ringwald }
27109e9d05bSMatthias Ringwald 
27209e9d05bSMatthias Ringwald int l2cap_reserve_packet_buffer(void){
27309e9d05bSMatthias Ringwald     return hci_reserve_packet_buffer();
27409e9d05bSMatthias Ringwald }
27509e9d05bSMatthias Ringwald 
27609e9d05bSMatthias Ringwald void l2cap_release_packet_buffer(void){
27709e9d05bSMatthias Ringwald     hci_release_packet_buffer();
27809e9d05bSMatthias Ringwald }
27909e9d05bSMatthias Ringwald 
280f511cefaSMatthias 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){
28109e9d05bSMatthias Ringwald     // 0 - Connection handle : PB=pb : BC=00
282f511cefaSMatthias Ringwald     little_endian_store_16(acl_buffer, 0, con_handle | (packet_boundary << 12) | (0 << 14));
28309e9d05bSMatthias Ringwald     // 2 - ACL length
28409e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 2,  len + 4);
28509e9d05bSMatthias Ringwald     // 4 - L2CAP packet length
28609e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 4,  len + 0);
28709e9d05bSMatthias Ringwald     // 6 - L2CAP channel DEST
28809e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 6,  remote_cid);
28909e9d05bSMatthias Ringwald }
29009e9d05bSMatthias Ringwald 
291f511cefaSMatthias Ringwald // assumption - only on LE connections
29209e9d05bSMatthias Ringwald int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
29309e9d05bSMatthias Ringwald 
29409e9d05bSMatthias Ringwald     if (!hci_is_packet_buffer_reserved()){
29509e9d05bSMatthias Ringwald         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
29609e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
29709e9d05bSMatthias Ringwald     }
29809e9d05bSMatthias Ringwald 
29909e9d05bSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
30009e9d05bSMatthias Ringwald         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
30109e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
30209e9d05bSMatthias Ringwald     }
30309e9d05bSMatthias Ringwald 
30409e9d05bSMatthias Ringwald     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
30509e9d05bSMatthias Ringwald 
30609e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
307f511cefaSMatthias Ringwald     l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
30809e9d05bSMatthias Ringwald     // send
30909e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len+8);
31009e9d05bSMatthias Ringwald }
31109e9d05bSMatthias Ringwald 
312f511cefaSMatthias Ringwald // assumption - only on LE connections
31309e9d05bSMatthias Ringwald int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
31409e9d05bSMatthias Ringwald 
31509e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(con_handle)){
31609e9d05bSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", cid);
31709e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
31809e9d05bSMatthias Ringwald     }
31909e9d05bSMatthias Ringwald 
32009e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
32109e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
32209e9d05bSMatthias Ringwald 
32309e9d05bSMatthias Ringwald     memcpy(&acl_buffer[8], data, len);
32409e9d05bSMatthias Ringwald 
32509e9d05bSMatthias Ringwald     return l2cap_send_prepared_connectionless(con_handle, cid, len);
32609e9d05bSMatthias Ringwald }
32709e9d05bSMatthias Ringwald 
32809e9d05bSMatthias Ringwald static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
329d9d23054SMatthias Ringwald     log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
33009e9d05bSMatthias Ringwald     uint8_t event[4];
33109e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
33209e9d05bSMatthias Ringwald     event[1] = sizeof(event) - 2;
33309e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, channel);
33409e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
33509e9d05bSMatthias Ringwald     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
33609e9d05bSMatthias Ringwald }
33709e9d05bSMatthias Ringwald 
33809e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
33917a9b554SMatthias Ringwald static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
34058de5610Smatthias.ringwald     (* (channel->packet_handler))(type, channel->local_cid, data, size);
34158de5610Smatthias.ringwald }
34258de5610Smatthias.ringwald 
34344276248SMatthias Ringwald static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
34444276248SMatthias Ringwald     uint8_t event[4];
34544276248SMatthias Ringwald     event[0] = event_code;
34644276248SMatthias Ringwald     event[1] = sizeof(event) - 2;
34744276248SMatthias Ringwald     little_endian_store_16(event, 2, channel->local_cid);
34844276248SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
34944276248SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
35044276248SMatthias Ringwald }
35109e9d05bSMatthias Ringwald #endif
35244276248SMatthias Ringwald 
35309e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
35458de5610Smatthias.ringwald void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
355c9dc710bS[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",
356fc64f94aSMatthias Ringwald              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
357c9dc710bS[email protected]              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
358bab5f4f0SMatthias Ringwald     uint8_t event[24];
35958de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
36058de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
36158de5610Smatthias.ringwald     event[2] = status;
362724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
363fc64f94aSMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
364f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
365f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
366f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
367f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 17, channel->local_mtu);
368f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 19, channel->remote_mtu);
369f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 21, channel->flush_timeout);
370bab5f4f0SMatthias Ringwald     event[23] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
37158de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
37217a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
37358de5610Smatthias.ringwald }
37458de5610Smatthias.ringwald 
37544276248SMatthias Ringwald static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
376e0abb8e7S[email protected]     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
37744276248SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
37858de5610Smatthias.ringwald }
37958de5610Smatthias.ringwald 
38044276248SMatthias Ringwald static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
381e0abb8e7S[email protected]     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
382fc64f94aSMatthias Ringwald              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
38358de5610Smatthias.ringwald     uint8_t event[16];
38458de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
38558de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
386724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[2]);
387fc64f94aSMatthias Ringwald     little_endian_store_16(event,  8, channel->con_handle);
388f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 10, channel->psm);
389f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 12, channel->local_cid);
390f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 14, channel->remote_cid);
39158de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
39217a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3930af41d30Smatthias.ringwald }
394808a48abSmatthias.ringwald 
3957f02f414SMatthias Ringwald static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
396665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
397665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
398665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
399665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
400b35f641cSmatthias.ringwald         if ( channel->local_cid == local_cid) {
401f62db1e3Smatthias.ringwald             return channel;
402f62db1e3Smatthias.ringwald         }
403f62db1e3Smatthias.ringwald     }
404f62db1e3Smatthias.ringwald     return NULL;
405f62db1e3Smatthias.ringwald }
406f62db1e3Smatthias.ringwald 
4070b9d7e78SMatthias Ringwald ///
4080b9d7e78SMatthias Ringwald 
40930725612SMatthias Ringwald void l2cap_request_can_send_now_event(uint16_t local_cid){
41030725612SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
41130725612SMatthias Ringwald     if (!channel) return;
41230725612SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
41330725612SMatthias Ringwald     l2cap_notify_channel_can_send();
41430725612SMatthias Ringwald }
41530725612SMatthias Ringwald 
4166b1fde37Smatthias.ringwald int  l2cap_can_send_packet_now(uint16_t local_cid){
4176b1fde37Smatthias.ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
4186b1fde37Smatthias.ringwald     if (!channel) return 0;
4190b9d7e78SMatthias Ringwald     return hci_can_send_acl_packet_now(channel->con_handle);
4207856fb31S[email protected] }
4217856fb31S[email protected] 
42283e7cdd9SMatthias Ringwald int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
42383e7cdd9SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
42483e7cdd9SMatthias Ringwald     if (!channel) return 0;
4250b9d7e78SMatthias Ringwald     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
42683e7cdd9SMatthias Ringwald }
42796cbd662Smatthias.ringwald uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
42896cbd662Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
42996cbd662Smatthias.ringwald     if (channel) {
43096cbd662Smatthias.ringwald         return channel->remote_mtu;
43196cbd662Smatthias.ringwald     }
43296cbd662Smatthias.ringwald     return 0;
43396cbd662Smatthias.ringwald }
43496cbd662Smatthias.ringwald 
435ec820d77SMatthias Ringwald static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
436665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
437665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
438665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
439665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4405932bd7cS[email protected]         if ( &channel->rtx == ts) {
4415932bd7cS[email protected]             return channel;
4425932bd7cS[email protected]         }
4435932bd7cS[email protected]     }
4445932bd7cS[email protected]     return NULL;
4455932bd7cS[email protected] }
4465932bd7cS[email protected] 
447ec820d77SMatthias Ringwald static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
4485932bd7cS[email protected]     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
44995d2c8f4SMatthias Ringwald     if (!channel) return;
4505932bd7cS[email protected] 
4515932bd7cS[email protected]     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
4525932bd7cS[email protected] 
4535932bd7cS[email protected]     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
4545932bd7cS[email protected]     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
4555932bd7cS[email protected]     // notify client
4565932bd7cS[email protected]     l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
4575932bd7cS[email protected] 
4585932bd7cS[email protected]     // discard channel
4599dcb2fb2S[email protected]     // no need to stop timer here, it is removed from list during timer callback
460665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4615932bd7cS[email protected]     btstack_memory_l2cap_channel_free(channel);
4625932bd7cS[email protected] }
4635932bd7cS[email protected] 
4645932bd7cS[email protected] static void l2cap_stop_rtx(l2cap_channel_t * channel){
4655932bd7cS[email protected]     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
466528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->rtx);
4675932bd7cS[email protected] }
4685932bd7cS[email protected] 
4695932bd7cS[email protected] static void l2cap_start_rtx(l2cap_channel_t * channel){
4705932bd7cS[email protected]     l2cap_stop_rtx(channel);
471cb0ff06bS[email protected]     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
472528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
473528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
474528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
4755932bd7cS[email protected] }
4765932bd7cS[email protected] 
4775932bd7cS[email protected] static void l2cap_start_ertx(l2cap_channel_t * channel){
4785932bd7cS[email protected]     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
4795932bd7cS[email protected]     l2cap_stop_rtx(channel);
480528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
481528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
482528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
4835932bd7cS[email protected] }
4845932bd7cS[email protected] 
48571de195eSMatthias Ringwald void l2cap_require_security_level_2_for_outgoing_sdp(void){
486ac301f95S[email protected]     require_security_level2_for_outgoing_sdp = 1;
487ac301f95S[email protected] }
488ac301f95S[email protected] 
489df3354fcS[email protected] static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
490235946f1SMatthias Ringwald     return (psm == BLUETOOTH_PROTOCOL_SDP) && (!require_security_level2_for_outgoing_sdp);
491df3354fcS[email protected] }
4925932bd7cS[email protected] 
4937f02f414SMatthias Ringwald static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
494a35252c8S[email protected]     if (!hci_can_send_acl_packet_now(handle)){
4959da54300S[email protected]         log_info("l2cap_send_signaling_packet, cannot send");
496b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
497b1d43497Smatthias.ringwald     }
498b1d43497Smatthias.ringwald 
4999da54300S[email protected]     // log_info("l2cap_send_signaling_packet type %u", cmd);
5002a373862S[email protected]     hci_reserve_packet_buffer();
501facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
50258de5610Smatthias.ringwald     va_list argptr;
50358de5610Smatthias.ringwald     va_start(argptr, identifier);
50470efece1S[email protected]     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
50558de5610Smatthias.ringwald     va_end(argptr);
5069da54300S[email protected]     // log_info("l2cap_send_signaling_packet con %u!", handle);
507826f7347S[email protected]     return hci_send_acl_packet_buffer(len);
50858de5610Smatthias.ringwald }
50958de5610Smatthias.ringwald 
510f511cefaSMatthias Ringwald // assumption - only on Classic connections
511b1d43497Smatthias.ringwald int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
512b1d43497Smatthias.ringwald 
513c8b9416aS[email protected]     if (!hci_is_packet_buffer_reserved()){
514c8b9416aS[email protected]         log_error("l2cap_send_prepared called without reserving packet first");
515c8b9416aS[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
516c8b9416aS[email protected]     }
517c8b9416aS[email protected] 
51858de5610Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
519b1d43497Smatthias.ringwald     if (!channel) {
5209da54300S[email protected]         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
521b1d43497Smatthias.ringwald         return -1;   // TODO: define error
5226218e6f1Smatthias.ringwald     }
5236218e6f1Smatthias.ringwald 
524fc64f94aSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
5259da54300S[email protected]         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
526a35252c8S[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
527a35252c8S[email protected]     }
528a35252c8S[email protected] 
529fc64f94aSMatthias Ringwald     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
530b1d43497Smatthias.ringwald 
53185ddcd84SMatthias Ringwald     int fcs_size = 0;
53285ddcd84SMatthias Ringwald 
53385ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
53485ddcd84SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
53585ddcd84SMatthias Ringwald         fcs_size = 2;
53685ddcd84SMatthias Ringwald     }
53785ddcd84SMatthias Ringwald #endif
53885ddcd84SMatthias Ringwald 
539f511cefaSMatthias Ringwald     // set non-flushable packet boundary flag if supported on Controller
540facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
541f511cefaSMatthias Ringwald     uint8_t packet_boundary_flag = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
54285ddcd84SMatthias Ringwald     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
54385ddcd84SMatthias Ringwald 
54485ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
54585ddcd84SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
54685ddcd84SMatthias Ringwald         // calculate FCS over l2cap data
54785ddcd84SMatthias Ringwald         uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
54885ddcd84SMatthias Ringwald         log_info("I-Frame: fcs 0x%04x", fcs);
54985ddcd84SMatthias Ringwald         little_endian_store_16(acl_buffer, 8 + len, fcs);
55058de5610Smatthias.ringwald     }
55185ddcd84SMatthias Ringwald #endif
55285ddcd84SMatthias Ringwald 
55385ddcd84SMatthias Ringwald     // send
55485ddcd84SMatthias Ringwald     return hci_send_acl_packet_buffer(len+8+fcs_size);
55585ddcd84SMatthias Ringwald }
55685ddcd84SMatthias Ringwald 
55785ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
55885ddcd84SMatthias 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){
55985ddcd84SMatthias Ringwald     return (((uint16_t) sar) << 14) | (req_seq << 8) | (final << 7) | (tx_seq << 1) | 0;
56085ddcd84SMatthias Ringwald }
56185ddcd84SMatthias 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){
56238f62777SMatthias Ringwald     return (req_seq << 8) | (final << 7) | (poll << 4) | (((int) supervisory_function) << 2) | 1;
56385ddcd84SMatthias Ringwald }
56485ddcd84SMatthias Ringwald static int l2cap_next_ertm_seq_nr(int seq_nr){
56585ddcd84SMatthias Ringwald     return (seq_nr + 1) & 0x3f;
56685ddcd84SMatthias Ringwald }
567f0fb4cd7SMatthias Ringwald static void l2cap_ertm_next_tx_write_index(l2cap_channel_t * channel){
568f0fb4cd7SMatthias Ringwald     channel->tx_write_index++;
569f0fb4cd7SMatthias Ringwald     if (channel->tx_write_index < channel->num_tx_buffers) return;
570f0fb4cd7SMatthias Ringwald     channel->tx_write_index = 0;
571f0fb4cd7SMatthias Ringwald }
57220fa474dSMatthias Ringwald static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts){
57320fa474dSMatthias Ringwald     log_info("l2cap_ertm_monitor_timeout_callback");
574db55d2e9SMatthias Ringwald     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
575db55d2e9SMatthias Ringwald 
576db55d2e9SMatthias Ringwald     // TODO: we assume that it's the oldest packet
577db55d2e9SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
578db55d2e9SMatthias Ringwald     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
579db55d2e9SMatthias Ringwald 
580db55d2e9SMatthias Ringwald     // check retry count
581db55d2e9SMatthias Ringwald     if (tx_state->retry_count < l2cap_channel->remote_max_transmit){
582db55d2e9SMatthias Ringwald         // increment retry count
583db55d2e9SMatthias Ringwald         tx_state->retry_count++;
584db55d2e9SMatthias Ringwald 
585db55d2e9SMatthias Ringwald         // start monitor timer
586db55d2e9SMatthias Ringwald         btstack_run_loop_set_timer_handler(&tx_state->monitor_timer, &l2cap_ertm_monitor_timeout_callback);
587db55d2e9SMatthias Ringwald         btstack_run_loop_set_timer_context(&tx_state->monitor_timer, l2cap_channel);
588db55d2e9SMatthias Ringwald         btstack_run_loop_set_timer(&tx_state->monitor_timer, l2cap_channel->local_monitor_timeout_ms);
589db55d2e9SMatthias Ringwald         btstack_run_loop_add_timer(&tx_state->monitor_timer);
590db55d2e9SMatthias Ringwald 
591db55d2e9SMatthias Ringwald         // send RR/P=1
592db55d2e9SMatthias Ringwald         l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
593db55d2e9SMatthias Ringwald     } else {
594db55d2e9SMatthias Ringwald         log_info("Monitor timer expired & retry count >= max transmit -> disconnect");
595db55d2e9SMatthias Ringwald         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
596db55d2e9SMatthias Ringwald     }
597db55d2e9SMatthias Ringwald     l2cap_run();
598db55d2e9SMatthias Ringwald }
599db55d2e9SMatthias Ringwald static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts){
600db55d2e9SMatthias Ringwald     log_info("l2cap_ertm_retransmission_timeout_callback");
601db55d2e9SMatthias Ringwald     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
602db55d2e9SMatthias Ringwald 
603db55d2e9SMatthias Ringwald     // TODO: we assume that it's the oldest packet
604db55d2e9SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
605db55d2e9SMatthias Ringwald     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
606db55d2e9SMatthias Ringwald 
607db55d2e9SMatthias Ringwald     // set retry count = 1
608db55d2e9SMatthias Ringwald     tx_state->retry_count = 1;
609db55d2e9SMatthias Ringwald 
610db55d2e9SMatthias Ringwald     // start monitor timer
611db55d2e9SMatthias Ringwald     btstack_run_loop_set_timer_handler(&tx_state->monitor_timer, &l2cap_ertm_monitor_timeout_callback);
612db55d2e9SMatthias Ringwald     btstack_run_loop_set_timer_context(&tx_state->monitor_timer, l2cap_channel);
613db55d2e9SMatthias Ringwald     btstack_run_loop_set_timer(&tx_state->monitor_timer, l2cap_channel->local_monitor_timeout_ms);
614db55d2e9SMatthias Ringwald     btstack_run_loop_add_timer(&tx_state->monitor_timer);
615db55d2e9SMatthias Ringwald 
616db55d2e9SMatthias Ringwald     // send RR/P=1
617db55d2e9SMatthias Ringwald     l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
61820fa474dSMatthias Ringwald     l2cap_run();
61920fa474dSMatthias Ringwald }
620*7b7901d8SMatthias Ringwald static int l2cap_ertm_send_information_frame(l2cap_channel_t * channel, int index, int final){
621f0fb4cd7SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
622f0fb4cd7SMatthias Ringwald     hci_reserve_packet_buffer();
623f0fb4cd7SMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
624*7b7901d8SMatthias Ringwald     uint16_t control = l2cap_encanced_control_field_for_information_frame(tx_state->tx_seq, final, 0, L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU);
625f0fb4cd7SMatthias Ringwald     log_info("I-Frame: control 0x%04x", control);
626f0fb4cd7SMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
627f0fb4cd7SMatthias Ringwald     memcpy(&acl_buffer[8+2], &channel->tx_packets_data[index * channel->local_mtu], tx_state->len);
628f0fb4cd7SMatthias Ringwald     // send
629f0fb4cd7SMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2 + tx_state->len);
630f0fb4cd7SMatthias Ringwald }
631f0fb4cd7SMatthias Ringwald static int l2cap_ertm_send(l2cap_channel_t * channel, uint8_t * data, uint16_t len){
632f0fb4cd7SMatthias Ringwald     if (len > channel->remote_mtu){
633f0fb4cd7SMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
634f0fb4cd7SMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
635f0fb4cd7SMatthias Ringwald     }
636f0fb4cd7SMatthias Ringwald     // TODO: check tx_transmit
6372a424812SMatthias Ringwald     // store int tx packet bufferx
638f0fb4cd7SMatthias Ringwald     int index = channel->tx_write_index;
639f0fb4cd7SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
640f0fb4cd7SMatthias Ringwald     tx_state->tx_seq = channel->next_tx_seq;
641f0fb4cd7SMatthias Ringwald     tx_state->len = len;
642db55d2e9SMatthias Ringwald     tx_state->retry_count = 0;
643f0fb4cd7SMatthias Ringwald     memcpy(&channel->tx_packets_data[index * channel->local_mtu], data, len);
644f0fb4cd7SMatthias Ringwald     // update
645f0fb4cd7SMatthias Ringwald     channel->next_tx_seq = l2cap_next_ertm_seq_nr(channel->next_tx_seq);
646f0fb4cd7SMatthias Ringwald     l2cap_ertm_next_tx_write_index(channel);
64762041d70SMatthias Ringwald     // set retransmission timer
64862041d70SMatthias Ringwald     btstack_run_loop_set_timer_handler(&tx_state->retransmission_timer, &l2cap_ertm_retransmission_timeout_callback);
64962041d70SMatthias Ringwald     btstack_run_loop_set_timer_context(&tx_state->retransmission_timer, channel);
65062041d70SMatthias Ringwald     btstack_run_loop_set_timer(&tx_state->retransmission_timer, channel->local_retransmission_timeout_ms);
65162041d70SMatthias Ringwald     btstack_run_loop_add_timer(&tx_state->retransmission_timer);
652675e6881SMatthias Ringwald     // try to send
653675e6881SMatthias Ringwald     l2cap_run();
654f0fb4cd7SMatthias Ringwald     return 0;
655f0fb4cd7SMatthias Ringwald }
65685ddcd84SMatthias Ringwald #endif
65758de5610Smatthias.ringwald 
658f511cefaSMatthias Ringwald // assumption - only on Classic connections
659ce8f182eSMatthias Ringwald int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
660a35252c8S[email protected]     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
661a35252c8S[email protected]     if (!channel) {
662ce8f182eSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
663a35252c8S[email protected]         return -1;   // TODO: define error
664a35252c8S[email protected]     }
665a35252c8S[email protected] 
666f0fb4cd7SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
667f0fb4cd7SMatthias Ringwald     // send in ERTM
668f0fb4cd7SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
669f0fb4cd7SMatthias Ringwald         return l2cap_ertm_send(channel, data, len);
670f0fb4cd7SMatthias Ringwald     }
671f0fb4cd7SMatthias Ringwald #endif
672f0fb4cd7SMatthias Ringwald 
673f0efaa57S[email protected]     if (len > channel->remote_mtu){
674ce8f182eSMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
675f0efaa57S[email protected]         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
676f0efaa57S[email protected]     }
677f0efaa57S[email protected] 
678fc64f94aSMatthias Ringwald     if (!hci_can_send_acl_packet_now(channel->con_handle)){
679ce8f182eSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
680b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
681b1d43497Smatthias.ringwald     }
682b1d43497Smatthias.ringwald 
6832a373862S[email protected]     hci_reserve_packet_buffer();
684facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
685f0fb4cd7SMatthias Ringwald     memcpy(&acl_buffer[8], data, len);
686f0fb4cd7SMatthias Ringwald     return l2cap_send_prepared(local_cid, len);
687b1d43497Smatthias.ringwald }
688b1d43497Smatthias.ringwald 
689fc64f94aSMatthias Ringwald int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
690fc64f94aSMatthias Ringwald     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
6910e37e417S[email protected] }
6920e37e417S[email protected] 
69328ca2b46S[email protected] static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
69428ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
69528ca2b46S[email protected] }
69628ca2b46S[email protected] 
69728ca2b46S[email protected] static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
69828ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
69928ca2b46S[email protected] }
70009e9d05bSMatthias Ringwald #endif
70128ca2b46S[email protected] 
70228ca2b46S[email protected] 
70309e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
70409e9d05bSMatthias Ringwald static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
70509e9d05bSMatthias Ringwald 
70609e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(handle)){
70709e9d05bSMatthias Ringwald         log_info("l2cap_send_le_signaling_packet, cannot send");
70809e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
70909e9d05bSMatthias Ringwald     }
71009e9d05bSMatthias Ringwald 
71109e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
71209e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
71309e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
71409e9d05bSMatthias Ringwald     va_list argptr;
71509e9d05bSMatthias Ringwald     va_start(argptr, identifier);
71609e9d05bSMatthias Ringwald     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
71709e9d05bSMatthias Ringwald     va_end(argptr);
71809e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
71909e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len);
72009e9d05bSMatthias Ringwald }
72109e9d05bSMatthias Ringwald #endif
72209e9d05bSMatthias Ringwald 
72309e9d05bSMatthias Ringwald uint16_t l2cap_max_mtu(void){
72409e9d05bSMatthias Ringwald     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
72509e9d05bSMatthias Ringwald }
72609e9d05bSMatthias Ringwald 
72709e9d05bSMatthias Ringwald uint16_t l2cap_max_le_mtu(void){
72809e9d05bSMatthias Ringwald     return l2cap_max_mtu();
72909e9d05bSMatthias Ringwald }
730b1d43497Smatthias.ringwald 
731450ad7ecSMatthias Ringwald static uint16_t l2cap_setup_options_mtu(l2cap_channel_t * channel, uint8_t * config_options){
732450ad7ecSMatthias Ringwald     config_options[0] = 1; // MTU
733450ad7ecSMatthias Ringwald     config_options[1] = 2; // len param
734450ad7ecSMatthias Ringwald     little_endian_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
735450ad7ecSMatthias Ringwald     return 4;
736450ad7ecSMatthias Ringwald }
737450ad7ecSMatthias Ringwald 
7386dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
739450ad7ecSMatthias Ringwald static uint16_t l2cap_setup_options_ertm(l2cap_channel_t * channel, uint8_t * config_options){
7406dca2a0cSMatthias Ringwald     config_options[0] = 0x04;   // RETRANSMISSION AND FLOW CONTROL OPTION
7416dca2a0cSMatthias Ringwald     config_options[1] = 9;      // length
7426dca2a0cSMatthias Ringwald     config_options[2] = (uint8_t) channel->mode;
7437b181629SMatthias Ringwald     config_options[3] = channel->num_rx_buffers;    // == TxWindows size
744bbc0a9e7SMatthias Ringwald     config_options[4] = channel->local_max_transmit;
745bbc0a9e7SMatthias Ringwald     little_endian_store_16( config_options, 5, channel->local_retransmission_timeout_ms);
746bbc0a9e7SMatthias Ringwald     little_endian_store_16( config_options, 7, channel->local_monitor_timeout_ms);
7477b181629SMatthias Ringwald     little_endian_store_16( config_options, 9, channel->local_mtu);
748450ad7ecSMatthias Ringwald     return 11;
7496dca2a0cSMatthias Ringwald }
75038f62777SMatthias Ringwald static int l2cap_ertm_send_supervisor_frame(l2cap_channel_t * channel, uint16_t control){
75138f62777SMatthias Ringwald     hci_reserve_packet_buffer();
75238f62777SMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
75338f62777SMatthias Ringwald     log_info("S-Frame: control 0x%04x", control);
75438f62777SMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
75538f62777SMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2);
75638f62777SMatthias Ringwald }
757212b6be2SMatthias Ringwald static int l2cap_ertm_num_unacknowledged_tx_packets(l2cap_channel_t * channel){
758212b6be2SMatthias Ringwald     int unacknowledged_packets = channel->tx_send_index - channel->tx_read_index;
759212b6be2SMatthias Ringwald     if (unacknowledged_packets < 0){
760212b6be2SMatthias Ringwald         unacknowledged_packets += channel->num_tx_buffers;
761212b6be2SMatthias Ringwald     }
762212b6be2SMatthias Ringwald     return unacknowledged_packets;
763212b6be2SMatthias Ringwald }
764450ad7ecSMatthias Ringwald #endif
765450ad7ecSMatthias Ringwald 
766450ad7ecSMatthias Ringwald static uint16_t l2cap_setup_options(l2cap_channel_t * channel, uint8_t * config_options){
767450ad7ecSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
768450ad7ecSMatthias Ringwald     // use ERTM options if supported
769450ad7ecSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
770450ad7ecSMatthias Ringwald     if ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE) && (connection->l2cap_state.extended_feature_mask & 0x08)){
771450ad7ecSMatthias Ringwald         return l2cap_setup_options_ertm(channel, config_options);
772450ad7ecSMatthias Ringwald 
773450ad7ecSMatthias Ringwald     }
774450ad7ecSMatthias Ringwald #endif
775450ad7ecSMatthias Ringwald     return l2cap_setup_options_mtu(channel, config_options);
7766dca2a0cSMatthias Ringwald }
7776dca2a0cSMatthias Ringwald 
7781b9cb13dSMatthias Ringwald static uint32_t l2cap_extended_features_mask(void){
7791b9cb13dSMatthias Ringwald     // extended features request supported, features: fixed channels, unicast connectionless data reception
7801b9cb13dSMatthias Ringwald     uint32_t features = 0x280;
7811b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
7821b9cb13dSMatthias Ringwald     features |= 0x0008;
7831b9cb13dSMatthias Ringwald #endif
7841b9cb13dSMatthias Ringwald     return features;
7851b9cb13dSMatthias Ringwald }
7861b9cb13dSMatthias Ringwald 
7878158c421Smatthias.ringwald // MARK: L2CAP_RUN
7882cd0be45Smatthias.ringwald // process outstanding signaling tasks
7897f02f414SMatthias Ringwald static void l2cap_run(void){
7902b83fb7dSmatthias.ringwald 
79122c29ab4SMatthias Ringwald     // log_info("l2cap_run: entered");
79222c29ab4SMatthias Ringwald 
7932b83fb7dSmatthias.ringwald     // check pending signaling responses
7942b83fb7dSmatthias.ringwald     while (signaling_responses_pending){
7952b83fb7dSmatthias.ringwald 
7962b83fb7dSmatthias.ringwald         hci_con_handle_t handle = signaling_responses[0].handle;
797a35252c8S[email protected] 
798a35252c8S[email protected]         if (!hci_can_send_acl_packet_now(handle)) break;
799a35252c8S[email protected] 
8002b83fb7dSmatthias.ringwald         uint8_t  sig_id        = signaling_responses[0].sig_id;
801e74c5f58SMatthias Ringwald         uint8_t  response_code = signaling_responses[0].code;
8022b360848Smatthias.ringwald         uint16_t infoType      = signaling_responses[0].data;  // INFORMATION_REQUEST
80363a7246aSmatthias.ringwald         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
804b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
805b3264428SMatthias Ringwald         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
806b3264428SMatthias Ringwald #endif
807f3963406SMatthias Ringwald         UNUSED(infoType);
80809e9d05bSMatthias Ringwald 
809f53da564S[email protected]         // remove first item before sending (to avoid sending response mutliple times)
810f53da564S[email protected]         signaling_responses_pending--;
811f53da564S[email protected]         int i;
812f53da564S[email protected]         for (i=0; i < signaling_responses_pending; i++){
813f53da564S[email protected]             memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t));
814f53da564S[email protected]         }
815f53da564S[email protected] 
816f53da564S[email protected]         switch (response_code){
81709e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
8182b360848Smatthias.ringwald             case CONNECTION_REQUEST:
819e74c5f58SMatthias Ringwald                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
8202bd8b7e7S[email protected]                 // also disconnect if result is 0x0003 - security blocked
8214d816277S[email protected]                 if (result == 0x0003){
8222bd8b7e7S[email protected]                     hci_disconnect_security_block(handle);
8234d816277S[email protected]                 }
8242b360848Smatthias.ringwald                 break;
8252b83fb7dSmatthias.ringwald             case ECHO_REQUEST:
8262b83fb7dSmatthias.ringwald                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
8272b83fb7dSmatthias.ringwald                 break;
8282b83fb7dSmatthias.ringwald             case INFORMATION_REQUEST:
8293b0484b3S[email protected]                 switch (infoType){
8303b0484b3S[email protected]                     case 1: { // Connectionless MTU
8313b0484b3S[email protected]                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
8323b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(connectionless_mtu), &connectionless_mtu);
8333b0484b3S[email protected]                         }
834202c8a4cSMatthias Ringwald                         break;
8353b0484b3S[email protected]                     case 2: {  // Extended Features Supported
8361b9cb13dSMatthias Ringwald                             uint32_t features = l2cap_extended_features_mask();
8373b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(features), &features);
8383b0484b3S[email protected]                         }
839202c8a4cSMatthias Ringwald                         break;
8403b0484b3S[email protected]                     case 3: { // Fixed Channels Supported
8413b0484b3S[email protected]                             uint8_t map[8];
8423b0484b3S[email protected]                             memset(map, 0, 8);
843288636a2SMatthias Ringwald                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
8443b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(map), &map);
8453b0484b3S[email protected]                         }
846202c8a4cSMatthias Ringwald                         break;
8473b0484b3S[email protected]                     default:
8482b83fb7dSmatthias.ringwald                         // all other types are not supported
8492b83fb7dSmatthias.ringwald                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
8503b0484b3S[email protected]                         break;
8512b83fb7dSmatthias.ringwald                 }
8522b83fb7dSmatthias.ringwald                 break;
85363a7246aSmatthias.ringwald             case COMMAND_REJECT:
8545ca8d57bS[email protected]                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
85563f0ac45SMatthias Ringwald                 break;
85609e9d05bSMatthias Ringwald #endif
857a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
85863f0ac45SMatthias Ringwald             case LE_CREDIT_BASED_CONNECTION_REQUEST:
85963f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
86063f0ac45SMatthias Ringwald                 break;
86170efece1S[email protected]             case COMMAND_REJECT_LE:
86270efece1S[email protected]                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
86363a7246aSmatthias.ringwald                 break;
86470efece1S[email protected] #endif
8652b83fb7dSmatthias.ringwald             default:
8662b83fb7dSmatthias.ringwald                 // should not happen
8672b83fb7dSmatthias.ringwald                 break;
8682b83fb7dSmatthias.ringwald         }
8692b83fb7dSmatthias.ringwald     }
8702b83fb7dSmatthias.ringwald 
871665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
872f3963406SMatthias Ringwald     UNUSED(it);
87309e9d05bSMatthias Ringwald 
8741b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
8751b9cb13dSMatthias Ringwald     // send l2cap information request if neccessary
8761b9cb13dSMatthias Ringwald     hci_connections_get_iterator(&it);
8771b9cb13dSMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
8781b9cb13dSMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
8791b9cb13dSMatthias Ringwald         if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST){
8801b9cb13dSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
8811b9cb13dSMatthias Ringwald             // send information request for extended features
8821b9cb13dSMatthias Ringwald             uint8_t sig_id = l2cap_next_sig_id();
8831b9cb13dSMatthias Ringwald             uint8_t info_type = 2;
8841b9cb13dSMatthias Ringwald             l2cap_send_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
8851b9cb13dSMatthias Ringwald             return;
8861b9cb13dSMatthias Ringwald         }
8871b9cb13dSMatthias Ringwald     }
8881b9cb13dSMatthias Ringwald #endif
8891b9cb13dSMatthias Ringwald 
89009e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
89143ec931dSMatthias Ringwald     uint8_t  config_options[10];
892665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
893665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
894baf94f06S[email protected] 
895665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
89622c29ab4SMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
8972cd0be45Smatthias.ringwald         switch (channel->state){
8982cd0be45Smatthias.ringwald 
899df3354fcS[email protected]             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
900ad671560S[email protected]             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
901fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
902a00031e2S[email protected]                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
903ad671560S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
904fc64f94aSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
905ad671560S[email protected]                 }
906ad671560S[email protected]                 break;
907ad671560S[email protected] 
90802b22dc4Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
909baf94f06S[email protected]                 if (!hci_can_send_command_packet_now()) break;
91064472d52Smatthias.ringwald                 // send connection request - set state first
91164472d52Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
91202b22dc4Smatthias.ringwald                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
9138f8108aaSmatthias.ringwald                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
91402b22dc4Smatthias.ringwald                 break;
91502b22dc4Smatthias.ringwald 
916e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
917fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
91822c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
919fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
920e7ff783cSmatthias.ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
9219dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
922665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
923d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
924e7ff783cSmatthias.ringwald                 break;
925e7ff783cSmatthias.ringwald 
926552d92a1Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
927fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
928fa8473a4Smatthias.ringwald                 channel->state = L2CAP_STATE_CONFIG;
92928ca2b46S[email protected]                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
930fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
931552d92a1Smatthias.ringwald                 break;
932552d92a1Smatthias.ringwald 
9336fdcc387Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
934fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
9356fdcc387Smatthias.ringwald                 // success, start l2cap handshake
936b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
9376fdcc387Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
938fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
9395932bd7cS[email protected]                 l2cap_start_rtx(channel);
9406fdcc387Smatthias.ringwald                 break;
9416fdcc387Smatthias.ringwald 
942fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
943fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
94473cf2b3dSmatthias.ringwald                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
94563a7246aSmatthias.ringwald                     uint16_t flags = 0;
94628ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
94763a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
94863a7246aSmatthias.ringwald                         flags = 1;
94963a7246aSmatthias.ringwald                     } else {
95028ca2b46S[email protected]                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
95163a7246aSmatthias.ringwald                     }
95263a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
953ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
954fc64f94aSMatthias 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);
955ac8f1300SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
956ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
957ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
958ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
9596dca2a0cSMatthias Ringwald                         uint16_t options_size = l2cap_setup_options(channel, config_options);
960ac8f1300SMatthias 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);
961ac8f1300SMatthias Ringwald #endif
962ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
96363a7246aSmatthias.ringwald                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
964ac8f1300SMatthias Ringwald                         uint16_t options_size = l2cap_setup_options(channel, config_options);
965ac8f1300SMatthias 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);
96663a7246aSmatthias.ringwald                     } else {
967ac8f1300SMatthias Ringwald                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
96863a7246aSmatthias.ringwald                     }
96963a7246aSmatthias.ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
970fa8473a4Smatthias.ringwald                 }
97173cf2b3dSmatthias.ringwald                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
97228ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
97328ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
974b1988dceSmatthias.ringwald                     channel->local_sig_id = l2cap_next_sig_id();
9756dca2a0cSMatthias Ringwald                     uint16_t options_size = l2cap_setup_options(channel, config_options);
9766dca2a0cSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options);
9775932bd7cS[email protected]                     l2cap_start_rtx(channel);
978fa8473a4Smatthias.ringwald                 }
979fa8473a4Smatthias.ringwald                 if (l2cap_channel_ready_for_open(channel)){
980552d92a1Smatthias.ringwald                     channel->state = L2CAP_STATE_OPEN;
981552d92a1Smatthias.ringwald                     l2cap_emit_channel_opened(channel, 0);  // success
982fa8473a4Smatthias.ringwald                 }
983552d92a1Smatthias.ringwald                 break;
984552d92a1Smatthias.ringwald 
985e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
986fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
98722c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
988fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
9895932bd7cS[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 :)
990756102d3Smatthias.ringwald                 l2cap_finialize_channel_close(channel);  // -- remove from list
991e7ff783cSmatthias.ringwald                 break;
992e7ff783cSmatthias.ringwald 
993e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
994fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
995b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
9962cd0be45Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
997fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
9982cd0be45Smatthias.ringwald                 break;
9992cd0be45Smatthias.ringwald             default:
10002cd0be45Smatthias.ringwald                 break;
10012cd0be45Smatthias.ringwald         }
100238f62777SMatthias Ringwald 
100338f62777SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
100438f62777SMatthias Ringwald         // send s-frame to acknowledge received packets
100538f62777SMatthias Ringwald         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
1006675e6881SMatthias Ringwald 
1007675e6881SMatthias Ringwald         if (channel->tx_send_index != channel->tx_write_index){
1008212b6be2SMatthias Ringwald             int unacknowledged_packets = l2cap_ertm_num_unacknowledged_tx_packets(channel);
1009212b6be2SMatthias Ringwald             // check remote tx window
1010212b6be2SMatthias Ringwald             log_info("unacknowledged_packets %u, remote tx window size %u", unacknowledged_packets, channel->remote_tx_window_size);
1011212b6be2SMatthias Ringwald             if (unacknowledged_packets < channel->remote_tx_window_size){
1012675e6881SMatthias Ringwald                 int index = channel->tx_send_index;
1013675e6881SMatthias Ringwald                 channel->tx_send_index++;
1014675e6881SMatthias Ringwald                 if (channel->tx_send_index >= channel->num_tx_buffers){
1015675e6881SMatthias Ringwald                     channel->tx_send_index = 0;
1016675e6881SMatthias Ringwald                 }
1017*7b7901d8SMatthias Ringwald                 l2cap_ertm_send_information_frame(channel, index, 0);   // final = 0
1018675e6881SMatthias Ringwald                 continue;
1019675e6881SMatthias Ringwald             }
1020212b6be2SMatthias Ringwald         }
1021675e6881SMatthias Ringwald 
1022d84e866fSMatthias Ringwald         if (channel->send_supervisor_frame_receiver_ready){
102378cd8a22SMatthias Ringwald             channel->send_supervisor_frame_receiver_ready = 0;
1024d84e866fSMatthias Ringwald             log_info("Send S-Frame: RR %u", channel->req_seq);
102538f62777SMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 0, 0, channel->req_seq);
102638f62777SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
1027675e6881SMatthias Ringwald             continue;
102838f62777SMatthias Ringwald         }
102962041d70SMatthias Ringwald         if (channel->send_supervisor_frame_receiver_ready_poll){
103078cd8a22SMatthias Ringwald             channel->send_supervisor_frame_receiver_ready_poll = 0;
103162041d70SMatthias Ringwald             log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
103262041d70SMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
103362041d70SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
103462041d70SMatthias Ringwald             continue;
103562041d70SMatthias Ringwald         }
103678cd8a22SMatthias Ringwald         if (channel->send_supervisor_frame_receiver_ready_final){
103778cd8a22SMatthias Ringwald             channel->send_supervisor_frame_receiver_ready_final = 0;
103878cd8a22SMatthias Ringwald             log_info("Send S-Frame: RR %u with final=1 ", channel->req_seq);
103978cd8a22SMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 0, 1, channel->req_seq);
104078cd8a22SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
104178cd8a22SMatthias Ringwald             continue;
104278cd8a22SMatthias Ringwald         }
10438f1c9639SMatthias Ringwald         if (channel->send_supervisor_frame_receiver_not_ready){
104478cd8a22SMatthias Ringwald             channel->send_supervisor_frame_receiver_not_ready = 0;
10458f1c9639SMatthias Ringwald             log_info("Send S-Frame: RNR %u", channel->req_seq);
10468f1c9639SMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
10478f1c9639SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
10488f1c9639SMatthias Ringwald             continue;
10498f1c9639SMatthias Ringwald         }
1050*7b7901d8SMatthias Ringwald 
1051*7b7901d8SMatthias Ringwald         if (channel->srej_active){
1052*7b7901d8SMatthias Ringwald             int i;
1053*7b7901d8SMatthias Ringwald             for (i=0;i<channel->num_tx_buffers;i++){
1054*7b7901d8SMatthias Ringwald                 l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
1055*7b7901d8SMatthias Ringwald                 if (tx_state->retransmission_requested) {
1056*7b7901d8SMatthias Ringwald                     tx_state->retransmission_requested = 0;
1057*7b7901d8SMatthias Ringwald                     l2cap_ertm_send_information_frame(channel, i, 1);   // final = 1 as SREJ has poll = 1
1058*7b7901d8SMatthias Ringwald                     break;
1059*7b7901d8SMatthias Ringwald                 }
1060*7b7901d8SMatthias Ringwald             }
1061*7b7901d8SMatthias Ringwald             if (i == channel->num_tx_buffers){
1062*7b7901d8SMatthias Ringwald                 // no retransmission request found
1063*7b7901d8SMatthias Ringwald                 channel->srej_active = 0;
1064*7b7901d8SMatthias Ringwald             } else {
1065*7b7901d8SMatthias Ringwald                 // packet was sent
1066*7b7901d8SMatthias Ringwald                 continue;
1067*7b7901d8SMatthias Ringwald             }
1068*7b7901d8SMatthias Ringwald         }
106938f62777SMatthias Ringwald #endif
107038f62777SMatthias Ringwald 
10712cd0be45Smatthias.ringwald     }
107209e9d05bSMatthias Ringwald #endif
1073da886c03S[email protected] 
1074cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1075efedfb4cSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1076efedfb4cSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
10777f107edaSMatthias Ringwald         uint8_t  * acl_buffer;
10787f107edaSMatthias Ringwald         uint8_t  * l2cap_payload;
10797f107edaSMatthias Ringwald         uint16_t pos;
10807f107edaSMatthias Ringwald         uint16_t payload_size;
1081efedfb4cSMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1082efedfb4cSMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1083efedfb4cSMatthias Ringwald         switch (channel->state){
10845cb87675SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
10855cb87675SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
10865cb87675SMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
10875cb87675SMatthias Ringwald                 // le psm, source cid, mtu, mps, initial credits
10881b8b8d05SMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
108963f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
109063f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
109163f0ac45SMatthias 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);
10925cb87675SMatthias Ringwald                 break;
109323017473SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
109423017473SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
109523017473SMatthias Ringwald                 // TODO: support larger MPS
109623017473SMatthias Ringwald                 channel->state = L2CAP_STATE_OPEN;
109763f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
109863f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
109963f0ac45SMatthias 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);
110064e11ca9SMatthias Ringwald                 // notify client
110144276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0);
110223017473SMatthias Ringwald                 break;
1103e7d0c9aaSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
1104e7d0c9aaSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1105e7d0c9aaSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
110663f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
1107e7d0c9aaSMatthias Ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1108e7d0c9aaSMatthias Ringwald                 l2cap_stop_rtx(channel);
1109e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1110e7d0c9aaSMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
1111e7d0c9aaSMatthias Ringwald                 break;
11127f107edaSMatthias Ringwald             case L2CAP_STATE_OPEN:
111385aeef60SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
111485aeef60SMatthias Ringwald 
111585aeef60SMatthias Ringwald                 // send credits
111685aeef60SMatthias Ringwald                 if (channel->new_credits_incoming){
111785aeef60SMatthias Ringwald                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
111885aeef60SMatthias Ringwald                     channel->local_sig_id = l2cap_next_sig_id();
111985aeef60SMatthias Ringwald                     uint16_t new_credits = channel->new_credits_incoming;
112085aeef60SMatthias Ringwald                     channel->new_credits_incoming = 0;
112185aeef60SMatthias Ringwald                     channel->credits_incoming += new_credits;
112285aeef60SMatthias Ringwald                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
112385aeef60SMatthias Ringwald                     break;
112485aeef60SMatthias Ringwald                 }
112585aeef60SMatthias Ringwald 
112685aeef60SMatthias Ringwald                 // send data
11277f107edaSMatthias Ringwald                 if (!channel->send_sdu_buffer) break;
11287f107edaSMatthias Ringwald                 if (!channel->credits_outgoing) break;
112985aeef60SMatthias Ringwald 
11307f107edaSMatthias Ringwald                 // send part of SDU
11317f107edaSMatthias Ringwald                 hci_reserve_packet_buffer();
11327f107edaSMatthias Ringwald                 acl_buffer = hci_get_outgoing_packet_buffer();
11337f107edaSMatthias Ringwald                 l2cap_payload = acl_buffer + 8;
11347f107edaSMatthias Ringwald                 pos = 0;
11357f107edaSMatthias Ringwald                 if (!channel->send_sdu_pos){
11367f107edaSMatthias Ringwald                     // store SDU len
11377f107edaSMatthias Ringwald                     channel->send_sdu_pos += 2;
11387f107edaSMatthias Ringwald                     little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
11397f107edaSMatthias Ringwald                     pos += 2;
11407f107edaSMatthias Ringwald                 }
11417f107edaSMatthias Ringwald                 payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
114285aeef60SMatthias Ringwald                 log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
11437f107edaSMatthias Ringwald                 memcpy(&l2cap_payload[pos], &channel->send_sdu_buffer[channel->send_sdu_pos-2], payload_size); // -2 for virtual SDU len
11447f107edaSMatthias Ringwald                 pos += payload_size;
11457f107edaSMatthias Ringwald                 channel->send_sdu_pos += payload_size;
1146f511cefaSMatthias Ringwald                 l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
11477f107edaSMatthias Ringwald                 // done
11487f107edaSMatthias Ringwald 
114985aeef60SMatthias Ringwald                 channel->credits_outgoing--;
11507f107edaSMatthias Ringwald 
11517f107edaSMatthias Ringwald                 if (channel->send_sdu_pos >= channel->send_sdu_len + 2){
11527f107edaSMatthias Ringwald                     channel->send_sdu_buffer = NULL;
115344276248SMatthias Ringwald                     // send done event
115444276248SMatthias Ringwald                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
115544276248SMatthias Ringwald                     // inform about can send now
115644276248SMatthias Ringwald                     l2cap_le_notify_channel_can_send(channel);
11577f107edaSMatthias Ringwald                 }
11587f107edaSMatthias Ringwald                 hci_send_acl_packet_buffer(8 + pos);
11597f107edaSMatthias Ringwald                 break;
1160828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1161828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1162828a7f7aSMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
1163828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1164828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1165828a7f7aSMatthias Ringwald                 break;
1166828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1167828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1168828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1169828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1170828a7f7aSMatthias Ringwald                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
1171828a7f7aSMatthias Ringwald                 break;
1172efedfb4cSMatthias Ringwald             default:
1173efedfb4cSMatthias Ringwald                 break;
1174efedfb4cSMatthias Ringwald         }
1175efedfb4cSMatthias Ringwald     }
117609e9d05bSMatthias Ringwald #endif
1177efedfb4cSMatthias Ringwald 
117809e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
1179da886c03S[email protected]     // send l2cap con paramter update if necessary
1180da886c03S[email protected]     hci_connections_get_iterator(&it);
1181665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
1182665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
11835d14fa8fSMatthias Ringwald         if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue;
1184b68d7bc3SMatthias Ringwald         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
1185da886c03S[email protected]         switch (connection->le_con_parameter_update_state){
1186b68d7bc3SMatthias Ringwald             case CON_PARAMETER_UPDATE_SEND_REQUEST:
1187b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1188b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier,
1189b68d7bc3SMatthias Ringwald                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
1190b68d7bc3SMatthias Ringwald                 break;
1191da886c03S[email protected]             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
1192b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
1193b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
1194da886c03S[email protected]                 break;
1195da886c03S[email protected]             case CON_PARAMETER_UPDATE_DENY:
1196b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1197b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
1198da886c03S[email protected]                 break;
1199da886c03S[email protected]             default:
1200da886c03S[email protected]                 break;
1201da886c03S[email protected]         }
1202da886c03S[email protected]     }
12034d7157c3S[email protected] #endif
1204da886c03S[email protected] 
120522c29ab4SMatthias Ringwald     // log_info("l2cap_run: exit");
12062cd0be45Smatthias.ringwald }
12072cd0be45Smatthias.ringwald 
120809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1209fc64f94aSMatthias Ringwald static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
12102df5dadcS[email protected]     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
12115533f01eS[email protected]         log_info("l2cap_handle_connection_complete expected state");
12122df5dadcS[email protected]         // success, start l2cap handshake
1213fc64f94aSMatthias Ringwald         channel->con_handle = con_handle;
12142df5dadcS[email protected]         // check remote SSP feature first
12152df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
12162df5dadcS[email protected]     }
12172df5dadcS[email protected] }
12182df5dadcS[email protected] 
12191b9cb13dSMatthias Ringwald static void l2cap_ready_to_connect(l2cap_channel_t * channel){
12201b9cb13dSMatthias Ringwald 
12211b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
122227e0774aSMatthias Ringwald     // assumption: outgoing connection
12231b9cb13dSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
12241b9cb13dSMatthias Ringwald     if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
12251b9cb13dSMatthias Ringwald         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
12261b9cb13dSMatthias Ringwald         channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
12271b9cb13dSMatthias Ringwald         return;
12281b9cb13dSMatthias Ringwald     }
12291b9cb13dSMatthias Ringwald #endif
12301b9cb13dSMatthias Ringwald 
12311b9cb13dSMatthias Ringwald     // fine, go ahead
12321b9cb13dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
12331b9cb13dSMatthias Ringwald }
12341b9cb13dSMatthias Ringwald 
12352df5dadcS[email protected] static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
12362df5dadcS[email protected]     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
12372df5dadcS[email protected] 
12382df5dadcS[email protected]     // we have been waiting for remote supported features, if both support SSP,
1239ac301f95S[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));
1240fc64f94aSMatthias Ringwald     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
12412df5dadcS[email protected]         // request security level 2
12422df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
1243fc64f94aSMatthias Ringwald         gap_request_security_level(channel->con_handle, LEVEL_2);
12442df5dadcS[email protected]         return;
12452df5dadcS[email protected]     }
12461b9cb13dSMatthias Ringwald 
12471b9cb13dSMatthias Ringwald     l2cap_ready_to_connect(channel);
12482df5dadcS[email protected] }
124909e9d05bSMatthias Ringwald #endif
12502df5dadcS[email protected] 
125109e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
1252da144af5SMatthias 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,
1253da144af5SMatthias Ringwald     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
1254da144af5SMatthias Ringwald 
1255da144af5SMatthias Ringwald     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1256da144af5SMatthias Ringwald     if (!channel) {
1257da144af5SMatthias Ringwald         return NULL;
1258da144af5SMatthias Ringwald     }
1259da144af5SMatthias Ringwald 
1260da144af5SMatthias Ringwald      // Init memory (make valgrind happy)
1261da144af5SMatthias Ringwald     memset(channel, 0, sizeof(l2cap_channel_t));
1262da144af5SMatthias Ringwald 
1263da144af5SMatthias Ringwald     // fill in
1264da144af5SMatthias Ringwald     channel->packet_handler = packet_handler;
1265da144af5SMatthias Ringwald     bd_addr_copy(channel->address, address);
1266da144af5SMatthias Ringwald     channel->address_type = address_type;
1267da144af5SMatthias Ringwald     channel->psm = psm;
1268da144af5SMatthias Ringwald     channel->local_mtu  = local_mtu;
1269da144af5SMatthias Ringwald     channel->remote_mtu = L2CAP_MINIMAL_MTU;
1270da144af5SMatthias Ringwald     channel->required_security_level = security_level;
1271da144af5SMatthias Ringwald 
1272da144af5SMatthias Ringwald     //
1273da144af5SMatthias Ringwald     channel->local_cid = l2cap_next_local_cid();
1274da144af5SMatthias Ringwald     channel->con_handle = 0;
1275da144af5SMatthias Ringwald 
1276da144af5SMatthias Ringwald     // set initial state
1277da144af5SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
1278da144af5SMatthias Ringwald     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
1279da144af5SMatthias Ringwald     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
1280da144af5SMatthias Ringwald     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
128138f62777SMatthias Ringwald 
1282da144af5SMatthias Ringwald     return channel;
1283da144af5SMatthias Ringwald }
128409e9d05bSMatthias Ringwald #endif
128509e9d05bSMatthias Ringwald 
128609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1287da144af5SMatthias Ringwald 
12889077cb15SMatthias Ringwald /**
12899077cb15SMatthias Ringwald  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
12909077cb15SMatthias Ringwald  * @param packet_handler
12919077cb15SMatthias Ringwald  * @param address
12929077cb15SMatthias Ringwald  * @param psm
12939077cb15SMatthias Ringwald  * @param mtu
12949077cb15SMatthias Ringwald  * @param local_cid
12959077cb15SMatthias Ringwald  */
12969077cb15SMatthias Ringwald 
12979d139fbaSMatthias 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){
12989d139fbaSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
12999d139fbaSMatthias Ringwald     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1300da144af5SMatthias Ringwald 
13019d139fbaSMatthias 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);
1302da144af5SMatthias Ringwald 
1303da144af5SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
1304fc64f94aSMatthias Ringwald     if (!channel) {
13059077cb15SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
13069077cb15SMatthias Ringwald     }
13079077cb15SMatthias Ringwald 
13081b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
13091b9cb13dSMatthias Ringwald     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
13101b9cb13dSMatthias Ringwald #endif
13111b9cb13dSMatthias Ringwald 
13129077cb15SMatthias Ringwald     // add to connections list
1313fc64f94aSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
13149077cb15SMatthias Ringwald 
13159077cb15SMatthias Ringwald     // store local_cid
13169077cb15SMatthias Ringwald     if (out_local_cid){
1317fc64f94aSMatthias Ringwald        *out_local_cid = channel->local_cid;
13189077cb15SMatthias Ringwald     }
13199077cb15SMatthias Ringwald 
13209077cb15SMatthias Ringwald     // check if hci connection is already usable
13219077cb15SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
13229077cb15SMatthias Ringwald     if (conn){
1323add0254bSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
1324fc64f94aSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
13259077cb15SMatthias Ringwald         // check if remote supported fearures are already received
13269077cb15SMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
1327fc64f94aSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
13289077cb15SMatthias Ringwald         }
13299077cb15SMatthias Ringwald     }
13309077cb15SMatthias Ringwald 
13319077cb15SMatthias Ringwald     l2cap_run();
13329077cb15SMatthias Ringwald 
13339077cb15SMatthias Ringwald     return 0;
13349077cb15SMatthias Ringwald }
13359077cb15SMatthias Ringwald 
13361b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
13377b181629SMatthias Ringwald 
13382b70d705SMatthias Ringwald static uint8_t l2cap_ertm_validate_local_config(uint8_t max_transmit, uint16_t retransmission_timeout_ms,
13392b70d705SMatthias Ringwald     uint16_t monitor_timeout_ms, uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size){
13402b70d705SMatthias Ringwald     UNUSED(buffer);
13412b70d705SMatthias Ringwald     UNUSED(size);
13422b70d705SMatthias Ringwald 
13432b70d705SMatthias Ringwald     uint8_t result = ERROR_CODE_SUCCESS;
13442b70d705SMatthias Ringwald     if (max_transmit < 1){
13452b70d705SMatthias Ringwald         log_error("max_transmit must be >= 1");
13462b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
13472b70d705SMatthias Ringwald     }
13482b70d705SMatthias Ringwald     if (retransmission_timeout_ms < 2000){
13492b70d705SMatthias Ringwald         log_error("retransmission_timeout_ms must be >= 2000 ms");
13502b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
13512b70d705SMatthias Ringwald     }
13522b70d705SMatthias Ringwald     if (monitor_timeout_ms < 12000){
13532b70d705SMatthias Ringwald         log_error("monitor_timeout_ms must be >= 12000 ms");
13542b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
13552b70d705SMatthias Ringwald     }
13562b70d705SMatthias Ringwald     if (num_rx_buffers < 1){
13572b70d705SMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
13582b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
13592b70d705SMatthias Ringwald     }
13602b70d705SMatthias Ringwald     if (num_tx_buffers < 1){
13612b70d705SMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
13622b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
13632b70d705SMatthias Ringwald     }
13642b70d705SMatthias Ringwald     return result;
13652b70d705SMatthias Ringwald }
13662b70d705SMatthias Ringwald 
13677b181629SMatthias Ringwald static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, int ertm_mandatory, uint8_t max_transmit,
13687b181629SMatthias Ringwald     uint16_t retransmission_timeout_ms, uint16_t monitor_timeout_ms, uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size){
13697b181629SMatthias Ringwald 
13707b181629SMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
13717b181629SMatthias Ringwald     channel->ertm_mandatory = ertm_mandatory;
1372bbc0a9e7SMatthias Ringwald     channel->local_max_transmit = max_transmit;
1373bbc0a9e7SMatthias Ringwald     channel->local_retransmission_timeout_ms = retransmission_timeout_ms;
1374bbc0a9e7SMatthias Ringwald     channel->local_monitor_timeout_ms = monitor_timeout_ms;
13757b181629SMatthias Ringwald     channel->num_rx_buffers = num_rx_buffers;
13767b181629SMatthias Ringwald     channel->num_tx_buffers = num_tx_buffers;
13777b181629SMatthias Ringwald 
13787b181629SMatthias Ringwald     // TODO: align buffer pointer
13797b181629SMatthias Ringwald     uint32_t pos = 0;
13807b181629SMatthias Ringwald     channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) &buffer[pos];
13817b181629SMatthias Ringwald     pos += num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
13827b181629SMatthias Ringwald     channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) &buffer[pos];
13837b181629SMatthias Ringwald     pos += num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
13847b181629SMatthias Ringwald     // calculate MTU
13857b181629SMatthias Ringwald     channel->local_mtu = (size - pos) / (num_rx_buffers + num_tx_buffers);
13867b181629SMatthias Ringwald     log_info("Local ERTM MTU: %u", channel->local_mtu);
13877b181629SMatthias Ringwald     channel->rx_packets_data = &buffer[pos];
13887b181629SMatthias Ringwald     pos += num_rx_buffers * channel->local_mtu;
13897b181629SMatthias Ringwald     channel->tx_packets_data = &buffer[pos];
13907b181629SMatthias Ringwald     log_info("RX packets %p, TX packets %p", channel->rx_packets_data, channel->tx_packets_data);
13917b181629SMatthias Ringwald }
13927b181629SMatthias Ringwald 
1393501329faSMatthias Ringwald uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
1394501329faSMatthias Ringwald     int ertm_mandatory, uint8_t max_transmit, uint16_t retransmission_timeout_ms, uint16_t monitor_timeout_ms,
1395501329faSMatthias Ringwald     uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
1396501329faSMatthias Ringwald 
13971b9cb13dSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
1398501329faSMatthias Ringwald     uint16_t local_mtu = l2cap_max_mtu();
13991b9cb13dSMatthias Ringwald 
1400501329faSMatthias Ringwald     log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x -> local mtu %u", bd_addr_to_str(address), psm, local_mtu);
14011b9cb13dSMatthias Ringwald 
14022b70d705SMatthias Ringwald     // validate local config
14032b70d705SMatthias Ringwald     uint8_t result = l2cap_ertm_validate_local_config(max_transmit, retransmission_timeout_ms, monitor_timeout_ms, num_tx_buffers, num_rx_buffers, buffer, size);
14042b70d705SMatthias Ringwald     if (result) return result;
14052b70d705SMatthias Ringwald 
1406501329faSMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
14071b9cb13dSMatthias Ringwald     if (!channel) {
14081b9cb13dSMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
14091b9cb13dSMatthias Ringwald     }
14101b9cb13dSMatthias Ringwald 
14117b181629SMatthias Ringwald     // configure ERTM
14127b181629SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_mandatory, max_transmit, retransmission_timeout_ms,
14137b181629SMatthias Ringwald         monitor_timeout_ms, num_tx_buffers, num_rx_buffers, buffer, size);
14141b9cb13dSMatthias Ringwald 
14151b9cb13dSMatthias Ringwald     // add to connections list
14161b9cb13dSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
14171b9cb13dSMatthias Ringwald 
14181b9cb13dSMatthias Ringwald     // store local_cid
14191b9cb13dSMatthias Ringwald     if (out_local_cid){
14201b9cb13dSMatthias Ringwald        *out_local_cid = channel->local_cid;
14211b9cb13dSMatthias Ringwald     }
14221b9cb13dSMatthias Ringwald 
14231b9cb13dSMatthias Ringwald     // check if hci connection is already usable
14241b9cb13dSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
14251b9cb13dSMatthias Ringwald     if (conn){
14261b9cb13dSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
14271b9cb13dSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
14281b9cb13dSMatthias Ringwald         // check if remote supported fearures are already received
14291b9cb13dSMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
14301b9cb13dSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
14311b9cb13dSMatthias Ringwald         }
14321b9cb13dSMatthias Ringwald     }
14331b9cb13dSMatthias Ringwald 
14341b9cb13dSMatthias Ringwald     l2cap_run();
14351b9cb13dSMatthias Ringwald 
14361b9cb13dSMatthias Ringwald     return 0;
14371b9cb13dSMatthias Ringwald }
14381b9cb13dSMatthias Ringwald #endif
14391b9cb13dSMatthias Ringwald 
1440ce8f182eSMatthias Ringwald void
1441ce8f182eSMatthias Ringwald l2cap_disconnect(uint16_t local_cid, uint8_t reason){
1442e0abb8e7S[email protected]     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
1443b35f641cSmatthias.ringwald     // find channel for local_cid
1444b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1445f62db1e3Smatthias.ringwald     if (channel) {
1446e7ff783cSmatthias.ringwald         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1447f62db1e3Smatthias.ringwald     }
14482cd0be45Smatthias.ringwald     // process
14492cd0be45Smatthias.ringwald     l2cap_run();
145043625864Smatthias.ringwald }
14511e6aba47Smatthias.ringwald 
1452afde0c52Smatthias.ringwald static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
1453665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1454665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1455665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1456665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1457058e3d6bSMatthias Ringwald         if ( bd_addr_cmp( channel->address, address) != 0) continue;
1458c22aecc9S[email protected]         // channel for this address found
1459c22aecc9S[email protected]         switch (channel->state){
1460c22aecc9S[email protected]             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
1461c22aecc9S[email protected]             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1462afde0c52Smatthias.ringwald                 // failure, forward error code
1463afde0c52Smatthias.ringwald                 l2cap_emit_channel_opened(channel, status);
1464afde0c52Smatthias.ringwald                 // discard channel
14659dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
1466665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1467d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
1468c22aecc9S[email protected]                 break;
1469c22aecc9S[email protected]             default:
1470c22aecc9S[email protected]                 break;
1471afde0c52Smatthias.ringwald         }
1472afde0c52Smatthias.ringwald     }
1473afde0c52Smatthias.ringwald }
1474afde0c52Smatthias.ringwald 
1475afde0c52Smatthias.ringwald static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
1476665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1477665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1478665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1479665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1480058e3d6bSMatthias Ringwald         if ( ! bd_addr_cmp( channel->address, address) ){
14812df5dadcS[email protected]             l2cap_handle_connection_complete(handle, channel);
1482afde0c52Smatthias.ringwald         }
1483afde0c52Smatthias.ringwald     }
14846fdcc387Smatthias.ringwald     // process
14856fdcc387Smatthias.ringwald     l2cap_run();
1486afde0c52Smatthias.ringwald }
148709e9d05bSMatthias Ringwald #endif
1488b448a0e7Smatthias.ringwald 
148933c40538SMatthias Ringwald static void l2cap_notify_channel_can_send(void){
149009e9d05bSMatthias Ringwald 
149109e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
149233c40538SMatthias Ringwald     btstack_linked_list_iterator_t it;
149333c40538SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
149433c40538SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
149533c40538SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
149633c40538SMatthias Ringwald         if (!channel->waiting_for_can_send_now) continue;
1497fc64f94aSMatthias Ringwald         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
149833c40538SMatthias Ringwald         channel->waiting_for_can_send_now = 0;
149934e7e577SMatthias Ringwald         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
150033c40538SMatthias Ringwald     }
150109e9d05bSMatthias Ringwald #endif
150244276248SMatthias Ringwald 
15032125de09SMatthias Ringwald     int i;
15042125de09SMatthias Ringwald     for (i=0;i<L2CAP_FIXED_CHANNEL_TABLE_SIZE;i++){
1505773c4106SMatthias Ringwald         if (!fixed_channels[i].callback) continue;
15062125de09SMatthias Ringwald         if (!fixed_channels[i].waiting_for_can_send_now) continue;
150735454696SMatthias Ringwald         int can_send = 0;
150834e7e577SMatthias Ringwald         if (l2cap_fixed_channel_table_index_is_le(i)){
150935454696SMatthias Ringwald #ifdef ENABLE_BLE
151034e7e577SMatthias Ringwald             can_send = hci_can_send_acl_le_packet_now();
151135454696SMatthias Ringwald #endif
151234e7e577SMatthias Ringwald         } else {
151335454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
151434e7e577SMatthias Ringwald             can_send = hci_can_send_acl_classic_packet_now();
151535454696SMatthias Ringwald #endif
151634e7e577SMatthias Ringwald         }
151734e7e577SMatthias Ringwald         if (!can_send) continue;
151834e7e577SMatthias Ringwald         fixed_channels[i].waiting_for_can_send_now = 0;
151934e7e577SMatthias Ringwald         l2cap_emit_can_send_now(fixed_channels[i].callback, l2cap_fixed_channel_table_channel_id_for_index(i));
15202125de09SMatthias Ringwald     }
152133c40538SMatthias Ringwald }
152233c40538SMatthias Ringwald 
1523d9a7306aSMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
1524afde0c52Smatthias.ringwald 
15259ec2630cSMatthias Ringwald     UNUSED(packet_type);
15269ec2630cSMatthias Ringwald     UNUSED(cid);
15279ec2630cSMatthias Ringwald     UNUSED(size);
15289ec2630cSMatthias Ringwald 
1529afde0c52Smatthias.ringwald     bd_addr_t address;
1530afde0c52Smatthias.ringwald     hci_con_handle_t handle;
15312d00edd4Smatthias.ringwald     int hci_con_used;
153209e9d05bSMatthias Ringwald     btstack_linked_list_iterator_t it;
153309e9d05bSMatthias Ringwald 
153409e9d05bSMatthias Ringwald     // avoid unused warnings
1535f3963406SMatthias Ringwald     UNUSED(address);
1536f3963406SMatthias Ringwald     UNUSED(hci_con_used);
1537f3963406SMatthias Ringwald     UNUSED(it);
1538f22209dfSMatthias Ringwald     UNUSED(handle);
1539afde0c52Smatthias.ringwald 
15400e2df43fSMatthias Ringwald     switch(hci_event_packet_get_type(packet)){
1541afde0c52Smatthias.ringwald 
154209e9d05bSMatthias Ringwald         // Notify channel packet handler if they can send now
154309e9d05bSMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
154409e9d05bSMatthias Ringwald         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
154509e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
154609e9d05bSMatthias Ringwald             l2cap_notify_channel_can_send();
154709e9d05bSMatthias Ringwald             break;
154809e9d05bSMatthias Ringwald 
154909e9d05bSMatthias Ringwald         case HCI_EVENT_COMMAND_STATUS:
155009e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
155109e9d05bSMatthias Ringwald             break;
155209e9d05bSMatthias Ringwald 
155309e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1554afde0c52Smatthias.ringwald         // handle connection complete events
1555afde0c52Smatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
1556724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], address);
1557afde0c52Smatthias.ringwald             if (packet[2] == 0){
1558f8fbdce0SMatthias Ringwald                 handle = little_endian_read_16(packet, 3);
1559afde0c52Smatthias.ringwald                 l2cap_handle_connection_success_for_addr(address, handle);
1560afde0c52Smatthias.ringwald             } else {
1561afde0c52Smatthias.ringwald                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
1562afde0c52Smatthias.ringwald             }
1563afde0c52Smatthias.ringwald             break;
1564afde0c52Smatthias.ringwald 
1565afde0c52Smatthias.ringwald         // handle successful create connection cancel command
1566afde0c52Smatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
1567073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
1568afde0c52Smatthias.ringwald                 if (packet[5] == 0){
1569724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[6], address);
1570afde0c52Smatthias.ringwald                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
1571afde0c52Smatthias.ringwald                     l2cap_handle_connection_failed_for_addr(address, 0x16);
157203cfbabcSmatthias.ringwald                 }
15731e6aba47Smatthias.ringwald             }
157439d59809Smatthias.ringwald             l2cap_run();    // try sending signaling packets first
157539d59809Smatthias.ringwald             break;
157609e9d05bSMatthias Ringwald #endif
157727a923d0Smatthias.ringwald 
15781e6aba47Smatthias.ringwald         // handle disconnection complete events
1579afde0c52Smatthias.ringwald         case HCI_EVENT_DISCONNECTION_COMPLETE:
1580c22aecc9S[email protected]             // send l2cap disconnect events for all channels on this handle and free them
158109e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1582d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1583665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1584665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1585665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1586fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
158715ec09bbSmatthias.ringwald                 l2cap_emit_channel_closed(channel);
15889dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
1589665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1590d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
159127a923d0Smatthias.ringwald             }
159209e9d05bSMatthias Ringwald #endif
1593a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1594d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1595991fea48SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1596991fea48SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1597991fea48SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1598991fea48SMatthias Ringwald                 if (channel->con_handle != handle) continue;
1599991fea48SMatthias Ringwald                 l2cap_emit_channel_closed(channel);
1600991fea48SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1601991fea48SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
1602991fea48SMatthias Ringwald             }
1603991fea48SMatthias Ringwald #endif
1604afde0c52Smatthias.ringwald             break;
1605fcadd0caSmatthias.ringwald 
1606ee091cf1Smatthias.ringwald         // HCI Connection Timeouts
160709e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1608afde0c52Smatthias.ringwald         case L2CAP_EVENT_TIMEOUT_CHECK:
1609f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
1610bd04d84aSMatthias Ringwald             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
161180ca58a0Smatthias.ringwald             if (hci_authentication_active_for_handle(handle)) break;
16122d00edd4Smatthias.ringwald             hci_con_used = 0;
1613665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1614665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1615665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1616fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
16172d00edd4Smatthias.ringwald                 hci_con_used = 1;
1618c22aecc9S[email protected]                 break;
1619ee091cf1Smatthias.ringwald             }
16202d00edd4Smatthias.ringwald             if (hci_con_used) break;
1621d94d3cafS[email protected]             if (!hci_can_send_command_packet_now()) break;
16229edc8742Smatthias.ringwald             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
1623afde0c52Smatthias.ringwald             break;
1624ee091cf1Smatthias.ringwald 
1625df3354fcS[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1626f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1627665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1628665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1629665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1630fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
16312df5dadcS[email protected]                 l2cap_handle_remote_supported_features_received(channel);
1632df3354fcS[email protected]                 break;
1633df3354fcS[email protected]             }
1634c22aecc9S[email protected]             break;
1635df3354fcS[email protected] 
16365611a760SMatthias Ringwald         case GAP_EVENT_SECURITY_LEVEL:
1637f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
1638bd63148eS[email protected]             log_info("l2cap - security level update");
1639665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1640665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1641665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1642fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
16435533f01eS[email protected] 
1644bd63148eS[email protected]                 log_info("l2cap - state %u", channel->state);
1645bd63148eS[email protected] 
1646e569dfd9SMatthias Ringwald                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
16475533f01eS[email protected]                 gap_security_level_t required_level = channel->required_security_level;
16485533f01eS[email protected] 
1649df3354fcS[email protected]                 switch (channel->state){
1650df3354fcS[email protected]                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
16515533f01eS[email protected]                         if (actual_level >= required_level){
165252606043SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
165352606043SMatthias Ringwald                             // we need to know if ERTM is supported before sending a config response
165452606043SMatthias Ringwald                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
165552606043SMatthias Ringwald                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
165652606043SMatthias Ringwald                             channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
165752606043SMatthias Ringwald #else
1658f85a9399S[email protected]                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
165944276248SMatthias Ringwald                             l2cap_emit_incoming_connection(channel);
166052606043SMatthias Ringwald #endif
16611eb2563eS[email protected]                         } else {
1662775ecc36SMatthias Ringwald                             channel->reason = 0x0003; // security block
16631eb2563eS[email protected]                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
16641eb2563eS[email protected]                         }
1665df3354fcS[email protected]                         break;
1666df3354fcS[email protected] 
1667df3354fcS[email protected]                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
16685533f01eS[email protected]                         if (actual_level >= required_level){
16691b9cb13dSMatthias Ringwald                             l2cap_ready_to_connect(channel);
1670df3354fcS[email protected]                         } else {
1671df3354fcS[email protected]                             // disconnnect, authentication not good enough
1672df3354fcS[email protected]                             hci_disconnect_security_block(handle);
1673df3354fcS[email protected]                         }
1674df3354fcS[email protected]                         break;
1675df3354fcS[email protected] 
1676df3354fcS[email protected]                     default:
1677df3354fcS[email protected]                         break;
1678df3354fcS[email protected]                 }
1679f85a9399S[email protected]             }
1680f85a9399S[email protected]             break;
168109e9d05bSMatthias Ringwald #endif
1682f85a9399S[email protected] 
1683afde0c52Smatthias.ringwald         default:
1684afde0c52Smatthias.ringwald             break;
1685afde0c52Smatthias.ringwald     }
1686afde0c52Smatthias.ringwald 
1687bd63148eS[email protected]     l2cap_run();
16881e6aba47Smatthias.ringwald }
16891e6aba47Smatthias.ringwald 
1690e74c5f58SMatthias 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){
16914cf56b4aSmatthias.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."
16922b360848Smatthias.ringwald     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
16932b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].handle = handle;
16942b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].code = code;
16952b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].sig_id = sig_id;
1696e74c5f58SMatthias Ringwald         signaling_responses[signaling_responses_pending].cid = cid;
16972b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].data = data;
16982b360848Smatthias.ringwald         signaling_responses_pending++;
16992b360848Smatthias.ringwald         l2cap_run();
17002b360848Smatthias.ringwald     }
17012b360848Smatthias.ringwald }
17022b360848Smatthias.ringwald 
170309e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
170409e9d05bSMatthias Ringwald static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
170509e9d05bSMatthias Ringwald     channel->remote_sig_id = identifier;
170609e9d05bSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
170709e9d05bSMatthias Ringwald     l2cap_run();
170809e9d05bSMatthias Ringwald }
170909e9d05bSMatthias Ringwald 
1710b35f641cSmatthias.ringwald static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
1711645658c9Smatthias.ringwald 
17129da54300S[email protected]     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
1713645658c9Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
1714645658c9Smatthias.ringwald     if (!service) {
1715645658c9Smatthias.ringwald         // 0x0002 PSM not supported
1716e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
1717645658c9Smatthias.ringwald         return;
1718645658c9Smatthias.ringwald     }
1719645658c9Smatthias.ringwald 
17205061f3afS[email protected]     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
1721645658c9Smatthias.ringwald     if (!hci_connection) {
17222b360848Smatthias.ringwald         //
17239da54300S[email protected]         log_error("no hci_connection for handle %u", handle);
1724645658c9Smatthias.ringwald         return;
1725645658c9Smatthias.ringwald     }
17262bd8b7e7S[email protected] 
1727645658c9Smatthias.ringwald     // alloc structure
17289da54300S[email protected]     // log_info("l2cap_handle_connection_request register channel");
1729da144af5SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, hci_connection->address, BD_ADDR_TYPE_CLASSIC,
1730da144af5SMatthias Ringwald     psm, service->mtu, service->required_security_level);
17312b360848Smatthias.ringwald     if (!channel){
17322b360848Smatthias.ringwald         // 0x0004 No resources available
1733e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
17342b360848Smatthias.ringwald         return;
17352b360848Smatthias.ringwald     }
1736da144af5SMatthias Ringwald 
1737fc64f94aSMatthias Ringwald     channel->con_handle = handle;
1738b35f641cSmatthias.ringwald     channel->remote_cid = source_cid;
1739b1988dceSmatthias.ringwald     channel->remote_sig_id = sig_id;
1740645658c9Smatthias.ringwald 
1741f53da564S[email protected]     // limit local mtu to max acl packet length - l2cap header
17422985cb84Smatthias.ringwald     if (channel->local_mtu > l2cap_max_mtu()) {
17432985cb84Smatthias.ringwald         channel->local_mtu = l2cap_max_mtu();
17449775e25bSmatthias.ringwald     }
17459775e25bSmatthias.ringwald 
1746645658c9Smatthias.ringwald     // set initial state
1747df3354fcS[email protected]     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
1748a24785d0SMatthias Ringwald     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
1749e405ae81Smatthias.ringwald 
1750645658c9Smatthias.ringwald     // add to connections list
1751665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1752645658c9Smatthias.ringwald 
1753f85a9399S[email protected]     // assert security requirements
17541eb2563eS[email protected]     gap_request_security_level(handle, channel->required_security_level);
1755e405ae81Smatthias.ringwald }
1756645658c9Smatthias.ringwald 
1757ce8f182eSMatthias Ringwald void l2cap_accept_connection(uint16_t local_cid){
1758e0abb8e7S[email protected]     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
1759b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1760e405ae81Smatthias.ringwald     if (!channel) {
1761ce8f182eSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
1762e405ae81Smatthias.ringwald         return;
1763e405ae81Smatthias.ringwald     }
1764e405ae81Smatthias.ringwald 
176543ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
176643ec931dSMatthias Ringwald     // configure L2CAP Basic mode
176743ec931dSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
176843ec931dSMatthias Ringwald #endif
176943ec931dSMatthias Ringwald 
1770552d92a1Smatthias.ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
1771e405ae81Smatthias.ringwald 
1772552d92a1Smatthias.ringwald     // process
1773552d92a1Smatthias.ringwald     l2cap_run();
1774e405ae81Smatthias.ringwald }
1775645658c9Smatthias.ringwald 
177643ec931dSMatthias Ringwald 
177743ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
17782b70d705SMatthias Ringwald uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, int ertm_mandatory, uint8_t max_transmit,
1779501329faSMatthias Ringwald     uint16_t retransmission_timeout_ms, uint16_t monitor_timeout_ms, uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size){
1780501329faSMatthias Ringwald 
178143ec931dSMatthias Ringwald     log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
178243ec931dSMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
178343ec931dSMatthias Ringwald     if (!channel) {
178443ec931dSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
17852b70d705SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
178643ec931dSMatthias Ringwald     }
178743ec931dSMatthias Ringwald 
17882b70d705SMatthias Ringwald     // validate local config
17892b70d705SMatthias Ringwald     uint8_t result = l2cap_ertm_validate_local_config(max_transmit, retransmission_timeout_ms, monitor_timeout_ms, num_tx_buffers, num_rx_buffers, buffer, size);
17902b70d705SMatthias Ringwald     if (result) return result;
17912b70d705SMatthias Ringwald 
179243ec931dSMatthias Ringwald     // configure L2CAP ERTM
17937b181629SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_mandatory, max_transmit, retransmission_timeout_ms, monitor_timeout_ms, num_tx_buffers, num_rx_buffers, buffer, size);
179443ec931dSMatthias Ringwald 
17957b181629SMatthias Ringwald     // continue
179643ec931dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
179743ec931dSMatthias Ringwald 
179843ec931dSMatthias Ringwald     // process
179943ec931dSMatthias Ringwald     l2cap_run();
18002b70d705SMatthias Ringwald 
18012b70d705SMatthias Ringwald     return ERROR_CODE_SUCCESS;
180243ec931dSMatthias Ringwald }
18032a424812SMatthias Ringwald 
180467a3a5b7SMatthias Ringwald uint8_t l2cap_ertm_set_busy(uint16_t local_cid){
18058f1c9639SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
18068f1c9639SMatthias Ringwald     if (!channel) {
18078f1c9639SMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
18088f1c9639SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
18098f1c9639SMatthias Ringwald     }
18108f1c9639SMatthias Ringwald     channel->send_supervisor_frame_receiver_not_ready = 1;
18118f1c9639SMatthias Ringwald     l2cap_run();
181267a3a5b7SMatthias Ringwald     return ERROR_CODE_SUCCESS;
181367a3a5b7SMatthias Ringwald }
181467a3a5b7SMatthias Ringwald 
181567a3a5b7SMatthias Ringwald uint8_t l2cap_ertm_set_ready(uint16_t local_cid){
181667a3a5b7SMatthias Ringwald     return ERROR_CODE_SUCCESS;
181767a3a5b7SMatthias Ringwald     UNUSED(local_cid);
181867a3a5b7SMatthias Ringwald }
181967a3a5b7SMatthias Ringwald 
18202a424812SMatthias Ringwald static void l2cap_ertm_handle_req_seq(l2cap_channel_t * l2cap_channel, uint8_t req_seq){
18212a424812SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
18222a424812SMatthias Ringwald     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
18232a424812SMatthias Ringwald     if ( ((req_seq - 1) & 0x3f) == tx_state->tx_seq){
18242a424812SMatthias Ringwald         log_info("RR seq %u == seq of oldest tx packet -> packet done", req_seq);
182562041d70SMatthias Ringwald         // stop retransmission timer
182662041d70SMatthias Ringwald         btstack_run_loop_remove_timer(&tx_state->retransmission_timer);
18272a424812SMatthias Ringwald         l2cap_channel->tx_read_index++;
18282a424812SMatthias Ringwald         if (l2cap_channel->tx_read_index >= l2cap_channel->num_rx_buffers){
18292a424812SMatthias Ringwald             l2cap_channel->tx_read_index = 0;
18302a424812SMatthias Ringwald         }
18312a424812SMatthias Ringwald     } else {
18322a424812SMatthias Ringwald         log_info("RR seq %u != seq of oldest tx packet %u ???", req_seq, tx_state->tx_seq);
18332a424812SMatthias Ringwald     }
18342a424812SMatthias Ringwald }
183567a3a5b7SMatthias Ringwald 
1836*7b7901d8SMatthias Ringwald static l2cap_ertm_tx_packet_state_t * l2cap_ertm_get_tx_state(l2cap_channel_t * l2cap_channel, uint8_t tx_seq){
1837*7b7901d8SMatthias Ringwald     int i;
1838*7b7901d8SMatthias Ringwald     for (i=0;i<l2cap_channel->num_tx_buffers;i++){
1839*7b7901d8SMatthias Ringwald         l2cap_ertm_tx_packet_state_t * tx_state = &l2cap_channel->tx_packets_state[i];
1840*7b7901d8SMatthias Ringwald         if (tx_state->tx_seq == tx_seq) return tx_state;
1841*7b7901d8SMatthias Ringwald     }
1842*7b7901d8SMatthias Ringwald     return NULL;
1843*7b7901d8SMatthias Ringwald }
184443ec931dSMatthias Ringwald #endif
184543ec931dSMatthias Ringwald 
184643ec931dSMatthias Ringwald 
18477ef6a7bbSMatthias Ringwald void l2cap_decline_connection(uint16_t local_cid){
18487ef6a7bbSMatthias Ringwald     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
1849b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
1850e405ae81Smatthias.ringwald     if (!channel) {
1851ce8f182eSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
1852e405ae81Smatthias.ringwald         return;
1853e405ae81Smatthias.ringwald     }
1854e7ff783cSmatthias.ringwald     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
18557ef6a7bbSMatthias Ringwald     channel->reason = 0x04; // no resources available
1856e7ff783cSmatthias.ringwald     l2cap_run();
1857645658c9Smatthias.ringwald }
1858645658c9Smatthias.ringwald 
18597f02f414SMatthias Ringwald static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
1860b1988dceSmatthias.ringwald 
1861b1988dceSmatthias.ringwald     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1862b1988dceSmatthias.ringwald 
1863f8fbdce0SMatthias Ringwald     uint16_t flags = little_endian_read_16(command, 6);
186463a7246aSmatthias.ringwald     if (flags & 1) {
186563a7246aSmatthias.ringwald         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
186663a7246aSmatthias.ringwald     }
186763a7246aSmatthias.ringwald 
18682784b77dSmatthias.ringwald     // accept the other's configuration options
1869f8fbdce0SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
18703de7c0caSmatthias.ringwald     uint16_t pos     = 8;
18713de7c0caSmatthias.ringwald     while (pos < end_pos){
187263a7246aSmatthias.ringwald         uint8_t option_hint = command[pos] >> 7;
187363a7246aSmatthias.ringwald         uint8_t option_type = command[pos] & 0x7f;
187463a7246aSmatthias.ringwald         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
187563a7246aSmatthias.ringwald         pos++;
18761dc511deSmatthias.ringwald         uint8_t length = command[pos++];
18771dc511deSmatthias.ringwald         // MTU { type(8): 1, len(8):2, MTU(16) }
187863a7246aSmatthias.ringwald         if (option_type == 1 && length == 2){
1879f8fbdce0SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, pos);
18809d139fbaSMatthias Ringwald             if (channel->remote_mtu > l2cap_max_mtu()){
18819d139fbaSMatthias Ringwald                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
18829d139fbaSMatthias Ringwald                 channel->remote_mtu = l2cap_max_mtu();
18839d139fbaSMatthias Ringwald             }
188463a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
188563a7246aSmatthias.ringwald         }
18860fe7a9d0S[email protected]         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
18870fe7a9d0S[email protected]         if (option_type == 2 && length == 2){
1888f8fbdce0SMatthias Ringwald             channel->flush_timeout = little_endian_read_16(command, pos);
18890fe7a9d0S[email protected]         }
1890f2fa388dSMatthias Ringwald 
18916dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
18926dca2a0cSMatthias Ringwald         // Retransmission and Flow Control Option
18936dca2a0cSMatthias Ringwald         if (option_type == 4 && length == 9){
18943232a1c6SMatthias Ringwald             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
1895ac8f1300SMatthias Ringwald             switch(channel->mode){
1896ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
189725cd60d3SMatthias Ringwald                     // Store remote config
1898bbc0a9e7SMatthias Ringwald                     channel->remote_tx_window_size = command[pos+1];
1899bbc0a9e7SMatthias Ringwald                     channel->remote_max_transmit   = command[pos+2];
1900bbc0a9e7SMatthias Ringwald                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
1901bbc0a9e7SMatthias Ringwald                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
1902bbc0a9e7SMatthias Ringwald                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u",
1903bbc0a9e7SMatthias Ringwald                         channel->remote_tx_window_size,
1904bbc0a9e7SMatthias Ringwald                         channel->remote_max_transmit,
1905bbc0a9e7SMatthias Ringwald                         channel->remote_retransmission_timeout_ms,
1906bbc0a9e7SMatthias Ringwald                         channel->remote_monitor_timeout_ms);
1907bbc0a9e7SMatthias Ringwald                     // we store remote MPS in remote_mtu, might need to get re-evaluated
1908bbc0a9e7SMatthias Ringwald                     channel->remote_mtu = little_endian_read_16(command, pos + 7);
190925cd60d3SMatthias Ringwald                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
191025cd60d3SMatthias Ringwald                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
191125cd60d3SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1912ac8f1300SMatthias Ringwald                     } else {
1913ac8f1300SMatthias Ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1914ac8f1300SMatthias Ringwald                     }
1915ac8f1300SMatthias Ringwald                     break;
1916ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
1917ac8f1300SMatthias Ringwald                     switch (mode){
1918ac8f1300SMatthias Ringwald                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
1919ac8f1300SMatthias Ringwald                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
1920ac8f1300SMatthias Ringwald                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
1921ac8f1300SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1922ac8f1300SMatthias Ringwald                             }
1923ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
1924ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1925ac8f1300SMatthias Ringwald                             break;
1926ac8f1300SMatthias Ringwald                         default: // case L2CAP_CHANNEL_MODE_BASIC:
1927ac8f1300SMatthias Ringwald                             // TODO store and evaluate configuration
1928ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1929ac8f1300SMatthias Ringwald                             break;
1930ac8f1300SMatthias Ringwald                     }
1931ac8f1300SMatthias Ringwald                     break;
1932ac8f1300SMatthias Ringwald                 default:
1933ac8f1300SMatthias Ringwald                     break;
1934ac8f1300SMatthias Ringwald             }
19353232a1c6SMatthias Ringwald         }
19366dca2a0cSMatthias Ringwald #endif
193763a7246aSmatthias.ringwald         // check for unknown options
193863a7246aSmatthias.ringwald         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
1939c177a91cS[email protected]             log_info("l2cap cid %u, unknown options", channel->local_cid);
194063a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
19411dc511deSmatthias.ringwald         }
19421dc511deSmatthias.ringwald         pos += length;
19431dc511deSmatthias.ringwald     }
19442784b77dSmatthias.ringwald }
19452784b77dSmatthias.ringwald 
1946f2fa388dSMatthias Ringwald static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
1947f2fa388dSMatthias Ringwald     log_info("l2cap_signaling_handle_configure_response");
19483232a1c6SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
19493232a1c6SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1950f2fa388dSMatthias Ringwald     uint16_t pos     = 10;
19513232a1c6SMatthias Ringwald     while (pos < end_pos){
19523232a1c6SMatthias Ringwald         uint8_t option_hint = command[pos] >> 7;
19533232a1c6SMatthias Ringwald         uint8_t option_type = command[pos] & 0x7f;
19543232a1c6SMatthias Ringwald         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
19553232a1c6SMatthias Ringwald         pos++;
19563232a1c6SMatthias Ringwald         uint8_t length = command[pos++];
19573232a1c6SMatthias Ringwald 
19583232a1c6SMatthias Ringwald         // Retransmission and Flow Control Option
19593232a1c6SMatthias Ringwald         if (option_type == 4 && length == 9){
1960ac8f1300SMatthias Ringwald             switch (channel->mode){
1961ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
1962f2fa388dSMatthias Ringwald                     if (channel->ertm_mandatory){
1963ac8f1300SMatthias Ringwald                         // ??
1964f2fa388dSMatthias Ringwald                     } else {
1965ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
1966ac8f1300SMatthias Ringwald                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
1967f2fa388dSMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
19683232a1c6SMatthias Ringwald                         }
19693232a1c6SMatthias Ringwald                     }
1970ac8f1300SMatthias Ringwald                     break;
1971ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
1972ac8f1300SMatthias Ringwald                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
1973ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
1974ac8f1300SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1975ac8f1300SMatthias Ringwald                     }
1976ac8f1300SMatthias Ringwald                     break;
1977ac8f1300SMatthias Ringwald                 default:
1978ac8f1300SMatthias Ringwald                     break;
19793232a1c6SMatthias Ringwald             }
1980f2fa388dSMatthias Ringwald         }
19813232a1c6SMatthias Ringwald 
19823232a1c6SMatthias Ringwald         // check for unknown options
19833232a1c6SMatthias Ringwald         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
19843232a1c6SMatthias Ringwald             log_info("l2cap cid %u, unknown options", channel->local_cid);
19853232a1c6SMatthias Ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
19863232a1c6SMatthias Ringwald         }
19873232a1c6SMatthias Ringwald 
19883232a1c6SMatthias Ringwald         pos += length;
19893232a1c6SMatthias Ringwald     }
19903232a1c6SMatthias Ringwald #endif
19913232a1c6SMatthias Ringwald }
19923232a1c6SMatthias Ringwald 
1993fa8473a4Smatthias.ringwald static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
19949da54300S[email protected]     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
199573cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
199673cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
1997019f9b43SMatthias Ringwald     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
1998019f9b43SMatthias Ringwald     if (channel->state == L2CAP_STATE_OPEN) return 0;
1999fa8473a4Smatthias.ringwald     return 1;
2000fa8473a4Smatthias.ringwald }
2001fa8473a4Smatthias.ringwald 
2002fa8473a4Smatthias.ringwald 
20037f02f414SMatthias Ringwald static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
20041e6aba47Smatthias.ringwald 
200500d93d79Smatthias.ringwald     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
200600d93d79Smatthias.ringwald     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
200738e5900eSmatthias.ringwald     uint16_t result = 0;
20081e6aba47Smatthias.ringwald 
20099da54300S[email protected]     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
2010b35f641cSmatthias.ringwald 
20119a011532Smatthias.ringwald     // handle DISCONNECT REQUESTS seperately
20129a011532Smatthias.ringwald     if (code == DISCONNECTION_REQUEST){
20139a011532Smatthias.ringwald         switch (channel->state){
2014fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
20159a011532Smatthias.ringwald             case L2CAP_STATE_OPEN:
20162b83fb7dSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
20179a011532Smatthias.ringwald             case L2CAP_STATE_WAIT_DISCONNECT:
20189a011532Smatthias.ringwald                 l2cap_handle_disconnect_request(channel, identifier);
20199a011532Smatthias.ringwald                 break;
20209a011532Smatthias.ringwald 
20219a011532Smatthias.ringwald             default:
20229a011532Smatthias.ringwald                 // ignore in other states
20239a011532Smatthias.ringwald                 break;
20249a011532Smatthias.ringwald         }
20259a011532Smatthias.ringwald         return;
20269a011532Smatthias.ringwald     }
20279a011532Smatthias.ringwald 
202856081214Smatthias.ringwald     // @STATEMACHINE(l2cap)
20291e6aba47Smatthias.ringwald     switch (channel->state) {
20301e6aba47Smatthias.ringwald 
20311e6aba47Smatthias.ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
20321e6aba47Smatthias.ringwald             switch (code){
20331e6aba47Smatthias.ringwald                 case CONNECTION_RESPONSE:
20345932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2035f8fbdce0SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
203638e5900eSmatthias.ringwald                     switch (result) {
203738e5900eSmatthias.ringwald                         case 0:
2038169f8b28Smatthias.ringwald                             // successful connection
2039f8fbdce0SMatthias Ringwald                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2040fa8473a4Smatthias.ringwald                             channel->state = L2CAP_STATE_CONFIG;
204128ca2b46S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
204238e5900eSmatthias.ringwald                             break;
204338e5900eSmatthias.ringwald                         case 1:
20445932bd7cS[email protected]                             // connection pending. get some coffee, but start the ERTX
20455932bd7cS[email protected]                             l2cap_start_ertx(channel);
204638e5900eSmatthias.ringwald                             break;
204738e5900eSmatthias.ringwald                         default:
2048eb920dbeSmatthias.ringwald                             // channel closed
2049eb920dbeSmatthias.ringwald                             channel->state = L2CAP_STATE_CLOSED;
2050f32b992eSmatthias.ringwald                             // map l2cap connection response result to BTstack status enumeration
205138e5900eSmatthias.ringwald                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
2052eb920dbeSmatthias.ringwald 
2053eb920dbeSmatthias.ringwald                             // drop link key if security block
2054eb920dbeSmatthias.ringwald                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
205515a95bd5SMatthias Ringwald                                 gap_drop_link_key_for_bd_addr(channel->address);
2056eb920dbeSmatthias.ringwald                             }
2057eb920dbeSmatthias.ringwald 
2058eb920dbeSmatthias.ringwald                             // discard channel
2059665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2060d3a9df87Smatthias.ringwald                             btstack_memory_l2cap_channel_free(channel);
206138e5900eSmatthias.ringwald                             break;
20621e6aba47Smatthias.ringwald                     }
20631e6aba47Smatthias.ringwald                     break;
206438e5900eSmatthias.ringwald 
206538e5900eSmatthias.ringwald                 default:
20661e6aba47Smatthias.ringwald                     //@TODO: implement other signaling packets
206738e5900eSmatthias.ringwald                     break;
20681e6aba47Smatthias.ringwald             }
20691e6aba47Smatthias.ringwald             break;
20701e6aba47Smatthias.ringwald 
2071fa8473a4Smatthias.ringwald         case L2CAP_STATE_CONFIG:
2072f8fbdce0SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2073ae280e73Smatthias.ringwald             switch (code) {
2074ae280e73Smatthias.ringwald                 case CONFIGURE_REQUEST:
207528ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
2076ae280e73Smatthias.ringwald                     l2cap_signaling_handle_configure_request(channel, command);
207763a7246aSmatthias.ringwald                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
207863a7246aSmatthias.ringwald                         // only done if continuation not set
207963a7246aSmatthias.ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
208063a7246aSmatthias.ringwald                     }
2081ae280e73Smatthias.ringwald                     break;
20821e6aba47Smatthias.ringwald                 case CONFIGURE_RESPONSE:
20835932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2084f2fa388dSMatthias Ringwald                     l2cap_signaling_handle_configure_response(channel, result, command);
20855932bd7cS[email protected]                     switch (result){
20865932bd7cS[email protected]                         case 0: // success
20875932bd7cS[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
20885932bd7cS[email protected]                             break;
20895932bd7cS[email protected]                         case 4: // pending
20905932bd7cS[email protected]                             l2cap_start_ertx(channel);
20915932bd7cS[email protected]                             break;
20925932bd7cS[email protected]                         default:
2093a32d6a03SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2094a32d6a03SMatthias Ringwald                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
2095a32d6a03SMatthias Ringwald                                 // remote does not offer ertm but it's required
2096a32d6a03SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2097a32d6a03SMatthias Ringwald                                 break;
2098a32d6a03SMatthias Ringwald                             }
2099a32d6a03SMatthias Ringwald #endif
2100fe9d8984S[email protected]                             // retry on negative result
2101fe9d8984S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2102fe9d8984S[email protected]                             break;
2103fe9d8984S[email protected]                     }
21045a67bd4aSmatthias.ringwald                     break;
21055a67bd4aSmatthias.ringwald                 default:
21065a67bd4aSmatthias.ringwald                     break;
21071e6aba47Smatthias.ringwald             }
2108fa8473a4Smatthias.ringwald             if (l2cap_channel_ready_for_open(channel)){
2109fa8473a4Smatthias.ringwald                 // for open:
21105a67bd4aSmatthias.ringwald                 channel->state = L2CAP_STATE_OPEN;
2111fa8473a4Smatthias.ringwald                 l2cap_emit_channel_opened(channel, 0);
2112c8e4258aSmatthias.ringwald             }
2113c8e4258aSmatthias.ringwald             break;
2114f62db1e3Smatthias.ringwald 
2115f62db1e3Smatthias.ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
2116f62db1e3Smatthias.ringwald             switch (code) {
2117f62db1e3Smatthias.ringwald                 case DISCONNECTION_RESPONSE:
211827a923d0Smatthias.ringwald                     l2cap_finialize_channel_close(channel);
211927a923d0Smatthias.ringwald                     break;
21205a67bd4aSmatthias.ringwald                 default:
21215a67bd4aSmatthias.ringwald                     //@TODO: implement other signaling packets
21225a67bd4aSmatthias.ringwald                     break;
212327a923d0Smatthias.ringwald             }
212427a923d0Smatthias.ringwald             break;
212584836b65Smatthias.ringwald 
212684836b65Smatthias.ringwald         case L2CAP_STATE_CLOSED:
212784836b65Smatthias.ringwald             // @TODO handle incoming requests
212884836b65Smatthias.ringwald             break;
212984836b65Smatthias.ringwald 
213084836b65Smatthias.ringwald         case L2CAP_STATE_OPEN:
213184836b65Smatthias.ringwald             //@TODO: implement other signaling packets, e.g. re-configure
213284836b65Smatthias.ringwald             break;
213310642e45Smatthias.ringwald         default:
213410642e45Smatthias.ringwald             break;
213527a923d0Smatthias.ringwald     }
21369da54300S[email protected]     // log_info("new state %u", channel->state);
213727a923d0Smatthias.ringwald }
213827a923d0Smatthias.ringwald 
213900d93d79Smatthias.ringwald 
21407f02f414SMatthias Ringwald static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
214100d93d79Smatthias.ringwald 
21421b9cb13dSMatthias Ringwald     btstack_linked_list_iterator_t it;
21431b9cb13dSMatthias Ringwald 
214400d93d79Smatthias.ringwald     // get code, signalind identifier and command len
214500d93d79Smatthias.ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
214600d93d79Smatthias.ringwald     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
214700d93d79Smatthias.ringwald 
21481b9cb13dSMatthias Ringwald     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
21491b9cb13dSMatthias Ringwald     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_RESPONSE){
2150e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
215100d93d79Smatthias.ringwald         return;
215200d93d79Smatthias.ringwald     }
215300d93d79Smatthias.ringwald 
215400d93d79Smatthias.ringwald     // general commands without an assigned channel
215500d93d79Smatthias.ringwald     switch(code) {
215600d93d79Smatthias.ringwald 
215700d93d79Smatthias.ringwald         case CONNECTION_REQUEST: {
2158f8fbdce0SMatthias Ringwald             uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2159f8fbdce0SMatthias Ringwald             uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
216000d93d79Smatthias.ringwald             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
21612b83fb7dSmatthias.ringwald             return;
216200d93d79Smatthias.ringwald         }
216300d93d79Smatthias.ringwald 
21642b360848Smatthias.ringwald         case ECHO_REQUEST:
2165e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
21662b83fb7dSmatthias.ringwald             return;
216700d93d79Smatthias.ringwald 
216800d93d79Smatthias.ringwald         case INFORMATION_REQUEST: {
2169f8fbdce0SMatthias Ringwald             uint16_t infoType = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2170e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, infoType);
21712b83fb7dSmatthias.ringwald             return;
217200d93d79Smatthias.ringwald         }
217300d93d79Smatthias.ringwald 
21741b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
21751b9cb13dSMatthias Ringwald         case INFORMATION_RESPONSE: {
21761b9cb13dSMatthias Ringwald             hci_connection_t * connection = hci_connection_for_handle(handle);
21771b9cb13dSMatthias Ringwald             if (!connection) return;
21781b9cb13dSMatthias Ringwald             uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
21791b9cb13dSMatthias Ringwald             uint16_t result =  little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
21801b9cb13dSMatthias Ringwald             if (result != 0) return;
2181543b84e4SMatthias Ringwald             if (info_type != 0x02) return;
21821b9cb13dSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
21831b9cb13dSMatthias Ringwald             connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2184543b84e4SMatthias Ringwald             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
21851b9cb13dSMatthias Ringwald             // trigger connection request
21861b9cb13dSMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
21871b9cb13dSMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
21881b9cb13dSMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2189543b84e4SMatthias Ringwald                 if (channel->con_handle != handle) continue;
2190543b84e4SMatthias Ringwald                 // bail if ERTM was requested but is not supported
2191543b84e4SMatthias Ringwald                 if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2192f073f086SMatthias Ringwald                     if (channel->ertm_mandatory){
2193543b84e4SMatthias Ringwald                         // channel closed
2194543b84e4SMatthias Ringwald                         channel->state = L2CAP_STATE_CLOSED;
2195543b84e4SMatthias Ringwald                         // map l2cap connection response result to BTstack status enumeration
2196543b84e4SMatthias Ringwald                         l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTD);
2197543b84e4SMatthias Ringwald                         // discard channel
2198543b84e4SMatthias Ringwald                         btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2199543b84e4SMatthias Ringwald                         btstack_memory_l2cap_channel_free(channel);
2200543b84e4SMatthias Ringwald                         continue;
2201f073f086SMatthias Ringwald                     } else {
2202f073f086SMatthias Ringwald                         // fallback to Basic mode
2203f073f086SMatthias Ringwald                         channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2204f073f086SMatthias Ringwald                     }
2205543b84e4SMatthias Ringwald                 }
2206543b84e4SMatthias Ringwald                 // start connecting
22071b9cb13dSMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
22081b9cb13dSMatthias Ringwald                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
22091b9cb13dSMatthias Ringwald                 }
221052606043SMatthias Ringwald                 // respond to connection request
221152606043SMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
221252606043SMatthias Ringwald                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
221352606043SMatthias Ringwald                     l2cap_emit_incoming_connection(channel);
221452606043SMatthias Ringwald                 }
22151b9cb13dSMatthias Ringwald             }
22161b9cb13dSMatthias Ringwald             return;
22171b9cb13dSMatthias Ringwald         }
22181b9cb13dSMatthias Ringwald #endif
22191b9cb13dSMatthias Ringwald 
222000d93d79Smatthias.ringwald         default:
222100d93d79Smatthias.ringwald             break;
222200d93d79Smatthias.ringwald     }
222300d93d79Smatthias.ringwald 
222400d93d79Smatthias.ringwald 
222500d93d79Smatthias.ringwald     // Get potential destination CID
2226f8fbdce0SMatthias Ringwald     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
222700d93d79Smatthias.ringwald 
222800d93d79Smatthias.ringwald     // Find channel for this sig_id and connection handle
2229665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2230665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2231665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2232fc64f94aSMatthias Ringwald         if (channel->con_handle != handle) continue;
223300d93d79Smatthias.ringwald         if (code & 1) {
2234b1988dceSmatthias.ringwald             // match odd commands (responses) by previous signaling identifier
2235b1988dceSmatthias.ringwald             if (channel->local_sig_id == sig_id) {
223600d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
22374e32727eSmatthias.ringwald                 break;
223800d93d79Smatthias.ringwald             }
223900d93d79Smatthias.ringwald         } else {
2240b1988dceSmatthias.ringwald             // match even commands (requests) by local channel id
224100d93d79Smatthias.ringwald             if (channel->local_cid == dest_cid) {
224200d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
22434e32727eSmatthias.ringwald                 break;
224400d93d79Smatthias.ringwald             }
224500d93d79Smatthias.ringwald         }
224600d93d79Smatthias.ringwald     }
224700d93d79Smatthias.ringwald }
224809e9d05bSMatthias Ringwald #endif
224900d93d79Smatthias.ringwald 
2250e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
225109e9d05bSMatthias Ringwald 
225209e9d05bSMatthias Ringwald static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
225309e9d05bSMatthias Ringwald     uint8_t event[6];
225409e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
225509e9d05bSMatthias Ringwald     event[1] = 4;
225609e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
225709e9d05bSMatthias Ringwald     little_endian_store_16(event, 4, result);
225809e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
225909e9d05bSMatthias Ringwald     if (!l2cap_event_packet_handler) return;
226009e9d05bSMatthias Ringwald     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
226109e9d05bSMatthias Ringwald }
226209e9d05bSMatthias Ringwald 
2263c48b2a2cSMatthias Ringwald // @returns valid
2264c48b2a2cSMatthias Ringwald static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
2265e7d0c9aaSMatthias Ringwald     hci_connection_t * connection;
2266c48b2a2cSMatthias Ringwald     uint16_t result;
2267c48b2a2cSMatthias Ringwald     uint8_t  event[10];
226883fd9c76SMatthias Ringwald 
2269cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2270a3dc965aSMatthias Ringwald     btstack_linked_list_iterator_t it;
2271a3dc965aSMatthias Ringwald     l2cap_channel_t * channel;
2272a3dc965aSMatthias Ringwald     uint16_t local_cid;
227383fd9c76SMatthias Ringwald     uint16_t le_psm;
227463f0ac45SMatthias Ringwald     uint16_t new_credits;
227563f0ac45SMatthias Ringwald     uint16_t credits_before;
2276e7d0c9aaSMatthias Ringwald     l2cap_service_t * service;
227711cae19eSMilanka Ringwald     uint16_t source_cid;
227883fd9c76SMatthias Ringwald #endif
227900d93d79Smatthias.ringwald 
22801b8b8d05SMatthias Ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
228123017473SMatthias Ringwald     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u", code, sig_id);
22821b8b8d05SMatthias Ringwald 
22831b8b8d05SMatthias Ringwald     switch (code){
228400d93d79Smatthias.ringwald 
2285c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
2286c48b2a2cSMatthias Ringwald             result = little_endian_read_16(command, 4);
2287ccf076adS[email protected]             l2cap_emit_connection_parameter_update_response(handle, result);
2288ccf076adS[email protected]             break;
2289da886c03S[email protected] 
2290c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_REQUEST:
2291e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
2292da886c03S[email protected]             if (connection){
22936d91fb6cSMatthias Ringwald                 if (connection->role != HCI_ROLE_MASTER){
22946d91fb6cSMatthias Ringwald                     // reject command without notifying upper layer when not in master role
2295c48b2a2cSMatthias Ringwald                     return 0;
22966d91fb6cSMatthias Ringwald                 }
2297da886c03S[email protected]                 int update_parameter = 1;
2298a4c06b28SMatthias Ringwald                 le_connection_parameter_range_t existing_range;
22994ced4e8cSMatthias Ringwald                 gap_get_connection_parameter_range(&existing_range);
2300c48b2a2cSMatthias Ringwald                 uint16_t le_conn_interval_min = little_endian_read_16(command,8);
2301c48b2a2cSMatthias Ringwald                 uint16_t le_conn_interval_max = little_endian_read_16(command,10);
2302c48b2a2cSMatthias Ringwald                 uint16_t le_conn_latency = little_endian_read_16(command,12);
2303c48b2a2cSMatthias Ringwald                 uint16_t le_supervision_timeout = little_endian_read_16(command,14);
2304da886c03S[email protected] 
2305da886c03S[email protected]                 if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
2306da886c03S[email protected]                 if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
2307da886c03S[email protected] 
2308da886c03S[email protected]                 if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
2309da886c03S[email protected]                 if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
2310da886c03S[email protected] 
2311da886c03S[email protected]                 if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
2312da886c03S[email protected]                 if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
2313da886c03S[email protected] 
2314da886c03S[email protected]                 if (update_parameter){
2315da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
2316da886c03S[email protected]                     connection->le_conn_interval_min = le_conn_interval_min;
2317da886c03S[email protected]                     connection->le_conn_interval_max = le_conn_interval_max;
2318da886c03S[email protected]                     connection->le_conn_latency = le_conn_latency;
2319da886c03S[email protected]                     connection->le_supervision_timeout = le_supervision_timeout;
2320da886c03S[email protected]                 } else {
2321da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
2322da886c03S[email protected]                 }
2323c48b2a2cSMatthias Ringwald                 connection->le_con_param_update_identifier = sig_id;
2324da886c03S[email protected]             }
2325da886c03S[email protected] 
232633c40538SMatthias Ringwald             if (!l2cap_event_packet_handler) break;
2327c48b2a2cSMatthias Ringwald 
2328c48b2a2cSMatthias Ringwald             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
2329c48b2a2cSMatthias Ringwald             event[1] = 8;
2330c48b2a2cSMatthias Ringwald             memcpy(&event[2], &command[4], 8);
2331c48b2a2cSMatthias Ringwald             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
233233c40538SMatthias Ringwald             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
2333ccf076adS[email protected]             break;
2334c48b2a2cSMatthias Ringwald 
2335a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2336a3dc965aSMatthias Ringwald 
233763f0ac45SMatthias Ringwald         case COMMAND_REJECT:
233863f0ac45SMatthias Ringwald             // Find channel for this sig_id and connection handle
233963f0ac45SMatthias Ringwald             channel = NULL;
234063f0ac45SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
234163f0ac45SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
234263f0ac45SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
234363f0ac45SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
234463f0ac45SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
234563f0ac45SMatthias Ringwald                 channel = a_channel;
234663f0ac45SMatthias Ringwald                 break;
234763f0ac45SMatthias Ringwald             }
234863f0ac45SMatthias Ringwald             if (!channel) break;
234963f0ac45SMatthias Ringwald 
235063f0ac45SMatthias Ringwald             // if received while waiting for le connection response, assume legacy device
235163f0ac45SMatthias Ringwald             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
235263f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
235363f0ac45SMatthias Ringwald                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
235444276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0x0002);
235563f0ac45SMatthias Ringwald 
235663f0ac45SMatthias Ringwald                 // discard channel
235763f0ac45SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
235863f0ac45SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
235963f0ac45SMatthias Ringwald                 break;
236063f0ac45SMatthias Ringwald             }
236163f0ac45SMatthias Ringwald             break;
236263f0ac45SMatthias Ringwald 
2363e7d0c9aaSMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_REQUEST:
2364e7d0c9aaSMatthias Ringwald 
2365e7d0c9aaSMatthias Ringwald             // get hci connection, bail if not found (must not happen)
2366e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
2367e7d0c9aaSMatthias Ringwald             if (!connection) return 0;
2368e7d0c9aaSMatthias Ringwald 
2369e7d0c9aaSMatthias Ringwald             // check if service registered
2370e7d0c9aaSMatthias Ringwald             le_psm  = little_endian_read_16(command, 4);
2371e7d0c9aaSMatthias Ringwald             service = l2cap_le_get_service(le_psm);
237211cae19eSMilanka Ringwald             source_cid = little_endian_read_16(command, 6);
2373e7d0c9aaSMatthias Ringwald 
2374e7d0c9aaSMatthias Ringwald             if (service){
2375e7d0c9aaSMatthias Ringwald                 if (source_cid < 0x40){
2376e7d0c9aaSMatthias Ringwald                     // 0x0009 Connection refused - Invalid Source CID
2377e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
2378e7d0c9aaSMatthias Ringwald                     return 1;
2379e7d0c9aaSMatthias Ringwald                 }
2380e7d0c9aaSMatthias Ringwald 
2381e7d0c9aaSMatthias Ringwald                 // go through list of channels for this ACL connection and check if we get a match
2382e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2383e7d0c9aaSMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&it)){
23841b8b8d05SMatthias Ringwald                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
23851b8b8d05SMatthias Ringwald                     if (a_channel->con_handle != handle) continue;
23861b8b8d05SMatthias Ringwald                     if (a_channel->remote_cid != source_cid) continue;
2387e7d0c9aaSMatthias Ringwald                     // 0x000a Connection refused - Source CID already allocated
2388e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
2389e7d0c9aaSMatthias Ringwald                     return 1;
2390e7d0c9aaSMatthias Ringwald                 }
2391e7d0c9aaSMatthias Ringwald 
239283fd9c76SMatthias Ringwald                 // security: check encryption
239383fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_2){
239483fd9c76SMatthias Ringwald                     if (sm_encryption_key_size(handle) == 0){
239583fd9c76SMatthias Ringwald                         // 0x0008 Connection refused - insufficient encryption
2396e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
239783fd9c76SMatthias Ringwald                         return 1;
239883fd9c76SMatthias Ringwald                     }
239983fd9c76SMatthias Ringwald                     // anything less than 16 byte key size is insufficient
240083fd9c76SMatthias Ringwald                     if (sm_encryption_key_size(handle) < 16){
240183fd9c76SMatthias Ringwald                         // 0x0007 Connection refused – insufficient encryption key size
2402e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
240383fd9c76SMatthias Ringwald                         return 1;
240483fd9c76SMatthias Ringwald                     }
240583fd9c76SMatthias Ringwald                 }
240683fd9c76SMatthias Ringwald 
240783fd9c76SMatthias Ringwald                 // security: check authencation
240883fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_3){
240983fd9c76SMatthias Ringwald                     if (!sm_authenticated(handle)){
241083fd9c76SMatthias Ringwald                         // 0x0005 Connection refused – insufficient authentication
2411e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
241283fd9c76SMatthias Ringwald                         return 1;
241383fd9c76SMatthias Ringwald                     }
241483fd9c76SMatthias Ringwald                 }
241583fd9c76SMatthias Ringwald 
241683fd9c76SMatthias Ringwald                 // security: check authorization
241783fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_4){
241883fd9c76SMatthias Ringwald                     if (sm_authorization_state(handle) != AUTHORIZATION_GRANTED){
241983fd9c76SMatthias Ringwald                         // 0x0006 Connection refused – insufficient authorization
2420e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
242183fd9c76SMatthias Ringwald                         return 1;
242283fd9c76SMatthias Ringwald                     }
242383fd9c76SMatthias Ringwald                 }
2424e7d0c9aaSMatthias Ringwald 
2425e7d0c9aaSMatthias Ringwald                 // allocate channel
24261b8b8d05SMatthias Ringwald                 channel = l2cap_create_channel_entry(service->packet_handler, connection->address,
2427e7d0c9aaSMatthias Ringwald                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
2428e7d0c9aaSMatthias Ringwald                 if (!channel){
2429e7d0c9aaSMatthias Ringwald                     // 0x0004 Connection refused – no resources available
2430e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2431e7d0c9aaSMatthias Ringwald                     return 1;
2432e7d0c9aaSMatthias Ringwald                 }
2433e7d0c9aaSMatthias Ringwald 
2434e7d0c9aaSMatthias Ringwald                 channel->con_handle = handle;
2435e7d0c9aaSMatthias Ringwald                 channel->remote_cid = source_cid;
2436e7d0c9aaSMatthias Ringwald                 channel->remote_sig_id = sig_id;
24377f107edaSMatthias Ringwald                 channel->remote_mtu = little_endian_read_16(command, 8);
24387f107edaSMatthias Ringwald                 channel->remote_mps = little_endian_read_16(command, 10);
24397f107edaSMatthias Ringwald                 channel->credits_outgoing = little_endian_read_16(command, 12);
2440e7d0c9aaSMatthias Ringwald 
2441e7d0c9aaSMatthias Ringwald                 // set initial state
2442e7d0c9aaSMatthias Ringwald                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2443c99bb618SMatthias Ringwald                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
2444e7d0c9aaSMatthias Ringwald 
2445e7d0c9aaSMatthias Ringwald                 // add to connections list
2446e7d0c9aaSMatthias Ringwald                 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2447e7d0c9aaSMatthias Ringwald 
2448e7d0c9aaSMatthias Ringwald                 // post connection request event
244944276248SMatthias Ringwald                 l2cap_emit_le_incoming_connection(channel);
2450e7d0c9aaSMatthias Ringwald 
2451e7d0c9aaSMatthias Ringwald             } else {
2452e7d0c9aaSMatthias Ringwald                 // Connection refused – LE_PSM not supported
2453e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2454e7d0c9aaSMatthias Ringwald             }
2455e7d0c9aaSMatthias Ringwald             break;
24561b8b8d05SMatthias Ringwald 
24571b8b8d05SMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
24581b8b8d05SMatthias Ringwald             // Find channel for this sig_id and connection handle
24591b8b8d05SMatthias Ringwald             channel = NULL;
24601b8b8d05SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
24611b8b8d05SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
24621b8b8d05SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
24631b8b8d05SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
24641b8b8d05SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
24651b8b8d05SMatthias Ringwald                 channel = a_channel;
24661b8b8d05SMatthias Ringwald                 break;
24671b8b8d05SMatthias Ringwald             }
24681b8b8d05SMatthias Ringwald             if (!channel) break;
24691b8b8d05SMatthias Ringwald 
24701b8b8d05SMatthias Ringwald             // cid + 0
24711b8b8d05SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
24721b8b8d05SMatthias Ringwald             if (result){
24731b8b8d05SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
24741b8b8d05SMatthias Ringwald                 // map l2cap connection response result to BTstack status enumeration
247544276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, result);
24761b8b8d05SMatthias Ringwald 
24771b8b8d05SMatthias Ringwald                 // discard channel
247863f0ac45SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
24791b8b8d05SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
24801b8b8d05SMatthias Ringwald                 break;
24811b8b8d05SMatthias Ringwald             }
24821b8b8d05SMatthias Ringwald 
24831b8b8d05SMatthias Ringwald             // success
24841b8b8d05SMatthias Ringwald             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
24851b8b8d05SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
24861b8b8d05SMatthias Ringwald             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
24871b8b8d05SMatthias Ringwald             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
24881b8b8d05SMatthias Ringwald             channel->state = L2CAP_STATE_OPEN;
248944276248SMatthias Ringwald             l2cap_emit_le_channel_opened(channel, result);
24901b8b8d05SMatthias Ringwald             break;
24911b8b8d05SMatthias Ringwald 
249285aeef60SMatthias Ringwald         case LE_FLOW_CONTROL_CREDIT:
249385aeef60SMatthias Ringwald             // find channel
249485aeef60SMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
249585aeef60SMatthias Ringwald             channel = l2cap_le_get_channel_for_local_cid(local_cid);
249663f0ac45SMatthias Ringwald             if (!channel) {
249763f0ac45SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
249863f0ac45SMatthias Ringwald                 break;
249963f0ac45SMatthias Ringwald             }
250063f0ac45SMatthias Ringwald             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
250163f0ac45SMatthias Ringwald             credits_before = channel->credits_outgoing;
250263f0ac45SMatthias Ringwald             channel->credits_outgoing += new_credits;
250363f0ac45SMatthias Ringwald             // check for credit overrun
250463f0ac45SMatthias Ringwald             if (credits_before > channel->credits_outgoing){
250563f0ac45SMatthias Ringwald                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
250663f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
250763f0ac45SMatthias Ringwald                 break;
250863f0ac45SMatthias Ringwald             }
250963f0ac45SMatthias Ringwald             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
251085aeef60SMatthias Ringwald             break;
251185aeef60SMatthias Ringwald 
2512828a7f7aSMatthias Ringwald         case DISCONNECTION_REQUEST:
2513828a7f7aSMatthias Ringwald             // find channel
2514828a7f7aSMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
2515828a7f7aSMatthias Ringwald             channel = l2cap_le_get_channel_for_local_cid(local_cid);
251663f34e00SMatthias Ringwald             if (!channel) {
251763f34e00SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
251863f34e00SMatthias Ringwald                 break;
251963f34e00SMatthias Ringwald             }
2520828a7f7aSMatthias Ringwald             channel->remote_sig_id = sig_id;
2521828a7f7aSMatthias Ringwald             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
2522828a7f7aSMatthias Ringwald             break;
2523828a7f7aSMatthias Ringwald 
2524a3dc965aSMatthias Ringwald #endif
2525a3dc965aSMatthias Ringwald 
252663f0ac45SMatthias Ringwald         case DISCONNECTION_RESPONSE:
252763f0ac45SMatthias Ringwald             break;
252863f0ac45SMatthias Ringwald 
2529c48b2a2cSMatthias Ringwald         default:
2530c48b2a2cSMatthias Ringwald             // command unknown -> reject command
2531c48b2a2cSMatthias Ringwald             return 0;
2532ccf076adS[email protected]     }
2533c48b2a2cSMatthias Ringwald     return 1;
2534c48b2a2cSMatthias Ringwald }
2535e7d0c9aaSMatthias Ringwald #endif
2536c48b2a2cSMatthias Ringwald 
2537c48b2a2cSMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size ){
25389ec2630cSMatthias Ringwald     UNUSED(packet_type);
25399ec2630cSMatthias Ringwald     UNUSED(channel);
2540c48b2a2cSMatthias Ringwald 
254109e9d05bSMatthias Ringwald     l2cap_channel_t * l2cap_channel;
2542f3963406SMatthias Ringwald     UNUSED(l2cap_channel);
254309e9d05bSMatthias Ringwald 
2544c48b2a2cSMatthias Ringwald     // Get Channel ID
2545c48b2a2cSMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
2546c48b2a2cSMatthias Ringwald     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
2547c48b2a2cSMatthias Ringwald 
2548c48b2a2cSMatthias Ringwald     switch (channel_id) {
2549c48b2a2cSMatthias Ringwald 
255009e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2551c48b2a2cSMatthias Ringwald         case L2CAP_CID_SIGNALING: {
2552c48b2a2cSMatthias Ringwald             uint16_t command_offset = 8;
2553c48b2a2cSMatthias Ringwald             while (command_offset < size) {
2554c48b2a2cSMatthias Ringwald                 // handle signaling commands
2555c48b2a2cSMatthias Ringwald                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
2556c48b2a2cSMatthias Ringwald 
2557c48b2a2cSMatthias Ringwald                 // increment command_offset
2558c48b2a2cSMatthias Ringwald                 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2559c48b2a2cSMatthias Ringwald             }
2560c48b2a2cSMatthias Ringwald             break;
2561c48b2a2cSMatthias Ringwald         }
256209e9d05bSMatthias Ringwald #endif
2563c48b2a2cSMatthias Ringwald 
2564e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
2565e7d0c9aaSMatthias Ringwald         case L2CAP_CID_SIGNALING_LE: {
2566e7d0c9aaSMatthias Ringwald             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
2567e7d0c9aaSMatthias Ringwald             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
2568c48b2a2cSMatthias Ringwald             if (!valid){
2569e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2570ccf076adS[email protected]             }
2571ccf076adS[email protected]             break;
2572e7d0c9aaSMatthias Ringwald         }
2573e7d0c9aaSMatthias Ringwald #endif
2574c48b2a2cSMatthias Ringwald 
2575c48b2a2cSMatthias Ringwald         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
2576c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback) {
2577c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2578ccf076adS[email protected]             }
2579c48b2a2cSMatthias Ringwald             break;
2580c48b2a2cSMatthias Ringwald 
2581c48b2a2cSMatthias Ringwald         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
2582c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback) {
2583c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2584c48b2a2cSMatthias Ringwald             }
2585c48b2a2cSMatthias Ringwald             break;
2586c48b2a2cSMatthias Ringwald 
2587c48b2a2cSMatthias Ringwald         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
2588c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback) {
2589c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2590c48b2a2cSMatthias Ringwald             }
2591c48b2a2cSMatthias Ringwald             break;
25921bbc0b23S[email protected] 
259309e9d05bSMatthias Ringwald         default:
259409e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
259500d93d79Smatthias.ringwald             // Find channel for this channel_id and connection handle
259664e11ca9SMatthias Ringwald             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
2597d1fd2a88SMatthias Ringwald             if (l2cap_channel) {
259827e0774aSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
259927e0774aSMatthias Ringwald                 if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
260027e0774aSMatthias Ringwald 
260127e0774aSMatthias Ringwald                     // verify FCS
260227e0774aSMatthias Ringwald                     uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
260327e0774aSMatthias Ringwald                     uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
260427e0774aSMatthias Ringwald                     log_info("Packet FCS 0x%04x, calculated FCS 0x%04x", fcs_packet, fcs_calculated);
260527e0774aSMatthias Ringwald                     if (fcs_calculated != fcs_packet){
260627e0774aSMatthias Ringwald                         log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
260727e0774aSMatthias Ringwald                         // TODO: trigger retransmission or something like that
260827e0774aSMatthias Ringwald                         break;
260927e0774aSMatthias Ringwald                     }
261027e0774aSMatthias Ringwald 
261127e0774aSMatthias Ringwald                     // switch on packet type
261227e0774aSMatthias Ringwald                     uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
261338f62777SMatthias Ringwald                     uint8_t  req_seq = (control >> 8) & 0x3f;
261427e0774aSMatthias Ringwald                     if (control & 1){
261527e0774aSMatthias Ringwald                         // S-Frame
261678cd8a22SMatthias Ringwald                         int poll = (control >> 4) & 0x01;
2617bdbe2e49SMatthias Ringwald                         l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
26189ffcbce4SMatthias Ringwald                         log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
2619*7b7901d8SMatthias Ringwald                         l2cap_ertm_tx_packet_state_t * tx_state;
2620bdbe2e49SMatthias Ringwald                         switch (s){
2621bdbe2e49SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
26229ffcbce4SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
26232a424812SMatthias Ringwald                                 l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
262478cd8a22SMatthias Ringwald                                 if (poll){
262578cd8a22SMatthias Ringwald                                     l2cap_channel->send_supervisor_frame_receiver_ready_final = 1;
262678cd8a22SMatthias Ringwald                                 }
2627bdbe2e49SMatthias Ringwald                                 break;
26289ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
26299ffcbce4SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
26309ffcbce4SMatthias Ringwald                                 l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
26319ffcbce4SMatthias Ringwald                                 // rsetart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_handle_req_seq)
26329ffcbce4SMatthias Ringwald                                 l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
26339ffcbce4SMatthias Ringwald                                 break;
26349ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
26359ffcbce4SMatthias Ringwald                                 log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
26369ffcbce4SMatthias Ringwald                                 break;
26379ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
2638*7b7901d8SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
2639*7b7901d8SMatthias Ringwald                                 if (poll){
2640*7b7901d8SMatthias Ringwald                                     l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
2641*7b7901d8SMatthias Ringwald                                 }
2642*7b7901d8SMatthias Ringwald                                 // find requested i-frame
2643*7b7901d8SMatthias Ringwald                                 tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
2644*7b7901d8SMatthias Ringwald                                 if (tx_state){
2645*7b7901d8SMatthias Ringwald                                     log_info("Retransmission for tx_seq %u requested", req_seq);
2646*7b7901d8SMatthias Ringwald                                     tx_state->retransmission_requested = 1;
2647*7b7901d8SMatthias Ringwald                                     l2cap_channel->srej_active = 1;
2648*7b7901d8SMatthias Ringwald                                 }
26499ffcbce4SMatthias Ringwald                                 break;
2650bdbe2e49SMatthias Ringwald                             default:
2651bdbe2e49SMatthias Ringwald                                 break;
2652bdbe2e49SMatthias Ringwald                         }
265327e0774aSMatthias Ringwald                         break;
265427e0774aSMatthias Ringwald                     } else {
265527e0774aSMatthias Ringwald                         // I-Frame
265627e0774aSMatthias Ringwald                         // get control
265727e0774aSMatthias Ringwald                         l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
265838f62777SMatthias Ringwald                         uint8_t tx_seq = (control >> 1) & 0x3f;
265938f62777SMatthias Ringwald                         log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
266038f62777SMatthias Ringwald                         log_info("SAR: pos %u", l2cap_channel->rx_packets_state->pos);
266138f62777SMatthias Ringwald                         log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
26622a424812SMatthias Ringwald                         l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
266338f62777SMatthias Ringwald                         // check ordering
266438f62777SMatthias Ringwald                         if (l2cap_channel->expected_tx_seq == tx_seq){
266538f62777SMatthias Ringwald                             log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
266638f62777SMatthias Ringwald                             l2cap_channel->req_seq = tx_seq;
2667d84e866fSMatthias Ringwald                             l2cap_channel->send_supervisor_frame_receiver_ready = 1;
266838f62777SMatthias Ringwald                             l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
2669ed971c5aSMatthias Ringwald                             uint16_t sdu_length;
2670ed971c5aSMatthias Ringwald                             uint16_t segment_length;
2671ed971c5aSMatthias Ringwald                             uint16_t payload_offset;
267227e0774aSMatthias Ringwald                             switch (sar){
267327e0774aSMatthias Ringwald                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
2674ed971c5aSMatthias Ringwald                                     payload_offset = COMPLETE_L2CAP_HEADER+2;
2675ed971c5aSMatthias Ringwald                                     segment_length = payload_offset-2;
2676ed971c5aSMatthias Ringwald                                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER+2], segment_length);
267727e0774aSMatthias Ringwald                                     break;
267827e0774aSMatthias Ringwald                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
2679ed971c5aSMatthias Ringwald                                     // TODO: use current packet
2680ed971c5aSMatthias Ringwald                                     // TODO: check if reassembly started
2681ed971c5aSMatthias Ringwald                                     // TODO: check len against local mtu
2682ed971c5aSMatthias Ringwald                                     sdu_length = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER+2);
2683ed971c5aSMatthias Ringwald                                     payload_offset = COMPLETE_L2CAP_HEADER+4;
2684ed971c5aSMatthias Ringwald                                     segment_length = size - payload_offset-2;
2685ed971c5aSMatthias Ringwald                                     memcpy(&l2cap_channel->rx_packets_data[0], &packet[payload_offset], segment_length);
2686ed971c5aSMatthias Ringwald                                     l2cap_channel->rx_packets_state->sdu_length = sdu_length;
2687ed971c5aSMatthias Ringwald                                     l2cap_channel->rx_packets_state->pos = segment_length;
2688ed971c5aSMatthias Ringwald                                     break;
268927e0774aSMatthias Ringwald                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
2690ed971c5aSMatthias Ringwald                                     payload_offset = COMPLETE_L2CAP_HEADER+2;
2691ed971c5aSMatthias Ringwald                                     segment_length = size - payload_offset-2;
2692ed971c5aSMatthias Ringwald                                     memcpy(&l2cap_channel->rx_packets_data[l2cap_channel->rx_packets_state->pos], &packet[payload_offset], segment_length);
2693ed971c5aSMatthias Ringwald                                     l2cap_channel->rx_packets_state->pos += segment_length;
2694ed971c5aSMatthias Ringwald                                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->rx_packets_data, l2cap_channel->rx_packets_state[0].pos);
2695ed971c5aSMatthias Ringwald                                     break;
269627e0774aSMatthias Ringwald                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
2697ed971c5aSMatthias Ringwald                                     payload_offset = COMPLETE_L2CAP_HEADER+2;
2698ed971c5aSMatthias Ringwald                                     segment_length = size - payload_offset-2;
2699ed971c5aSMatthias Ringwald                                     memcpy(&l2cap_channel->rx_packets_data[l2cap_channel->rx_packets_state->pos], &packet[payload_offset], segment_length);
2700ed971c5aSMatthias Ringwald                                     l2cap_channel->rx_packets_state->pos += segment_length;
270127e0774aSMatthias Ringwald                                     break;
270227e0774aSMatthias Ringwald                                 }
270327e0774aSMatthias Ringwald                             }
270438f62777SMatthias Ringwald                         }
270527e0774aSMatthias Ringwald                     break;
270627e0774aSMatthias Ringwald                 }
270727e0774aSMatthias Ringwald #endif
27083d50b4baSMatthias Ringwald                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
270900d93d79Smatthias.ringwald             }
271009e9d05bSMatthias Ringwald #endif
2711a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
271264e11ca9SMatthias Ringwald             l2cap_channel = l2cap_le_get_channel_for_local_cid(channel_id);
271364e11ca9SMatthias Ringwald             if (l2cap_channel) {
271485aeef60SMatthias Ringwald                 // credit counting
271585aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming == 0){
271685aeef60SMatthias Ringwald                     log_error("LE Data Channel packet received but no incoming credits");
271785aeef60SMatthias Ringwald                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
271885aeef60SMatthias Ringwald                     break;
271985aeef60SMatthias Ringwald                 }
272085aeef60SMatthias Ringwald                 l2cap_channel->credits_incoming--;
272185aeef60SMatthias Ringwald 
272285aeef60SMatthias Ringwald                 // automatic credits
272385aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){
272485aeef60SMatthias Ringwald                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
272585aeef60SMatthias Ringwald                 }
272685aeef60SMatthias Ringwald 
2727cd529728SMatthias Ringwald                 // first fragment
2728cd529728SMatthias Ringwald                 uint16_t pos = 0;
2729cd529728SMatthias Ringwald                 if (!l2cap_channel->receive_sdu_len){
2730cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
2731cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_pos = 0;
2732cd529728SMatthias Ringwald                     pos  += 2;
2733cd529728SMatthias Ringwald                     size -= 2;
2734cd529728SMatthias Ringwald                 }
2735cd529728SMatthias Ringwald                 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], size-COMPLETE_L2CAP_HEADER);
2736cd529728SMatthias Ringwald                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
2737cd529728SMatthias Ringwald                 // done?
273863f0ac45SMatthias Ringwald                 log_info("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
2739cd529728SMatthias Ringwald                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
2740cd529728SMatthias Ringwald                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
2741cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = 0;
2742cd529728SMatthias Ringwald                 }
274363f0ac45SMatthias Ringwald             } else {
274463f0ac45SMatthias Ringwald                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
274564e11ca9SMatthias Ringwald             }
274664e11ca9SMatthias Ringwald #endif
27475652b5ffS[email protected]             break;
27485652b5ffS[email protected]     }
274900d93d79Smatthias.ringwald 
27501eb2563eS[email protected]     l2cap_run();
27512718e2e7Smatthias.ringwald }
275200d93d79Smatthias.ringwald 
275309e9d05bSMatthias Ringwald // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
275409e9d05bSMatthias Ringwald void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
275509e9d05bSMatthias Ringwald     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
275609e9d05bSMatthias Ringwald     if (index < 0) return;
275709e9d05bSMatthias Ringwald     fixed_channels[index].callback = the_packet_handler;
275809e9d05bSMatthias Ringwald }
275909e9d05bSMatthias Ringwald 
276009e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
276115ec09bbSmatthias.ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
276227a923d0Smatthias.ringwald void l2cap_finialize_channel_close(l2cap_channel_t * channel){
2763f62db1e3Smatthias.ringwald     channel->state = L2CAP_STATE_CLOSED;
2764f62db1e3Smatthias.ringwald     l2cap_emit_channel_closed(channel);
2765f62db1e3Smatthias.ringwald     // discard channel
27669dcb2fb2S[email protected]     l2cap_stop_rtx(channel);
2767665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2768d3a9df87Smatthias.ringwald     btstack_memory_l2cap_channel_free(channel);
2769c8e4258aSmatthias.ringwald }
27701e6aba47Smatthias.ringwald 
27718f2a52f4SMatthias Ringwald static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
2772665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
2773665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, services);
2774665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2775665d90f2SMatthias Ringwald         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
27769d9bbc01Smatthias.ringwald         if ( service->psm == psm){
27779d9bbc01Smatthias.ringwald             return service;
27789d9bbc01Smatthias.ringwald         };
27799d9bbc01Smatthias.ringwald     }
27809d9bbc01Smatthias.ringwald     return NULL;
27819d9bbc01Smatthias.ringwald }
27829d9bbc01Smatthias.ringwald 
27837192e786SMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
27847192e786SMatthias Ringwald     return l2cap_get_service_internal(&l2cap_services, psm);
27857192e786SMatthias Ringwald }
27867192e786SMatthias Ringwald 
2787e0abb8e7S[email protected] 
2788be2053a6SMatthias 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){
2789be2053a6SMatthias Ringwald 
2790be2053a6SMatthias Ringwald     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
2791e0abb8e7S[email protected] 
27924bb582b6Smatthias.ringwald     // check for alread registered psm
27939d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
2794277abc2cSmatthias.ringwald     if (service) {
2795be2053a6SMatthias Ringwald         log_error("l2cap_register_service: PSM %u already registered", psm);
2796be2053a6SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
2797277abc2cSmatthias.ringwald     }
27989d9bbc01Smatthias.ringwald 
27994bb582b6Smatthias.ringwald     // alloc structure
2800bb69aaaeS[email protected]     service = btstack_memory_l2cap_service_get();
2801277abc2cSmatthias.ringwald     if (!service) {
2802be2053a6SMatthias Ringwald         log_error("l2cap_register_service: no memory for l2cap_service_t");
2803be2053a6SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
2804277abc2cSmatthias.ringwald     }
28059d9bbc01Smatthias.ringwald 
28069d9bbc01Smatthias.ringwald     // fill in
28079d9bbc01Smatthias.ringwald     service->psm = psm;
28089d9bbc01Smatthias.ringwald     service->mtu = mtu;
280905ae8de3SMatthias Ringwald     service->packet_handler = service_packet_handler;
2810df3354fcS[email protected]     service->required_security_level = security_level;
28119d9bbc01Smatthias.ringwald 
28129d9bbc01Smatthias.ringwald     // add to services list
2813665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
2814c0e866bfSmatthias.ringwald 
2815c0e866bfSmatthias.ringwald     // enable page scan
281615a95bd5SMatthias Ringwald     gap_connectable_control(1);
28175842b6d9Smatthias.ringwald 
2818be2053a6SMatthias Ringwald     return 0;
28199d9bbc01Smatthias.ringwald }
28209d9bbc01Smatthias.ringwald 
28217e8856ebSMatthias Ringwald uint8_t l2cap_unregister_service(uint16_t psm){
2822e0abb8e7S[email protected] 
2823e0abb8e7S[email protected]     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
2824e0abb8e7S[email protected] 
28259d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
28267e8856ebSMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2827665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
2828d3a9df87Smatthias.ringwald     btstack_memory_l2cap_service_free(service);
2829c0e866bfSmatthias.ringwald 
2830c0e866bfSmatthias.ringwald     // disable page scan when no services registered
28317e8856ebSMatthias Ringwald     if (btstack_linked_list_empty(&l2cap_services)) {
283215a95bd5SMatthias Ringwald         gap_connectable_control(0);
28339d9bbc01Smatthias.ringwald     }
28347e8856ebSMatthias Ringwald     return 0;
28357e8856ebSMatthias Ringwald }
283609e9d05bSMatthias Ringwald #endif
28379d9bbc01Smatthias.ringwald 
28387192e786SMatthias Ringwald 
2839cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
284083fd9c76SMatthias Ringwald 
284157be49d6SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
284257be49d6SMatthias Ringwald     if (!channel->waiting_for_can_send_now) return;
284357be49d6SMatthias Ringwald     if (channel->send_sdu_buffer) return;
284457be49d6SMatthias Ringwald     channel->waiting_for_can_send_now = 0;
284557be49d6SMatthias Ringwald     log_info("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
284657be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
284757be49d6SMatthias Ringwald }
284857be49d6SMatthias Ringwald 
284957be49d6SMatthias Ringwald // 1BH2222
285057be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
285157be49d6SMatthias 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",
285257be49d6SMatthias Ringwald              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
285357be49d6SMatthias Ringwald     uint8_t event[19];
285457be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
285557be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
285657be49d6SMatthias Ringwald     event[2] = channel->address_type;
285757be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
285857be49d6SMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
285957be49d6SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
286057be49d6SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
286157be49d6SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
286257be49d6SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_mtu);
286357be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
286457be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
286557be49d6SMatthias Ringwald }
286657be49d6SMatthias Ringwald // 11BH22222
286757be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
286857be49d6SMatthias 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",
286957be49d6SMatthias Ringwald              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
287057be49d6SMatthias Ringwald              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
2871c99bb618SMatthias Ringwald     uint8_t event[23];
287257be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
287357be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
287457be49d6SMatthias Ringwald     event[2] = status;
287557be49d6SMatthias Ringwald     event[3] = channel->address_type;
287657be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[4]);
287757be49d6SMatthias Ringwald     little_endian_store_16(event, 10, channel->con_handle);
2878c99bb618SMatthias Ringwald     event[12] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
2879c99bb618SMatthias Ringwald     little_endian_store_16(event, 13, channel->psm);
2880c99bb618SMatthias Ringwald     little_endian_store_16(event, 15, channel->local_cid);
2881c99bb618SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_cid);
2882c99bb618SMatthias Ringwald     little_endian_store_16(event, 19, channel->local_mtu);
2883c99bb618SMatthias Ringwald     little_endian_store_16(event, 21, channel->remote_mtu);
288457be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
288557be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
288657be49d6SMatthias Ringwald }
288757be49d6SMatthias Ringwald 
288857be49d6SMatthias Ringwald static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid){
288957be49d6SMatthias Ringwald     btstack_linked_list_iterator_t it;
289057be49d6SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
289157be49d6SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
289257be49d6SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
289357be49d6SMatthias Ringwald         if ( channel->local_cid == local_cid) {
289457be49d6SMatthias Ringwald             return channel;
289557be49d6SMatthias Ringwald         }
289657be49d6SMatthias Ringwald     }
289757be49d6SMatthias Ringwald     return NULL;
289857be49d6SMatthias Ringwald }
289957be49d6SMatthias Ringwald 
290057be49d6SMatthias Ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
290157be49d6SMatthias Ringwald void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
290257be49d6SMatthias Ringwald     channel->state = L2CAP_STATE_CLOSED;
290357be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
290457be49d6SMatthias Ringwald     // discard channel
290557be49d6SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
290657be49d6SMatthias Ringwald     btstack_memory_l2cap_channel_free(channel);
290757be49d6SMatthias Ringwald }
290857be49d6SMatthias Ringwald 
2909e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
2910e7d0c9aaSMatthias Ringwald     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
29117192e786SMatthias Ringwald }
2912efedfb4cSMatthias Ringwald 
2913da144af5SMatthias Ringwald uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
29147192e786SMatthias Ringwald 
2915da144af5SMatthias Ringwald     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
29167192e786SMatthias Ringwald 
29177192e786SMatthias Ringwald     // check for alread registered psm
29187192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
29197192e786SMatthias Ringwald     if (service) {
2920da144af5SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
29217192e786SMatthias Ringwald     }
29227192e786SMatthias Ringwald 
29237192e786SMatthias Ringwald     // alloc structure
29247192e786SMatthias Ringwald     service = btstack_memory_l2cap_service_get();
29257192e786SMatthias Ringwald     if (!service) {
29267192e786SMatthias Ringwald         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
2927da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
29287192e786SMatthias Ringwald     }
29297192e786SMatthias Ringwald 
29307192e786SMatthias Ringwald     // fill in
29317192e786SMatthias Ringwald     service->psm = psm;
2932da144af5SMatthias Ringwald     service->mtu = 0;
29337192e786SMatthias Ringwald     service->packet_handler = packet_handler;
29347192e786SMatthias Ringwald     service->required_security_level = security_level;
29357192e786SMatthias Ringwald 
29367192e786SMatthias Ringwald     // add to services list
2937665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
29387192e786SMatthias Ringwald 
29397192e786SMatthias Ringwald     // done
2940da144af5SMatthias Ringwald     return 0;
29417192e786SMatthias Ringwald }
29427192e786SMatthias Ringwald 
2943da144af5SMatthias Ringwald uint8_t l2cap_le_unregister_service(uint16_t psm) {
29447192e786SMatthias Ringwald     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
29457192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
29469367f9b0SMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2947da144af5SMatthias Ringwald 
2948665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
29497192e786SMatthias Ringwald     btstack_memory_l2cap_service_free(service);
2950da144af5SMatthias Ringwald     return 0;
29517192e786SMatthias Ringwald }
2952da144af5SMatthias Ringwald 
2953da144af5SMatthias Ringwald uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
2954e7d0c9aaSMatthias Ringwald     // get channel
2955e7d0c9aaSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2956e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2957e7d0c9aaSMatthias Ringwald 
2958e7d0c9aaSMatthias Ringwald     // validate state
2959e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2960e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
2961e7d0c9aaSMatthias Ringwald     }
2962e7d0c9aaSMatthias Ringwald 
2963efedfb4cSMatthias Ringwald     // set state accept connection
296423017473SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
296523017473SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
296623017473SMatthias Ringwald     channel->local_mtu = mtu;
296785aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
296885aeef60SMatthias Ringwald     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
296985aeef60SMatthias Ringwald 
297085aeef60SMatthias Ringwald     // test
297163f0ac45SMatthias Ringwald     // channel->new_credits_incoming = 1;
2972e7d0c9aaSMatthias Ringwald 
2973e7d0c9aaSMatthias Ringwald     // go
2974e7d0c9aaSMatthias Ringwald     l2cap_run();
2975da144af5SMatthias Ringwald     return 0;
2976da144af5SMatthias Ringwald }
2977da144af5SMatthias Ringwald 
2978da144af5SMatthias Ringwald /**
2979da144af5SMatthias Ringwald  * @brief Deny incoming LE Data Channel connection due to resource constraints
2980da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2981da144af5SMatthias Ringwald  */
2982da144af5SMatthias Ringwald 
2983da144af5SMatthias Ringwald uint8_t l2cap_le_decline_connection(uint16_t local_cid){
2984e7d0c9aaSMatthias Ringwald     // get channel
2985e7d0c9aaSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2986e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2987e7d0c9aaSMatthias Ringwald 
2988e7d0c9aaSMatthias Ringwald     // validate state
2989e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2990e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
2991e7d0c9aaSMatthias Ringwald     }
2992e7d0c9aaSMatthias Ringwald 
2993efedfb4cSMatthias Ringwald     // set state decline connection
2994e7d0c9aaSMatthias Ringwald     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
2995e7d0c9aaSMatthias Ringwald     channel->reason = 0x04; // no resources available
2996e7d0c9aaSMatthias Ringwald     l2cap_run();
2997da144af5SMatthias Ringwald     return 0;
2998da144af5SMatthias Ringwald }
2999da144af5SMatthias Ringwald 
30007dafa750SMatthias Ringwald uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
3001da144af5SMatthias Ringwald     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
3002efedfb4cSMatthias Ringwald     uint16_t * out_local_cid) {
3003efedfb4cSMatthias Ringwald 
30047dafa750SMatthias Ringwald     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
3005da144af5SMatthias Ringwald 
30067dafa750SMatthias Ringwald 
30077dafa750SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
30087dafa750SMatthias Ringwald     if (!connection) {
30097dafa750SMatthias Ringwald         log_error("no hci_connection for handle 0x%04x", con_handle);
30107dafa750SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
30117dafa750SMatthias Ringwald     }
30127dafa750SMatthias Ringwald 
30137dafa750SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, connection->address, connection->address_type, psm, mtu, security_level);
3014da144af5SMatthias Ringwald     if (!channel) {
3015da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
3016da144af5SMatthias Ringwald     }
3017e7d0c9aaSMatthias Ringwald     log_info("l2cap_le_create_channel %p", channel);
3018da144af5SMatthias Ringwald 
3019da144af5SMatthias Ringwald     // store local_cid
3020da144af5SMatthias Ringwald     if (out_local_cid){
3021da144af5SMatthias Ringwald        *out_local_cid = channel->local_cid;
3022da144af5SMatthias Ringwald     }
3023da144af5SMatthias Ringwald 
30247dafa750SMatthias Ringwald     // provide buffer
30257dafa750SMatthias Ringwald     channel->con_handle = con_handle;
3026cd529728SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
30277dafa750SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
302885aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
302985aeef60SMatthias Ringwald     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
303085aeef60SMatthias Ringwald 
3031efedfb4cSMatthias Ringwald     // add to connections list
3032efedfb4cSMatthias Ringwald     btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
3033efedfb4cSMatthias Ringwald 
30347dafa750SMatthias Ringwald     // go
303563f0ac45SMatthias Ringwald     l2cap_run();
3036da144af5SMatthias Ringwald     return 0;
3037da144af5SMatthias Ringwald }
3038da144af5SMatthias Ringwald 
3039da144af5SMatthias Ringwald /**
3040da144af5SMatthias Ringwald  * @brief Provide credtis for LE Data Channel
3041da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3042da144af5SMatthias Ringwald  * @param credits               Number additional credits for peer
3043da144af5SMatthias Ringwald  */
304464e11ca9SMatthias Ringwald uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
304563f0ac45SMatthias Ringwald 
304663f0ac45SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
304763f0ac45SMatthias Ringwald     if (!channel) {
304863f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
304963f0ac45SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
305063f0ac45SMatthias Ringwald     }
305163f0ac45SMatthias Ringwald 
3052efedfb4cSMatthias Ringwald     // check state
305363f0ac45SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN){
305463f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
305563f0ac45SMatthias Ringwald     }
305663f0ac45SMatthias Ringwald 
305763f0ac45SMatthias Ringwald     // assert incoming credits + credits <= 0xffff
305863f0ac45SMatthias Ringwald     uint32_t total_credits = channel->credits_incoming;
305963f0ac45SMatthias Ringwald     total_credits += channel->new_credits_incoming;
306063f0ac45SMatthias Ringwald     total_credits += credits;
306163f0ac45SMatthias Ringwald     if (total_credits > 0xffff){
306263f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
306363f0ac45SMatthias Ringwald             channel->new_credits_incoming, credits);
306463f0ac45SMatthias Ringwald     }
306563f0ac45SMatthias Ringwald 
3066efedfb4cSMatthias Ringwald     // set credits_granted
306763f0ac45SMatthias Ringwald     channel->new_credits_incoming += credits;
306863f0ac45SMatthias Ringwald 
306963f0ac45SMatthias Ringwald     // go
307063f0ac45SMatthias Ringwald     l2cap_run();
3071da144af5SMatthias Ringwald     return 0;
3072da144af5SMatthias Ringwald }
3073da144af5SMatthias Ringwald 
3074da144af5SMatthias Ringwald /**
3075da144af5SMatthias Ringwald  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
3076da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3077da144af5SMatthias Ringwald  */
307864e11ca9SMatthias Ringwald int l2cap_le_can_send_now(uint16_t local_cid){
307944276248SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
308044276248SMatthias Ringwald     if (!channel) {
308144276248SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
3082da144af5SMatthias Ringwald         return 0;
3083da144af5SMatthias Ringwald     }
3084da144af5SMatthias Ringwald 
308544276248SMatthias Ringwald     // check state
308644276248SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN) return 0;
308744276248SMatthias Ringwald 
308844276248SMatthias Ringwald     // check queue
308944276248SMatthias Ringwald     if (channel->send_sdu_buffer) return 0;
309044276248SMatthias Ringwald 
309144276248SMatthias Ringwald     // fine, go ahead
309244276248SMatthias Ringwald     return 1;
309344276248SMatthias Ringwald }
309444276248SMatthias Ringwald 
3095da144af5SMatthias Ringwald /**
3096da144af5SMatthias Ringwald  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
3097da144af5SMatthias Ringwald  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
3098da144af5SMatthias Ringwald  *       so packet handler should be ready to handle it
3099da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3100da144af5SMatthias Ringwald  */
310164e11ca9SMatthias Ringwald uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
310244276248SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
310344276248SMatthias Ringwald     if (!channel) {
310444276248SMatthias Ringwald         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
310544276248SMatthias Ringwald         return 0;
310644276248SMatthias Ringwald     }
310744276248SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
310844276248SMatthias Ringwald     l2cap_le_notify_channel_can_send(channel);
3109da144af5SMatthias Ringwald     return 0;
3110da144af5SMatthias Ringwald }
3111da144af5SMatthias Ringwald 
3112da144af5SMatthias Ringwald /**
3113da144af5SMatthias Ringwald  * @brief Send data via LE Data Channel
3114da144af5SMatthias Ringwald  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
3115da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3116da144af5SMatthias Ringwald  * @param data                  data to send
3117da144af5SMatthias Ringwald  * @param size                  data size
3118da144af5SMatthias Ringwald  */
311964e11ca9SMatthias Ringwald uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
312064e11ca9SMatthias Ringwald 
312164e11ca9SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
312264e11ca9SMatthias Ringwald     if (!channel) {
312364e11ca9SMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
3124828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
312564e11ca9SMatthias Ringwald     }
312664e11ca9SMatthias Ringwald 
312764e11ca9SMatthias Ringwald     if (len > channel->remote_mtu){
312864e11ca9SMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
312964e11ca9SMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
313064e11ca9SMatthias Ringwald     }
313164e11ca9SMatthias Ringwald 
31327f107edaSMatthias Ringwald     if (channel->send_sdu_buffer){
313364e11ca9SMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
313464e11ca9SMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
313564e11ca9SMatthias Ringwald     }
313664e11ca9SMatthias Ringwald 
31377f107edaSMatthias Ringwald     channel->send_sdu_buffer = data;
31387f107edaSMatthias Ringwald     channel->send_sdu_len    = len;
31397f107edaSMatthias Ringwald     channel->send_sdu_pos    = 0;
314064e11ca9SMatthias Ringwald 
31417f107edaSMatthias Ringwald     l2cap_run();
31427f107edaSMatthias Ringwald     return 0;
3143da144af5SMatthias Ringwald }
3144da144af5SMatthias Ringwald 
3145da144af5SMatthias Ringwald /**
3146da144af5SMatthias Ringwald  * @brief Disconnect from LE Data Channel
3147da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3148da144af5SMatthias Ringwald  */
3149828a7f7aSMatthias Ringwald uint8_t l2cap_le_disconnect(uint16_t local_cid)
3150da144af5SMatthias Ringwald {
3151828a7f7aSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3152828a7f7aSMatthias Ringwald     if (!channel) {
3153828a7f7aSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
3154828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3155828a7f7aSMatthias Ringwald     }
3156828a7f7aSMatthias Ringwald 
3157828a7f7aSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3158828a7f7aSMatthias Ringwald     l2cap_run();
3159da144af5SMatthias Ringwald     return 0;
3160da144af5SMatthias Ringwald }
3161da144af5SMatthias Ringwald 
31627f02f414SMatthias Ringwald #endif
3163