xref: /btstack/src/l2cap.c (revision 78cd8a226db0f9d987c61bfafaa755ff58d485c9)
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 }
57262041d70SMatthias Ringwald static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts){
57362041d70SMatthias Ringwald     UNUSED(ts);
57462041d70SMatthias Ringwald     log_info("l2cap_ertm_retransmission_timeout_callback");
57562041d70SMatthias Ringwald     l2cap_channel_t * channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
57662041d70SMatthias Ringwald     channel->send_supervisor_frame_receiver_ready_poll = 1;
57762041d70SMatthias Ringwald     l2cap_run();
57862041d70SMatthias Ringwald }
579f0fb4cd7SMatthias Ringwald static int l2cap_ertm_send_information_frame(l2cap_channel_t * channel, int index){
580f0fb4cd7SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
581f0fb4cd7SMatthias Ringwald     hci_reserve_packet_buffer();
582f0fb4cd7SMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
583f0fb4cd7SMatthias Ringwald     uint16_t control = l2cap_encanced_control_field_for_information_frame(tx_state->tx_seq, 0, 0, L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU);
584f0fb4cd7SMatthias Ringwald     log_info("I-Frame: control 0x%04x", control);
585f0fb4cd7SMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
586f0fb4cd7SMatthias Ringwald     memcpy(&acl_buffer[8+2], &channel->tx_packets_data[index * channel->local_mtu], tx_state->len);
587f0fb4cd7SMatthias Ringwald     // send
588f0fb4cd7SMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2 + tx_state->len);
589f0fb4cd7SMatthias Ringwald }
590f0fb4cd7SMatthias Ringwald static int l2cap_ertm_send(l2cap_channel_t * channel, uint8_t * data, uint16_t len){
591f0fb4cd7SMatthias Ringwald     if (len > channel->remote_mtu){
592f0fb4cd7SMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
593f0fb4cd7SMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
594f0fb4cd7SMatthias Ringwald     }
595f0fb4cd7SMatthias Ringwald     // TODO: check tx_transmit
5962a424812SMatthias Ringwald     // store int tx packet bufferx
597f0fb4cd7SMatthias Ringwald     int index = channel->tx_write_index;
598f0fb4cd7SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
599f0fb4cd7SMatthias Ringwald     tx_state->tx_seq = channel->next_tx_seq;
600f0fb4cd7SMatthias Ringwald     tx_state->len = len;
601f0fb4cd7SMatthias Ringwald     memcpy(&channel->tx_packets_data[index * channel->local_mtu], data, len);
602f0fb4cd7SMatthias Ringwald     // update
603f0fb4cd7SMatthias Ringwald     channel->next_tx_seq = l2cap_next_ertm_seq_nr(channel->next_tx_seq);
604f0fb4cd7SMatthias Ringwald     l2cap_ertm_next_tx_write_index(channel);
60562041d70SMatthias Ringwald     // set retransmission timer
60662041d70SMatthias Ringwald     btstack_run_loop_set_timer_handler(&tx_state->retransmission_timer, &l2cap_ertm_retransmission_timeout_callback);
60762041d70SMatthias Ringwald     btstack_run_loop_set_timer_context(&tx_state->retransmission_timer, channel);
60862041d70SMatthias Ringwald     btstack_run_loop_set_timer(&tx_state->retransmission_timer, channel->local_retransmission_timeout_ms);
60962041d70SMatthias Ringwald     btstack_run_loop_add_timer(&tx_state->retransmission_timer);
610675e6881SMatthias Ringwald     // try to send
611675e6881SMatthias Ringwald     l2cap_run();
612f0fb4cd7SMatthias Ringwald     return 0;
613f0fb4cd7SMatthias Ringwald }
61485ddcd84SMatthias Ringwald #endif
61558de5610Smatthias.ringwald 
616f511cefaSMatthias Ringwald // assumption - only on Classic connections
617ce8f182eSMatthias Ringwald int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
618a35252c8S[email protected]     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
619a35252c8S[email protected]     if (!channel) {
620ce8f182eSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
621a35252c8S[email protected]         return -1;   // TODO: define error
622a35252c8S[email protected]     }
623a35252c8S[email protected] 
624f0fb4cd7SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
625f0fb4cd7SMatthias Ringwald     // send in ERTM
626f0fb4cd7SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
627f0fb4cd7SMatthias Ringwald         return l2cap_ertm_send(channel, data, len);
628f0fb4cd7SMatthias Ringwald     }
629f0fb4cd7SMatthias Ringwald #endif
630f0fb4cd7SMatthias Ringwald 
631f0efaa57S[email protected]     if (len > channel->remote_mtu){
632ce8f182eSMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
633f0efaa57S[email protected]         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
634f0efaa57S[email protected]     }
635f0efaa57S[email protected] 
636fc64f94aSMatthias Ringwald     if (!hci_can_send_acl_packet_now(channel->con_handle)){
637ce8f182eSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
638b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
639b1d43497Smatthias.ringwald     }
640b1d43497Smatthias.ringwald 
6412a373862S[email protected]     hci_reserve_packet_buffer();
642facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
643f0fb4cd7SMatthias Ringwald     memcpy(&acl_buffer[8], data, len);
644f0fb4cd7SMatthias Ringwald     return l2cap_send_prepared(local_cid, len);
645b1d43497Smatthias.ringwald }
646b1d43497Smatthias.ringwald 
647fc64f94aSMatthias Ringwald int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
648fc64f94aSMatthias Ringwald     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
6490e37e417S[email protected] }
6500e37e417S[email protected] 
65128ca2b46S[email protected] static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
65228ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
65328ca2b46S[email protected] }
65428ca2b46S[email protected] 
65528ca2b46S[email protected] static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
65628ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
65728ca2b46S[email protected] }
65809e9d05bSMatthias Ringwald #endif
65928ca2b46S[email protected] 
66028ca2b46S[email protected] 
66109e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
66209e9d05bSMatthias Ringwald static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, uint8_t identifier, ...){
66309e9d05bSMatthias Ringwald 
66409e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(handle)){
66509e9d05bSMatthias Ringwald         log_info("l2cap_send_le_signaling_packet, cannot send");
66609e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
66709e9d05bSMatthias Ringwald     }
66809e9d05bSMatthias Ringwald 
66909e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
67009e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
67109e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
67209e9d05bSMatthias Ringwald     va_list argptr;
67309e9d05bSMatthias Ringwald     va_start(argptr, identifier);
67409e9d05bSMatthias Ringwald     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
67509e9d05bSMatthias Ringwald     va_end(argptr);
67609e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
67709e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len);
67809e9d05bSMatthias Ringwald }
67909e9d05bSMatthias Ringwald #endif
68009e9d05bSMatthias Ringwald 
68109e9d05bSMatthias Ringwald uint16_t l2cap_max_mtu(void){
68209e9d05bSMatthias Ringwald     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
68309e9d05bSMatthias Ringwald }
68409e9d05bSMatthias Ringwald 
68509e9d05bSMatthias Ringwald uint16_t l2cap_max_le_mtu(void){
68609e9d05bSMatthias Ringwald     return l2cap_max_mtu();
68709e9d05bSMatthias Ringwald }
688b1d43497Smatthias.ringwald 
689450ad7ecSMatthias Ringwald static uint16_t l2cap_setup_options_mtu(l2cap_channel_t * channel, uint8_t * config_options){
690450ad7ecSMatthias Ringwald     config_options[0] = 1; // MTU
691450ad7ecSMatthias Ringwald     config_options[1] = 2; // len param
692450ad7ecSMatthias Ringwald     little_endian_store_16( (uint8_t*)&config_options, 2, channel->local_mtu);
693450ad7ecSMatthias Ringwald     return 4;
694450ad7ecSMatthias Ringwald }
695450ad7ecSMatthias Ringwald 
6966dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
697450ad7ecSMatthias Ringwald static uint16_t l2cap_setup_options_ertm(l2cap_channel_t * channel, uint8_t * config_options){
6986dca2a0cSMatthias Ringwald     config_options[0] = 0x04;   // RETRANSMISSION AND FLOW CONTROL OPTION
6996dca2a0cSMatthias Ringwald     config_options[1] = 9;      // length
7006dca2a0cSMatthias Ringwald     config_options[2] = (uint8_t) channel->mode;
7017b181629SMatthias Ringwald     config_options[3] = channel->num_rx_buffers;    // == TxWindows size
702bbc0a9e7SMatthias Ringwald     config_options[4] = channel->local_max_transmit;
703bbc0a9e7SMatthias Ringwald     little_endian_store_16( config_options, 5, channel->local_retransmission_timeout_ms);
704bbc0a9e7SMatthias Ringwald     little_endian_store_16( config_options, 7, channel->local_monitor_timeout_ms);
7057b181629SMatthias Ringwald     little_endian_store_16( config_options, 9, channel->local_mtu);
706450ad7ecSMatthias Ringwald     return 11;
7076dca2a0cSMatthias Ringwald }
70838f62777SMatthias Ringwald static int l2cap_ertm_send_supervisor_frame(l2cap_channel_t * channel, uint16_t control){
70938f62777SMatthias Ringwald     hci_reserve_packet_buffer();
71038f62777SMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
71138f62777SMatthias Ringwald     log_info("S-Frame: control 0x%04x", control);
71238f62777SMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
71338f62777SMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2);
71438f62777SMatthias Ringwald }
715212b6be2SMatthias Ringwald static int l2cap_ertm_num_unacknowledged_tx_packets(l2cap_channel_t * channel){
716212b6be2SMatthias Ringwald     int unacknowledged_packets = channel->tx_send_index - channel->tx_read_index;
717212b6be2SMatthias Ringwald     if (unacknowledged_packets < 0){
718212b6be2SMatthias Ringwald         unacknowledged_packets += channel->num_tx_buffers;
719212b6be2SMatthias Ringwald     }
720212b6be2SMatthias Ringwald     return unacknowledged_packets;
721212b6be2SMatthias Ringwald }
722450ad7ecSMatthias Ringwald #endif
723450ad7ecSMatthias Ringwald 
724450ad7ecSMatthias Ringwald static uint16_t l2cap_setup_options(l2cap_channel_t * channel, uint8_t * config_options){
725450ad7ecSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
726450ad7ecSMatthias Ringwald     // use ERTM options if supported
727450ad7ecSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
728450ad7ecSMatthias Ringwald     if ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE) && (connection->l2cap_state.extended_feature_mask & 0x08)){
729450ad7ecSMatthias Ringwald         return l2cap_setup_options_ertm(channel, config_options);
730450ad7ecSMatthias Ringwald 
731450ad7ecSMatthias Ringwald     }
732450ad7ecSMatthias Ringwald #endif
733450ad7ecSMatthias Ringwald     return l2cap_setup_options_mtu(channel, config_options);
7346dca2a0cSMatthias Ringwald }
7356dca2a0cSMatthias Ringwald 
7361b9cb13dSMatthias Ringwald static uint32_t l2cap_extended_features_mask(void){
7371b9cb13dSMatthias Ringwald     // extended features request supported, features: fixed channels, unicast connectionless data reception
7381b9cb13dSMatthias Ringwald     uint32_t features = 0x280;
7391b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
7401b9cb13dSMatthias Ringwald     features |= 0x0008;
7411b9cb13dSMatthias Ringwald #endif
7421b9cb13dSMatthias Ringwald     return features;
7431b9cb13dSMatthias Ringwald }
7441b9cb13dSMatthias Ringwald 
7458158c421Smatthias.ringwald // MARK: L2CAP_RUN
7462cd0be45Smatthias.ringwald // process outstanding signaling tasks
7477f02f414SMatthias Ringwald static void l2cap_run(void){
7482b83fb7dSmatthias.ringwald 
74922c29ab4SMatthias Ringwald     // log_info("l2cap_run: entered");
75022c29ab4SMatthias Ringwald 
7512b83fb7dSmatthias.ringwald     // check pending signaling responses
7522b83fb7dSmatthias.ringwald     while (signaling_responses_pending){
7532b83fb7dSmatthias.ringwald 
7542b83fb7dSmatthias.ringwald         hci_con_handle_t handle = signaling_responses[0].handle;
755a35252c8S[email protected] 
756a35252c8S[email protected]         if (!hci_can_send_acl_packet_now(handle)) break;
757a35252c8S[email protected] 
7582b83fb7dSmatthias.ringwald         uint8_t  sig_id        = signaling_responses[0].sig_id;
759e74c5f58SMatthias Ringwald         uint8_t  response_code = signaling_responses[0].code;
7602b360848Smatthias.ringwald         uint16_t infoType      = signaling_responses[0].data;  // INFORMATION_REQUEST
76163a7246aSmatthias.ringwald         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
762b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
763b3264428SMatthias Ringwald         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
764b3264428SMatthias Ringwald #endif
765f3963406SMatthias Ringwald         UNUSED(infoType);
76609e9d05bSMatthias Ringwald 
767f53da564S[email protected]         // remove first item before sending (to avoid sending response mutliple times)
768f53da564S[email protected]         signaling_responses_pending--;
769f53da564S[email protected]         int i;
770f53da564S[email protected]         for (i=0; i < signaling_responses_pending; i++){
771f53da564S[email protected]             memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t));
772f53da564S[email protected]         }
773f53da564S[email protected] 
774f53da564S[email protected]         switch (response_code){
77509e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
7762b360848Smatthias.ringwald             case CONNECTION_REQUEST:
777e74c5f58SMatthias Ringwald                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
7782bd8b7e7S[email protected]                 // also disconnect if result is 0x0003 - security blocked
7794d816277S[email protected]                 if (result == 0x0003){
7802bd8b7e7S[email protected]                     hci_disconnect_security_block(handle);
7814d816277S[email protected]                 }
7822b360848Smatthias.ringwald                 break;
7832b83fb7dSmatthias.ringwald             case ECHO_REQUEST:
7842b83fb7dSmatthias.ringwald                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
7852b83fb7dSmatthias.ringwald                 break;
7862b83fb7dSmatthias.ringwald             case INFORMATION_REQUEST:
7873b0484b3S[email protected]                 switch (infoType){
7883b0484b3S[email protected]                     case 1: { // Connectionless MTU
7893b0484b3S[email protected]                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
7903b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(connectionless_mtu), &connectionless_mtu);
7913b0484b3S[email protected]                         }
792202c8a4cSMatthias Ringwald                         break;
7933b0484b3S[email protected]                     case 2: {  // Extended Features Supported
7941b9cb13dSMatthias Ringwald                             uint32_t features = l2cap_extended_features_mask();
7953b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(features), &features);
7963b0484b3S[email protected]                         }
797202c8a4cSMatthias Ringwald                         break;
7983b0484b3S[email protected]                     case 3: { // Fixed Channels Supported
7993b0484b3S[email protected]                             uint8_t map[8];
8003b0484b3S[email protected]                             memset(map, 0, 8);
801288636a2SMatthias Ringwald                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
8023b0484b3S[email protected]                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 0, sizeof(map), &map);
8033b0484b3S[email protected]                         }
804202c8a4cSMatthias Ringwald                         break;
8053b0484b3S[email protected]                     default:
8062b83fb7dSmatthias.ringwald                         // all other types are not supported
8072b83fb7dSmatthias.ringwald                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, infoType, 1, 0, NULL);
8083b0484b3S[email protected]                         break;
8092b83fb7dSmatthias.ringwald                 }
8102b83fb7dSmatthias.ringwald                 break;
81163a7246aSmatthias.ringwald             case COMMAND_REJECT:
8125ca8d57bS[email protected]                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
81363f0ac45SMatthias Ringwald                 break;
81409e9d05bSMatthias Ringwald #endif
815a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
81663f0ac45SMatthias Ringwald             case LE_CREDIT_BASED_CONNECTION_REQUEST:
81763f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
81863f0ac45SMatthias Ringwald                 break;
81970efece1S[email protected]             case COMMAND_REJECT_LE:
82070efece1S[email protected]                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
82163a7246aSmatthias.ringwald                 break;
82270efece1S[email protected] #endif
8232b83fb7dSmatthias.ringwald             default:
8242b83fb7dSmatthias.ringwald                 // should not happen
8252b83fb7dSmatthias.ringwald                 break;
8262b83fb7dSmatthias.ringwald         }
8272b83fb7dSmatthias.ringwald     }
8282b83fb7dSmatthias.ringwald 
829665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
830f3963406SMatthias Ringwald     UNUSED(it);
83109e9d05bSMatthias Ringwald 
8321b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
8331b9cb13dSMatthias Ringwald     // send l2cap information request if neccessary
8341b9cb13dSMatthias Ringwald     hci_connections_get_iterator(&it);
8351b9cb13dSMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
8361b9cb13dSMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
8371b9cb13dSMatthias Ringwald         if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST){
8381b9cb13dSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
8391b9cb13dSMatthias Ringwald             // send information request for extended features
8401b9cb13dSMatthias Ringwald             uint8_t sig_id = l2cap_next_sig_id();
8411b9cb13dSMatthias Ringwald             uint8_t info_type = 2;
8421b9cb13dSMatthias Ringwald             l2cap_send_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
8431b9cb13dSMatthias Ringwald             return;
8441b9cb13dSMatthias Ringwald         }
8451b9cb13dSMatthias Ringwald     }
8461b9cb13dSMatthias Ringwald #endif
8471b9cb13dSMatthias Ringwald 
84809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
84943ec931dSMatthias Ringwald     uint8_t  config_options[10];
850665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
851665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
852baf94f06S[email protected] 
853665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
85422c29ab4SMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
8552cd0be45Smatthias.ringwald         switch (channel->state){
8562cd0be45Smatthias.ringwald 
857df3354fcS[email protected]             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
858ad671560S[email protected]             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
859fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
860a00031e2S[email protected]                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
861ad671560S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
862fc64f94aSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
863ad671560S[email protected]                 }
864ad671560S[email protected]                 break;
865ad671560S[email protected] 
86602b22dc4Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
867baf94f06S[email protected]                 if (!hci_can_send_command_packet_now()) break;
86864472d52Smatthias.ringwald                 // send connection request - set state first
86964472d52Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
87002b22dc4Smatthias.ringwald                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
8718f8108aaSmatthias.ringwald                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
87202b22dc4Smatthias.ringwald                 break;
87302b22dc4Smatthias.ringwald 
874e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
875fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
87622c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
877fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
878e7ff783cSmatthias.ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
8799dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
880665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
881d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
882e7ff783cSmatthias.ringwald                 break;
883e7ff783cSmatthias.ringwald 
884552d92a1Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
885fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
886fa8473a4Smatthias.ringwald                 channel->state = L2CAP_STATE_CONFIG;
88728ca2b46S[email protected]                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
888fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
889552d92a1Smatthias.ringwald                 break;
890552d92a1Smatthias.ringwald 
8916fdcc387Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
892fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
8936fdcc387Smatthias.ringwald                 // success, start l2cap handshake
894b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
8956fdcc387Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
896fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
8975932bd7cS[email protected]                 l2cap_start_rtx(channel);
8986fdcc387Smatthias.ringwald                 break;
8996fdcc387Smatthias.ringwald 
900fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
901fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
90273cf2b3dSmatthias.ringwald                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
90363a7246aSmatthias.ringwald                     uint16_t flags = 0;
90428ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
90563a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
90663a7246aSmatthias.ringwald                         flags = 1;
90763a7246aSmatthias.ringwald                     } else {
90828ca2b46S[email protected]                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
90963a7246aSmatthias.ringwald                     }
91063a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
911ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
912fc64f94aSMatthias 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);
913ac8f1300SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
914ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
915ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
916ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
9176dca2a0cSMatthias Ringwald                         uint16_t options_size = l2cap_setup_options(channel, config_options);
918ac8f1300SMatthias 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);
919ac8f1300SMatthias Ringwald #endif
920ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
92163a7246aSmatthias.ringwald                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
922ac8f1300SMatthias Ringwald                         uint16_t options_size = l2cap_setup_options(channel, config_options);
923ac8f1300SMatthias 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);
92463a7246aSmatthias.ringwald                     } else {
925ac8f1300SMatthias Ringwald                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
92663a7246aSmatthias.ringwald                     }
92763a7246aSmatthias.ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
928fa8473a4Smatthias.ringwald                 }
92973cf2b3dSmatthias.ringwald                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
93028ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
93128ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
932b1988dceSmatthias.ringwald                     channel->local_sig_id = l2cap_next_sig_id();
9336dca2a0cSMatthias Ringwald                     uint16_t options_size = l2cap_setup_options(channel, config_options);
9346dca2a0cSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options);
9355932bd7cS[email protected]                     l2cap_start_rtx(channel);
936fa8473a4Smatthias.ringwald                 }
937fa8473a4Smatthias.ringwald                 if (l2cap_channel_ready_for_open(channel)){
938552d92a1Smatthias.ringwald                     channel->state = L2CAP_STATE_OPEN;
939552d92a1Smatthias.ringwald                     l2cap_emit_channel_opened(channel, 0);  // success
940fa8473a4Smatthias.ringwald                 }
941552d92a1Smatthias.ringwald                 break;
942552d92a1Smatthias.ringwald 
943e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
944fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
94522c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
946fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
9475932bd7cS[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 :)
948756102d3Smatthias.ringwald                 l2cap_finialize_channel_close(channel);  // -- remove from list
949e7ff783cSmatthias.ringwald                 break;
950e7ff783cSmatthias.ringwald 
951e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
952fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
953b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
9542cd0be45Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
955fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
9562cd0be45Smatthias.ringwald                 break;
9572cd0be45Smatthias.ringwald             default:
9582cd0be45Smatthias.ringwald                 break;
9592cd0be45Smatthias.ringwald         }
96038f62777SMatthias Ringwald 
96138f62777SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
96238f62777SMatthias Ringwald         // send s-frame to acknowledge received packets
96338f62777SMatthias Ringwald         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
964675e6881SMatthias Ringwald 
965675e6881SMatthias Ringwald         if (channel->tx_send_index != channel->tx_write_index){
966212b6be2SMatthias Ringwald             int unacknowledged_packets = l2cap_ertm_num_unacknowledged_tx_packets(channel);
967212b6be2SMatthias Ringwald             // check remote tx window
968212b6be2SMatthias Ringwald             log_info("unacknowledged_packets %u, remote tx window size %u", unacknowledged_packets, channel->remote_tx_window_size);
969212b6be2SMatthias Ringwald             if (unacknowledged_packets < channel->remote_tx_window_size){
970675e6881SMatthias Ringwald                 int index = channel->tx_send_index;
971675e6881SMatthias Ringwald                 channel->tx_send_index++;
972675e6881SMatthias Ringwald                 if (channel->tx_send_index >= channel->num_tx_buffers){
973675e6881SMatthias Ringwald                     channel->tx_send_index = 0;
974675e6881SMatthias Ringwald                 }
975675e6881SMatthias Ringwald                 l2cap_ertm_send_information_frame(channel, index);
976675e6881SMatthias Ringwald                 continue;
977675e6881SMatthias Ringwald             }
978212b6be2SMatthias Ringwald         }
979675e6881SMatthias Ringwald 
980d84e866fSMatthias Ringwald         if (channel->send_supervisor_frame_receiver_ready){
981*78cd8a22SMatthias Ringwald             channel->send_supervisor_frame_receiver_ready = 0;
982d84e866fSMatthias Ringwald             log_info("Send S-Frame: RR %u", channel->req_seq);
98338f62777SMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 0, 0, channel->req_seq);
98438f62777SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
985675e6881SMatthias Ringwald             continue;
98638f62777SMatthias Ringwald         }
98762041d70SMatthias Ringwald         if (channel->send_supervisor_frame_receiver_ready_poll){
988*78cd8a22SMatthias Ringwald             channel->send_supervisor_frame_receiver_ready_poll = 0;
98962041d70SMatthias Ringwald             log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
99062041d70SMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
99162041d70SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
99262041d70SMatthias Ringwald             continue;
99362041d70SMatthias Ringwald         }
994*78cd8a22SMatthias Ringwald         if (channel->send_supervisor_frame_receiver_ready_final){
995*78cd8a22SMatthias Ringwald             channel->send_supervisor_frame_receiver_ready_final = 0;
996*78cd8a22SMatthias Ringwald             log_info("Send S-Frame: RR %u with final=1 ", channel->req_seq);
997*78cd8a22SMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 0, 1, channel->req_seq);
998*78cd8a22SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
999*78cd8a22SMatthias Ringwald             continue;
1000*78cd8a22SMatthias Ringwald         }
10018f1c9639SMatthias Ringwald         if (channel->send_supervisor_frame_receiver_not_ready){
1002*78cd8a22SMatthias Ringwald             channel->send_supervisor_frame_receiver_not_ready = 0;
10038f1c9639SMatthias Ringwald             log_info("Send S-Frame: RNR %u", channel->req_seq);
10048f1c9639SMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
10058f1c9639SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
10068f1c9639SMatthias Ringwald             continue;
10078f1c9639SMatthias Ringwald         }
100838f62777SMatthias Ringwald #endif
100938f62777SMatthias Ringwald 
10102cd0be45Smatthias.ringwald     }
101109e9d05bSMatthias Ringwald #endif
1012da886c03S[email protected] 
1013cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1014efedfb4cSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1015efedfb4cSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
10167f107edaSMatthias Ringwald         uint8_t  * acl_buffer;
10177f107edaSMatthias Ringwald         uint8_t  * l2cap_payload;
10187f107edaSMatthias Ringwald         uint16_t pos;
10197f107edaSMatthias Ringwald         uint16_t payload_size;
1020efedfb4cSMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1021efedfb4cSMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1022efedfb4cSMatthias Ringwald         switch (channel->state){
10235cb87675SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
10245cb87675SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
10255cb87675SMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
10265cb87675SMatthias Ringwald                 // le psm, source cid, mtu, mps, initial credits
10271b8b8d05SMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
102863f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
102963f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
103063f0ac45SMatthias 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);
10315cb87675SMatthias Ringwald                 break;
103223017473SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
103323017473SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
103423017473SMatthias Ringwald                 // TODO: support larger MPS
103523017473SMatthias Ringwald                 channel->state = L2CAP_STATE_OPEN;
103663f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
103763f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
103863f0ac45SMatthias 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);
103964e11ca9SMatthias Ringwald                 // notify client
104044276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0);
104123017473SMatthias Ringwald                 break;
1042e7d0c9aaSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
1043e7d0c9aaSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1044e7d0c9aaSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
104563f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
1046e7d0c9aaSMatthias Ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1047e7d0c9aaSMatthias Ringwald                 l2cap_stop_rtx(channel);
1048e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1049e7d0c9aaSMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
1050e7d0c9aaSMatthias Ringwald                 break;
10517f107edaSMatthias Ringwald             case L2CAP_STATE_OPEN:
105285aeef60SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
105385aeef60SMatthias Ringwald 
105485aeef60SMatthias Ringwald                 // send credits
105585aeef60SMatthias Ringwald                 if (channel->new_credits_incoming){
105685aeef60SMatthias Ringwald                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
105785aeef60SMatthias Ringwald                     channel->local_sig_id = l2cap_next_sig_id();
105885aeef60SMatthias Ringwald                     uint16_t new_credits = channel->new_credits_incoming;
105985aeef60SMatthias Ringwald                     channel->new_credits_incoming = 0;
106085aeef60SMatthias Ringwald                     channel->credits_incoming += new_credits;
106185aeef60SMatthias Ringwald                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
106285aeef60SMatthias Ringwald                     break;
106385aeef60SMatthias Ringwald                 }
106485aeef60SMatthias Ringwald 
106585aeef60SMatthias Ringwald                 // send data
10667f107edaSMatthias Ringwald                 if (!channel->send_sdu_buffer) break;
10677f107edaSMatthias Ringwald                 if (!channel->credits_outgoing) break;
106885aeef60SMatthias Ringwald 
10697f107edaSMatthias Ringwald                 // send part of SDU
10707f107edaSMatthias Ringwald                 hci_reserve_packet_buffer();
10717f107edaSMatthias Ringwald                 acl_buffer = hci_get_outgoing_packet_buffer();
10727f107edaSMatthias Ringwald                 l2cap_payload = acl_buffer + 8;
10737f107edaSMatthias Ringwald                 pos = 0;
10747f107edaSMatthias Ringwald                 if (!channel->send_sdu_pos){
10757f107edaSMatthias Ringwald                     // store SDU len
10767f107edaSMatthias Ringwald                     channel->send_sdu_pos += 2;
10777f107edaSMatthias Ringwald                     little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
10787f107edaSMatthias Ringwald                     pos += 2;
10797f107edaSMatthias Ringwald                 }
10807f107edaSMatthias Ringwald                 payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
108185aeef60SMatthias Ringwald                 log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
10827f107edaSMatthias Ringwald                 memcpy(&l2cap_payload[pos], &channel->send_sdu_buffer[channel->send_sdu_pos-2], payload_size); // -2 for virtual SDU len
10837f107edaSMatthias Ringwald                 pos += payload_size;
10847f107edaSMatthias Ringwald                 channel->send_sdu_pos += payload_size;
1085f511cefaSMatthias Ringwald                 l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
10867f107edaSMatthias Ringwald                 // done
10877f107edaSMatthias Ringwald 
108885aeef60SMatthias Ringwald                 channel->credits_outgoing--;
10897f107edaSMatthias Ringwald 
10907f107edaSMatthias Ringwald                 if (channel->send_sdu_pos >= channel->send_sdu_len + 2){
10917f107edaSMatthias Ringwald                     channel->send_sdu_buffer = NULL;
109244276248SMatthias Ringwald                     // send done event
109344276248SMatthias Ringwald                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
109444276248SMatthias Ringwald                     // inform about can send now
109544276248SMatthias Ringwald                     l2cap_le_notify_channel_can_send(channel);
10967f107edaSMatthias Ringwald                 }
10977f107edaSMatthias Ringwald                 hci_send_acl_packet_buffer(8 + pos);
10987f107edaSMatthias Ringwald                 break;
1099828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1100828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1101828a7f7aSMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
1102828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1103828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1104828a7f7aSMatthias Ringwald                 break;
1105828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1106828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1107828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1108828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1109828a7f7aSMatthias Ringwald                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
1110828a7f7aSMatthias Ringwald                 break;
1111efedfb4cSMatthias Ringwald             default:
1112efedfb4cSMatthias Ringwald                 break;
1113efedfb4cSMatthias Ringwald         }
1114efedfb4cSMatthias Ringwald     }
111509e9d05bSMatthias Ringwald #endif
1116efedfb4cSMatthias Ringwald 
111709e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
1118da886c03S[email protected]     // send l2cap con paramter update if necessary
1119da886c03S[email protected]     hci_connections_get_iterator(&it);
1120665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
1121665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
11225d14fa8fSMatthias Ringwald         if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue;
1123b68d7bc3SMatthias Ringwald         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
1124da886c03S[email protected]         switch (connection->le_con_parameter_update_state){
1125b68d7bc3SMatthias Ringwald             case CON_PARAMETER_UPDATE_SEND_REQUEST:
1126b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1127b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier,
1128b68d7bc3SMatthias Ringwald                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
1129b68d7bc3SMatthias Ringwald                 break;
1130da886c03S[email protected]             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
1131b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
1132b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
1133da886c03S[email protected]                 break;
1134da886c03S[email protected]             case CON_PARAMETER_UPDATE_DENY:
1135b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1136b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
1137da886c03S[email protected]                 break;
1138da886c03S[email protected]             default:
1139da886c03S[email protected]                 break;
1140da886c03S[email protected]         }
1141da886c03S[email protected]     }
11424d7157c3S[email protected] #endif
1143da886c03S[email protected] 
114422c29ab4SMatthias Ringwald     // log_info("l2cap_run: exit");
11452cd0be45Smatthias.ringwald }
11462cd0be45Smatthias.ringwald 
114709e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1148fc64f94aSMatthias Ringwald static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
11492df5dadcS[email protected]     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
11505533f01eS[email protected]         log_info("l2cap_handle_connection_complete expected state");
11512df5dadcS[email protected]         // success, start l2cap handshake
1152fc64f94aSMatthias Ringwald         channel->con_handle = con_handle;
11532df5dadcS[email protected]         // check remote SSP feature first
11542df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
11552df5dadcS[email protected]     }
11562df5dadcS[email protected] }
11572df5dadcS[email protected] 
11581b9cb13dSMatthias Ringwald static void l2cap_ready_to_connect(l2cap_channel_t * channel){
11591b9cb13dSMatthias Ringwald 
11601b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
116127e0774aSMatthias Ringwald     // assumption: outgoing connection
11621b9cb13dSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
11631b9cb13dSMatthias Ringwald     if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
11641b9cb13dSMatthias Ringwald         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
11651b9cb13dSMatthias Ringwald         channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
11661b9cb13dSMatthias Ringwald         return;
11671b9cb13dSMatthias Ringwald     }
11681b9cb13dSMatthias Ringwald #endif
11691b9cb13dSMatthias Ringwald 
11701b9cb13dSMatthias Ringwald     // fine, go ahead
11711b9cb13dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
11721b9cb13dSMatthias Ringwald }
11731b9cb13dSMatthias Ringwald 
11742df5dadcS[email protected] static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
11752df5dadcS[email protected]     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
11762df5dadcS[email protected] 
11772df5dadcS[email protected]     // we have been waiting for remote supported features, if both support SSP,
1178ac301f95S[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));
1179fc64f94aSMatthias Ringwald     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
11802df5dadcS[email protected]         // request security level 2
11812df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
1182fc64f94aSMatthias Ringwald         gap_request_security_level(channel->con_handle, LEVEL_2);
11832df5dadcS[email protected]         return;
11842df5dadcS[email protected]     }
11851b9cb13dSMatthias Ringwald 
11861b9cb13dSMatthias Ringwald     l2cap_ready_to_connect(channel);
11872df5dadcS[email protected] }
118809e9d05bSMatthias Ringwald #endif
11892df5dadcS[email protected] 
119009e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
1191da144af5SMatthias 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,
1192da144af5SMatthias Ringwald     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
1193da144af5SMatthias Ringwald 
1194da144af5SMatthias Ringwald     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1195da144af5SMatthias Ringwald     if (!channel) {
1196da144af5SMatthias Ringwald         return NULL;
1197da144af5SMatthias Ringwald     }
1198da144af5SMatthias Ringwald 
1199da144af5SMatthias Ringwald      // Init memory (make valgrind happy)
1200da144af5SMatthias Ringwald     memset(channel, 0, sizeof(l2cap_channel_t));
1201da144af5SMatthias Ringwald 
1202da144af5SMatthias Ringwald     // fill in
1203da144af5SMatthias Ringwald     channel->packet_handler = packet_handler;
1204da144af5SMatthias Ringwald     bd_addr_copy(channel->address, address);
1205da144af5SMatthias Ringwald     channel->address_type = address_type;
1206da144af5SMatthias Ringwald     channel->psm = psm;
1207da144af5SMatthias Ringwald     channel->local_mtu  = local_mtu;
1208da144af5SMatthias Ringwald     channel->remote_mtu = L2CAP_MINIMAL_MTU;
1209da144af5SMatthias Ringwald     channel->required_security_level = security_level;
1210da144af5SMatthias Ringwald 
1211da144af5SMatthias Ringwald     //
1212da144af5SMatthias Ringwald     channel->local_cid = l2cap_next_local_cid();
1213da144af5SMatthias Ringwald     channel->con_handle = 0;
1214da144af5SMatthias Ringwald 
1215da144af5SMatthias Ringwald     // set initial state
1216da144af5SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
1217da144af5SMatthias Ringwald     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
1218da144af5SMatthias Ringwald     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
1219da144af5SMatthias Ringwald     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
122038f62777SMatthias Ringwald 
1221da144af5SMatthias Ringwald     return channel;
1222da144af5SMatthias Ringwald }
122309e9d05bSMatthias Ringwald #endif
122409e9d05bSMatthias Ringwald 
122509e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1226da144af5SMatthias Ringwald 
12279077cb15SMatthias Ringwald /**
12289077cb15SMatthias Ringwald  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
12299077cb15SMatthias Ringwald  * @param packet_handler
12309077cb15SMatthias Ringwald  * @param address
12319077cb15SMatthias Ringwald  * @param psm
12329077cb15SMatthias Ringwald  * @param mtu
12339077cb15SMatthias Ringwald  * @param local_cid
12349077cb15SMatthias Ringwald  */
12359077cb15SMatthias Ringwald 
12369d139fbaSMatthias 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){
12379d139fbaSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
12389d139fbaSMatthias Ringwald     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1239da144af5SMatthias Ringwald 
12409d139fbaSMatthias 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);
1241da144af5SMatthias Ringwald 
1242da144af5SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
1243fc64f94aSMatthias Ringwald     if (!channel) {
12449077cb15SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
12459077cb15SMatthias Ringwald     }
12469077cb15SMatthias Ringwald 
12471b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
12481b9cb13dSMatthias Ringwald     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
12491b9cb13dSMatthias Ringwald #endif
12501b9cb13dSMatthias Ringwald 
12519077cb15SMatthias Ringwald     // add to connections list
1252fc64f94aSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
12539077cb15SMatthias Ringwald 
12549077cb15SMatthias Ringwald     // store local_cid
12559077cb15SMatthias Ringwald     if (out_local_cid){
1256fc64f94aSMatthias Ringwald        *out_local_cid = channel->local_cid;
12579077cb15SMatthias Ringwald     }
12589077cb15SMatthias Ringwald 
12599077cb15SMatthias Ringwald     // check if hci connection is already usable
12609077cb15SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
12619077cb15SMatthias Ringwald     if (conn){
1262add0254bSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
1263fc64f94aSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
12649077cb15SMatthias Ringwald         // check if remote supported fearures are already received
12659077cb15SMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
1266fc64f94aSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
12679077cb15SMatthias Ringwald         }
12689077cb15SMatthias Ringwald     }
12699077cb15SMatthias Ringwald 
12709077cb15SMatthias Ringwald     l2cap_run();
12719077cb15SMatthias Ringwald 
12729077cb15SMatthias Ringwald     return 0;
12739077cb15SMatthias Ringwald }
12749077cb15SMatthias Ringwald 
12751b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
12767b181629SMatthias Ringwald 
12772b70d705SMatthias Ringwald static uint8_t l2cap_ertm_validate_local_config(uint8_t max_transmit, uint16_t retransmission_timeout_ms,
12782b70d705SMatthias Ringwald     uint16_t monitor_timeout_ms, uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size){
12792b70d705SMatthias Ringwald     UNUSED(buffer);
12802b70d705SMatthias Ringwald     UNUSED(size);
12812b70d705SMatthias Ringwald 
12822b70d705SMatthias Ringwald     uint8_t result = ERROR_CODE_SUCCESS;
12832b70d705SMatthias Ringwald     if (max_transmit < 1){
12842b70d705SMatthias Ringwald         log_error("max_transmit must be >= 1");
12852b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
12862b70d705SMatthias Ringwald     }
12872b70d705SMatthias Ringwald     if (retransmission_timeout_ms < 2000){
12882b70d705SMatthias Ringwald         log_error("retransmission_timeout_ms must be >= 2000 ms");
12892b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
12902b70d705SMatthias Ringwald     }
12912b70d705SMatthias Ringwald     if (monitor_timeout_ms < 12000){
12922b70d705SMatthias Ringwald         log_error("monitor_timeout_ms must be >= 12000 ms");
12932b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
12942b70d705SMatthias Ringwald     }
12952b70d705SMatthias Ringwald     if (num_rx_buffers < 1){
12962b70d705SMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
12972b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
12982b70d705SMatthias Ringwald     }
12992b70d705SMatthias Ringwald     if (num_tx_buffers < 1){
13002b70d705SMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
13012b70d705SMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
13022b70d705SMatthias Ringwald     }
13032b70d705SMatthias Ringwald     return result;
13042b70d705SMatthias Ringwald }
13052b70d705SMatthias Ringwald 
13067b181629SMatthias Ringwald static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, int ertm_mandatory, uint8_t max_transmit,
13077b181629SMatthias 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){
13087b181629SMatthias Ringwald 
13097b181629SMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
13107b181629SMatthias Ringwald     channel->ertm_mandatory = ertm_mandatory;
1311bbc0a9e7SMatthias Ringwald     channel->local_max_transmit = max_transmit;
1312bbc0a9e7SMatthias Ringwald     channel->local_retransmission_timeout_ms = retransmission_timeout_ms;
1313bbc0a9e7SMatthias Ringwald     channel->local_monitor_timeout_ms = monitor_timeout_ms;
13147b181629SMatthias Ringwald     channel->num_rx_buffers = num_rx_buffers;
13157b181629SMatthias Ringwald     channel->num_tx_buffers = num_tx_buffers;
13167b181629SMatthias Ringwald 
13177b181629SMatthias Ringwald     // TODO: align buffer pointer
13187b181629SMatthias Ringwald     uint32_t pos = 0;
13197b181629SMatthias Ringwald     channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) &buffer[pos];
13207b181629SMatthias Ringwald     pos += num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
13217b181629SMatthias Ringwald     channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) &buffer[pos];
13227b181629SMatthias Ringwald     pos += num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
13237b181629SMatthias Ringwald     // calculate MTU
13247b181629SMatthias Ringwald     channel->local_mtu = (size - pos) / (num_rx_buffers + num_tx_buffers);
13257b181629SMatthias Ringwald     log_info("Local ERTM MTU: %u", channel->local_mtu);
13267b181629SMatthias Ringwald     channel->rx_packets_data = &buffer[pos];
13277b181629SMatthias Ringwald     pos += num_rx_buffers * channel->local_mtu;
13287b181629SMatthias Ringwald     channel->tx_packets_data = &buffer[pos];
13297b181629SMatthias Ringwald     log_info("RX packets %p, TX packets %p", channel->rx_packets_data, channel->tx_packets_data);
13307b181629SMatthias Ringwald }
13317b181629SMatthias Ringwald 
1332501329faSMatthias Ringwald uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
1333501329faSMatthias Ringwald     int ertm_mandatory, uint8_t max_transmit, uint16_t retransmission_timeout_ms, uint16_t monitor_timeout_ms,
1334501329faSMatthias Ringwald     uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
1335501329faSMatthias Ringwald 
13361b9cb13dSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
1337501329faSMatthias Ringwald     uint16_t local_mtu = l2cap_max_mtu();
13381b9cb13dSMatthias Ringwald 
1339501329faSMatthias Ringwald     log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x -> local mtu %u", bd_addr_to_str(address), psm, local_mtu);
13401b9cb13dSMatthias Ringwald 
13412b70d705SMatthias Ringwald     // validate local config
13422b70d705SMatthias 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);
13432b70d705SMatthias Ringwald     if (result) return result;
13442b70d705SMatthias Ringwald 
1345501329faSMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
13461b9cb13dSMatthias Ringwald     if (!channel) {
13471b9cb13dSMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
13481b9cb13dSMatthias Ringwald     }
13491b9cb13dSMatthias Ringwald 
13507b181629SMatthias Ringwald     // configure ERTM
13517b181629SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_mandatory, max_transmit, retransmission_timeout_ms,
13527b181629SMatthias Ringwald         monitor_timeout_ms, num_tx_buffers, num_rx_buffers, buffer, size);
13531b9cb13dSMatthias Ringwald 
13541b9cb13dSMatthias Ringwald     // add to connections list
13551b9cb13dSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
13561b9cb13dSMatthias Ringwald 
13571b9cb13dSMatthias Ringwald     // store local_cid
13581b9cb13dSMatthias Ringwald     if (out_local_cid){
13591b9cb13dSMatthias Ringwald        *out_local_cid = channel->local_cid;
13601b9cb13dSMatthias Ringwald     }
13611b9cb13dSMatthias Ringwald 
13621b9cb13dSMatthias Ringwald     // check if hci connection is already usable
13631b9cb13dSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
13641b9cb13dSMatthias Ringwald     if (conn){
13651b9cb13dSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
13661b9cb13dSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
13671b9cb13dSMatthias Ringwald         // check if remote supported fearures are already received
13681b9cb13dSMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
13691b9cb13dSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
13701b9cb13dSMatthias Ringwald         }
13711b9cb13dSMatthias Ringwald     }
13721b9cb13dSMatthias Ringwald 
13731b9cb13dSMatthias Ringwald     l2cap_run();
13741b9cb13dSMatthias Ringwald 
13751b9cb13dSMatthias Ringwald     return 0;
13761b9cb13dSMatthias Ringwald }
13771b9cb13dSMatthias Ringwald #endif
13781b9cb13dSMatthias Ringwald 
1379ce8f182eSMatthias Ringwald void
1380ce8f182eSMatthias Ringwald l2cap_disconnect(uint16_t local_cid, uint8_t reason){
1381e0abb8e7S[email protected]     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
1382b35f641cSmatthias.ringwald     // find channel for local_cid
1383b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1384f62db1e3Smatthias.ringwald     if (channel) {
1385e7ff783cSmatthias.ringwald         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1386f62db1e3Smatthias.ringwald     }
13872cd0be45Smatthias.ringwald     // process
13882cd0be45Smatthias.ringwald     l2cap_run();
138943625864Smatthias.ringwald }
13901e6aba47Smatthias.ringwald 
1391afde0c52Smatthias.ringwald static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
1392665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1393665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1394665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1395665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1396058e3d6bSMatthias Ringwald         if ( bd_addr_cmp( channel->address, address) != 0) continue;
1397c22aecc9S[email protected]         // channel for this address found
1398c22aecc9S[email protected]         switch (channel->state){
1399c22aecc9S[email protected]             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
1400c22aecc9S[email protected]             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1401afde0c52Smatthias.ringwald                 // failure, forward error code
1402afde0c52Smatthias.ringwald                 l2cap_emit_channel_opened(channel, status);
1403afde0c52Smatthias.ringwald                 // discard channel
14049dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
1405665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1406d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
1407c22aecc9S[email protected]                 break;
1408c22aecc9S[email protected]             default:
1409c22aecc9S[email protected]                 break;
1410afde0c52Smatthias.ringwald         }
1411afde0c52Smatthias.ringwald     }
1412afde0c52Smatthias.ringwald }
1413afde0c52Smatthias.ringwald 
1414afde0c52Smatthias.ringwald static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
1415665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1416665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1417665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1418665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1419058e3d6bSMatthias Ringwald         if ( ! bd_addr_cmp( channel->address, address) ){
14202df5dadcS[email protected]             l2cap_handle_connection_complete(handle, channel);
1421afde0c52Smatthias.ringwald         }
1422afde0c52Smatthias.ringwald     }
14236fdcc387Smatthias.ringwald     // process
14246fdcc387Smatthias.ringwald     l2cap_run();
1425afde0c52Smatthias.ringwald }
142609e9d05bSMatthias Ringwald #endif
1427b448a0e7Smatthias.ringwald 
142833c40538SMatthias Ringwald static void l2cap_notify_channel_can_send(void){
142909e9d05bSMatthias Ringwald 
143009e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
143133c40538SMatthias Ringwald     btstack_linked_list_iterator_t it;
143233c40538SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
143333c40538SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
143433c40538SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
143533c40538SMatthias Ringwald         if (!channel->waiting_for_can_send_now) continue;
1436fc64f94aSMatthias Ringwald         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
143733c40538SMatthias Ringwald         channel->waiting_for_can_send_now = 0;
143834e7e577SMatthias Ringwald         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
143933c40538SMatthias Ringwald     }
144009e9d05bSMatthias Ringwald #endif
144144276248SMatthias Ringwald 
14422125de09SMatthias Ringwald     int i;
14432125de09SMatthias Ringwald     for (i=0;i<L2CAP_FIXED_CHANNEL_TABLE_SIZE;i++){
1444773c4106SMatthias Ringwald         if (!fixed_channels[i].callback) continue;
14452125de09SMatthias Ringwald         if (!fixed_channels[i].waiting_for_can_send_now) continue;
144635454696SMatthias Ringwald         int can_send = 0;
144734e7e577SMatthias Ringwald         if (l2cap_fixed_channel_table_index_is_le(i)){
144835454696SMatthias Ringwald #ifdef ENABLE_BLE
144934e7e577SMatthias Ringwald             can_send = hci_can_send_acl_le_packet_now();
145035454696SMatthias Ringwald #endif
145134e7e577SMatthias Ringwald         } else {
145235454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
145334e7e577SMatthias Ringwald             can_send = hci_can_send_acl_classic_packet_now();
145435454696SMatthias Ringwald #endif
145534e7e577SMatthias Ringwald         }
145634e7e577SMatthias Ringwald         if (!can_send) continue;
145734e7e577SMatthias Ringwald         fixed_channels[i].waiting_for_can_send_now = 0;
145834e7e577SMatthias Ringwald         l2cap_emit_can_send_now(fixed_channels[i].callback, l2cap_fixed_channel_table_channel_id_for_index(i));
14592125de09SMatthias Ringwald     }
146033c40538SMatthias Ringwald }
146133c40538SMatthias Ringwald 
1462d9a7306aSMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
1463afde0c52Smatthias.ringwald 
14649ec2630cSMatthias Ringwald     UNUSED(packet_type);
14659ec2630cSMatthias Ringwald     UNUSED(cid);
14669ec2630cSMatthias Ringwald     UNUSED(size);
14679ec2630cSMatthias Ringwald 
1468afde0c52Smatthias.ringwald     bd_addr_t address;
1469afde0c52Smatthias.ringwald     hci_con_handle_t handle;
14702d00edd4Smatthias.ringwald     int hci_con_used;
147109e9d05bSMatthias Ringwald     btstack_linked_list_iterator_t it;
147209e9d05bSMatthias Ringwald 
147309e9d05bSMatthias Ringwald     // avoid unused warnings
1474f3963406SMatthias Ringwald     UNUSED(address);
1475f3963406SMatthias Ringwald     UNUSED(hci_con_used);
1476f3963406SMatthias Ringwald     UNUSED(it);
1477f22209dfSMatthias Ringwald     UNUSED(handle);
1478afde0c52Smatthias.ringwald 
14790e2df43fSMatthias Ringwald     switch(hci_event_packet_get_type(packet)){
1480afde0c52Smatthias.ringwald 
148109e9d05bSMatthias Ringwald         // Notify channel packet handler if they can send now
148209e9d05bSMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
148309e9d05bSMatthias Ringwald         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
148409e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
148509e9d05bSMatthias Ringwald             l2cap_notify_channel_can_send();
148609e9d05bSMatthias Ringwald             break;
148709e9d05bSMatthias Ringwald 
148809e9d05bSMatthias Ringwald         case HCI_EVENT_COMMAND_STATUS:
148909e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
149009e9d05bSMatthias Ringwald             break;
149109e9d05bSMatthias Ringwald 
149209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1493afde0c52Smatthias.ringwald         // handle connection complete events
1494afde0c52Smatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
1495724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], address);
1496afde0c52Smatthias.ringwald             if (packet[2] == 0){
1497f8fbdce0SMatthias Ringwald                 handle = little_endian_read_16(packet, 3);
1498afde0c52Smatthias.ringwald                 l2cap_handle_connection_success_for_addr(address, handle);
1499afde0c52Smatthias.ringwald             } else {
1500afde0c52Smatthias.ringwald                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
1501afde0c52Smatthias.ringwald             }
1502afde0c52Smatthias.ringwald             break;
1503afde0c52Smatthias.ringwald 
1504afde0c52Smatthias.ringwald         // handle successful create connection cancel command
1505afde0c52Smatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
1506073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
1507afde0c52Smatthias.ringwald                 if (packet[5] == 0){
1508724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[6], address);
1509afde0c52Smatthias.ringwald                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
1510afde0c52Smatthias.ringwald                     l2cap_handle_connection_failed_for_addr(address, 0x16);
151103cfbabcSmatthias.ringwald                 }
15121e6aba47Smatthias.ringwald             }
151339d59809Smatthias.ringwald             l2cap_run();    // try sending signaling packets first
151439d59809Smatthias.ringwald             break;
151509e9d05bSMatthias Ringwald #endif
151627a923d0Smatthias.ringwald 
15171e6aba47Smatthias.ringwald         // handle disconnection complete events
1518afde0c52Smatthias.ringwald         case HCI_EVENT_DISCONNECTION_COMPLETE:
1519c22aecc9S[email protected]             // send l2cap disconnect events for all channels on this handle and free them
152009e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1521d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1522665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1523665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1524665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1525fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
152615ec09bbSmatthias.ringwald                 l2cap_emit_channel_closed(channel);
15279dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
1528665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1529d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
153027a923d0Smatthias.ringwald             }
153109e9d05bSMatthias Ringwald #endif
1532a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1533d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1534991fea48SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1535991fea48SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1536991fea48SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1537991fea48SMatthias Ringwald                 if (channel->con_handle != handle) continue;
1538991fea48SMatthias Ringwald                 l2cap_emit_channel_closed(channel);
1539991fea48SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1540991fea48SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
1541991fea48SMatthias Ringwald             }
1542991fea48SMatthias Ringwald #endif
1543afde0c52Smatthias.ringwald             break;
1544fcadd0caSmatthias.ringwald 
1545ee091cf1Smatthias.ringwald         // HCI Connection Timeouts
154609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1547afde0c52Smatthias.ringwald         case L2CAP_EVENT_TIMEOUT_CHECK:
1548f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
1549bd04d84aSMatthias Ringwald             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
155080ca58a0Smatthias.ringwald             if (hci_authentication_active_for_handle(handle)) break;
15512d00edd4Smatthias.ringwald             hci_con_used = 0;
1552665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1553665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1554665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1555fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
15562d00edd4Smatthias.ringwald                 hci_con_used = 1;
1557c22aecc9S[email protected]                 break;
1558ee091cf1Smatthias.ringwald             }
15592d00edd4Smatthias.ringwald             if (hci_con_used) break;
1560d94d3cafS[email protected]             if (!hci_can_send_command_packet_now()) break;
15619edc8742Smatthias.ringwald             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
1562afde0c52Smatthias.ringwald             break;
1563ee091cf1Smatthias.ringwald 
1564df3354fcS[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1565f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
1566665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1567665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1568665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1569fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
15702df5dadcS[email protected]                 l2cap_handle_remote_supported_features_received(channel);
1571df3354fcS[email protected]                 break;
1572df3354fcS[email protected]             }
1573c22aecc9S[email protected]             break;
1574df3354fcS[email protected] 
15755611a760SMatthias Ringwald         case GAP_EVENT_SECURITY_LEVEL:
1576f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
1577bd63148eS[email protected]             log_info("l2cap - security level update");
1578665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
1579665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
1580665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1581fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
15825533f01eS[email protected] 
1583bd63148eS[email protected]                 log_info("l2cap - state %u", channel->state);
1584bd63148eS[email protected] 
1585e569dfd9SMatthias Ringwald                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
15865533f01eS[email protected]                 gap_security_level_t required_level = channel->required_security_level;
15875533f01eS[email protected] 
1588df3354fcS[email protected]                 switch (channel->state){
1589df3354fcS[email protected]                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
15905533f01eS[email protected]                         if (actual_level >= required_level){
159152606043SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
159252606043SMatthias Ringwald                             // we need to know if ERTM is supported before sending a config response
159352606043SMatthias Ringwald                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
159452606043SMatthias Ringwald                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
159552606043SMatthias Ringwald                             channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
159652606043SMatthias Ringwald #else
1597f85a9399S[email protected]                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
159844276248SMatthias Ringwald                             l2cap_emit_incoming_connection(channel);
159952606043SMatthias Ringwald #endif
16001eb2563eS[email protected]                         } else {
1601775ecc36SMatthias Ringwald                             channel->reason = 0x0003; // security block
16021eb2563eS[email protected]                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
16031eb2563eS[email protected]                         }
1604df3354fcS[email protected]                         break;
1605df3354fcS[email protected] 
1606df3354fcS[email protected]                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
16075533f01eS[email protected]                         if (actual_level >= required_level){
16081b9cb13dSMatthias Ringwald                             l2cap_ready_to_connect(channel);
1609df3354fcS[email protected]                         } else {
1610df3354fcS[email protected]                             // disconnnect, authentication not good enough
1611df3354fcS[email protected]                             hci_disconnect_security_block(handle);
1612df3354fcS[email protected]                         }
1613df3354fcS[email protected]                         break;
1614df3354fcS[email protected] 
1615df3354fcS[email protected]                     default:
1616df3354fcS[email protected]                         break;
1617df3354fcS[email protected]                 }
1618f85a9399S[email protected]             }
1619f85a9399S[email protected]             break;
162009e9d05bSMatthias Ringwald #endif
1621f85a9399S[email protected] 
1622afde0c52Smatthias.ringwald         default:
1623afde0c52Smatthias.ringwald             break;
1624afde0c52Smatthias.ringwald     }
1625afde0c52Smatthias.ringwald 
1626bd63148eS[email protected]     l2cap_run();
16271e6aba47Smatthias.ringwald }
16281e6aba47Smatthias.ringwald 
1629e74c5f58SMatthias 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){
16304cf56b4aSmatthias.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."
16312b360848Smatthias.ringwald     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
16322b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].handle = handle;
16332b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].code = code;
16342b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].sig_id = sig_id;
1635e74c5f58SMatthias Ringwald         signaling_responses[signaling_responses_pending].cid = cid;
16362b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].data = data;
16372b360848Smatthias.ringwald         signaling_responses_pending++;
16382b360848Smatthias.ringwald         l2cap_run();
16392b360848Smatthias.ringwald     }
16402b360848Smatthias.ringwald }
16412b360848Smatthias.ringwald 
164209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
164309e9d05bSMatthias Ringwald static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
164409e9d05bSMatthias Ringwald     channel->remote_sig_id = identifier;
164509e9d05bSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
164609e9d05bSMatthias Ringwald     l2cap_run();
164709e9d05bSMatthias Ringwald }
164809e9d05bSMatthias Ringwald 
1649b35f641cSmatthias.ringwald static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
1650645658c9Smatthias.ringwald 
16519da54300S[email protected]     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
1652645658c9Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
1653645658c9Smatthias.ringwald     if (!service) {
1654645658c9Smatthias.ringwald         // 0x0002 PSM not supported
1655e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
1656645658c9Smatthias.ringwald         return;
1657645658c9Smatthias.ringwald     }
1658645658c9Smatthias.ringwald 
16595061f3afS[email protected]     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
1660645658c9Smatthias.ringwald     if (!hci_connection) {
16612b360848Smatthias.ringwald         //
16629da54300S[email protected]         log_error("no hci_connection for handle %u", handle);
1663645658c9Smatthias.ringwald         return;
1664645658c9Smatthias.ringwald     }
16652bd8b7e7S[email protected] 
1666645658c9Smatthias.ringwald     // alloc structure
16679da54300S[email protected]     // log_info("l2cap_handle_connection_request register channel");
1668da144af5SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, hci_connection->address, BD_ADDR_TYPE_CLASSIC,
1669da144af5SMatthias Ringwald     psm, service->mtu, service->required_security_level);
16702b360848Smatthias.ringwald     if (!channel){
16712b360848Smatthias.ringwald         // 0x0004 No resources available
1672e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
16732b360848Smatthias.ringwald         return;
16742b360848Smatthias.ringwald     }
1675da144af5SMatthias Ringwald 
1676fc64f94aSMatthias Ringwald     channel->con_handle = handle;
1677b35f641cSmatthias.ringwald     channel->remote_cid = source_cid;
1678b1988dceSmatthias.ringwald     channel->remote_sig_id = sig_id;
1679645658c9Smatthias.ringwald 
1680f53da564S[email protected]     // limit local mtu to max acl packet length - l2cap header
16812985cb84Smatthias.ringwald     if (channel->local_mtu > l2cap_max_mtu()) {
16822985cb84Smatthias.ringwald         channel->local_mtu = l2cap_max_mtu();
16839775e25bSmatthias.ringwald     }
16849775e25bSmatthias.ringwald 
1685645658c9Smatthias.ringwald     // set initial state
1686df3354fcS[email protected]     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
1687a24785d0SMatthias Ringwald     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
1688e405ae81Smatthias.ringwald 
1689645658c9Smatthias.ringwald     // add to connections list
1690665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1691645658c9Smatthias.ringwald 
1692f85a9399S[email protected]     // assert security requirements
16931eb2563eS[email protected]     gap_request_security_level(handle, channel->required_security_level);
1694e405ae81Smatthias.ringwald }
1695645658c9Smatthias.ringwald 
1696ce8f182eSMatthias Ringwald void l2cap_accept_connection(uint16_t local_cid){
1697e0abb8e7S[email protected]     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
1698b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1699e405ae81Smatthias.ringwald     if (!channel) {
1700ce8f182eSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
1701e405ae81Smatthias.ringwald         return;
1702e405ae81Smatthias.ringwald     }
1703e405ae81Smatthias.ringwald 
170443ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
170543ec931dSMatthias Ringwald     // configure L2CAP Basic mode
170643ec931dSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
170743ec931dSMatthias Ringwald #endif
170843ec931dSMatthias Ringwald 
1709552d92a1Smatthias.ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
1710e405ae81Smatthias.ringwald 
1711552d92a1Smatthias.ringwald     // process
1712552d92a1Smatthias.ringwald     l2cap_run();
1713e405ae81Smatthias.ringwald }
1714645658c9Smatthias.ringwald 
171543ec931dSMatthias Ringwald 
171643ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
17172b70d705SMatthias Ringwald uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, int ertm_mandatory, uint8_t max_transmit,
1718501329faSMatthias 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){
1719501329faSMatthias Ringwald 
172043ec931dSMatthias Ringwald     log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
172143ec931dSMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
172243ec931dSMatthias Ringwald     if (!channel) {
172343ec931dSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
17242b70d705SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
172543ec931dSMatthias Ringwald     }
172643ec931dSMatthias Ringwald 
17272b70d705SMatthias Ringwald     // validate local config
17282b70d705SMatthias 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);
17292b70d705SMatthias Ringwald     if (result) return result;
17302b70d705SMatthias Ringwald 
173143ec931dSMatthias Ringwald     // configure L2CAP ERTM
17327b181629SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_mandatory, max_transmit, retransmission_timeout_ms, monitor_timeout_ms, num_tx_buffers, num_rx_buffers, buffer, size);
173343ec931dSMatthias Ringwald 
17347b181629SMatthias Ringwald     // continue
173543ec931dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
173643ec931dSMatthias Ringwald 
173743ec931dSMatthias Ringwald     // process
173843ec931dSMatthias Ringwald     l2cap_run();
17392b70d705SMatthias Ringwald 
17402b70d705SMatthias Ringwald     return ERROR_CODE_SUCCESS;
174143ec931dSMatthias Ringwald }
17422a424812SMatthias Ringwald 
174367a3a5b7SMatthias Ringwald uint8_t l2cap_ertm_set_busy(uint16_t local_cid){
17448f1c9639SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
17458f1c9639SMatthias Ringwald     if (!channel) {
17468f1c9639SMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
17478f1c9639SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
17488f1c9639SMatthias Ringwald     }
17498f1c9639SMatthias Ringwald     channel->send_supervisor_frame_receiver_not_ready = 1;
17508f1c9639SMatthias Ringwald     l2cap_run();
175167a3a5b7SMatthias Ringwald     return ERROR_CODE_SUCCESS;
175267a3a5b7SMatthias Ringwald }
175367a3a5b7SMatthias Ringwald 
175467a3a5b7SMatthias Ringwald uint8_t l2cap_ertm_set_ready(uint16_t local_cid){
175567a3a5b7SMatthias Ringwald     return ERROR_CODE_SUCCESS;
175667a3a5b7SMatthias Ringwald     UNUSED(local_cid);
175767a3a5b7SMatthias Ringwald }
175867a3a5b7SMatthias Ringwald 
17592a424812SMatthias Ringwald static void l2cap_ertm_handle_req_seq(l2cap_channel_t * l2cap_channel, uint8_t req_seq){
17602a424812SMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
17612a424812SMatthias Ringwald     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
17622a424812SMatthias Ringwald     if ( ((req_seq - 1) & 0x3f) == tx_state->tx_seq){
17632a424812SMatthias Ringwald         log_info("RR seq %u == seq of oldest tx packet -> packet done", req_seq);
176462041d70SMatthias Ringwald         // stop retransmission timer
176562041d70SMatthias Ringwald         btstack_run_loop_remove_timer(&tx_state->retransmission_timer);
17662a424812SMatthias Ringwald         l2cap_channel->tx_read_index++;
17672a424812SMatthias Ringwald         if (l2cap_channel->tx_read_index >= l2cap_channel->num_rx_buffers){
17682a424812SMatthias Ringwald             l2cap_channel->tx_read_index = 0;
17692a424812SMatthias Ringwald         }
17702a424812SMatthias Ringwald     } else {
17712a424812SMatthias Ringwald         log_info("RR seq %u != seq of oldest tx packet %u ???", req_seq, tx_state->tx_seq);
17722a424812SMatthias Ringwald     }
17732a424812SMatthias Ringwald }
177467a3a5b7SMatthias Ringwald 
177543ec931dSMatthias Ringwald #endif
177643ec931dSMatthias Ringwald 
177743ec931dSMatthias Ringwald 
17787ef6a7bbSMatthias Ringwald void l2cap_decline_connection(uint16_t local_cid){
17797ef6a7bbSMatthias Ringwald     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
1780b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
1781e405ae81Smatthias.ringwald     if (!channel) {
1782ce8f182eSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
1783e405ae81Smatthias.ringwald         return;
1784e405ae81Smatthias.ringwald     }
1785e7ff783cSmatthias.ringwald     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
17867ef6a7bbSMatthias Ringwald     channel->reason = 0x04; // no resources available
1787e7ff783cSmatthias.ringwald     l2cap_run();
1788645658c9Smatthias.ringwald }
1789645658c9Smatthias.ringwald 
17907f02f414SMatthias Ringwald static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
1791b1988dceSmatthias.ringwald 
1792b1988dceSmatthias.ringwald     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
1793b1988dceSmatthias.ringwald 
1794f8fbdce0SMatthias Ringwald     uint16_t flags = little_endian_read_16(command, 6);
179563a7246aSmatthias.ringwald     if (flags & 1) {
179663a7246aSmatthias.ringwald         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
179763a7246aSmatthias.ringwald     }
179863a7246aSmatthias.ringwald 
17992784b77dSmatthias.ringwald     // accept the other's configuration options
1800f8fbdce0SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
18013de7c0caSmatthias.ringwald     uint16_t pos     = 8;
18023de7c0caSmatthias.ringwald     while (pos < end_pos){
180363a7246aSmatthias.ringwald         uint8_t option_hint = command[pos] >> 7;
180463a7246aSmatthias.ringwald         uint8_t option_type = command[pos] & 0x7f;
180563a7246aSmatthias.ringwald         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
180663a7246aSmatthias.ringwald         pos++;
18071dc511deSmatthias.ringwald         uint8_t length = command[pos++];
18081dc511deSmatthias.ringwald         // MTU { type(8): 1, len(8):2, MTU(16) }
180963a7246aSmatthias.ringwald         if (option_type == 1 && length == 2){
1810f8fbdce0SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, pos);
18119d139fbaSMatthias Ringwald             if (channel->remote_mtu > l2cap_max_mtu()){
18129d139fbaSMatthias Ringwald                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
18139d139fbaSMatthias Ringwald                 channel->remote_mtu = l2cap_max_mtu();
18149d139fbaSMatthias Ringwald             }
181563a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
181663a7246aSmatthias.ringwald         }
18170fe7a9d0S[email protected]         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
18180fe7a9d0S[email protected]         if (option_type == 2 && length == 2){
1819f8fbdce0SMatthias Ringwald             channel->flush_timeout = little_endian_read_16(command, pos);
18200fe7a9d0S[email protected]         }
1821f2fa388dSMatthias Ringwald 
18226dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
18236dca2a0cSMatthias Ringwald         // Retransmission and Flow Control Option
18246dca2a0cSMatthias Ringwald         if (option_type == 4 && length == 9){
18253232a1c6SMatthias Ringwald             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
1826ac8f1300SMatthias Ringwald             switch(channel->mode){
1827ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
182825cd60d3SMatthias Ringwald                     // Store remote config
1829bbc0a9e7SMatthias Ringwald                     channel->remote_tx_window_size = command[pos+1];
1830bbc0a9e7SMatthias Ringwald                     channel->remote_max_transmit   = command[pos+2];
1831bbc0a9e7SMatthias Ringwald                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
1832bbc0a9e7SMatthias Ringwald                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
1833bbc0a9e7SMatthias Ringwald                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u",
1834bbc0a9e7SMatthias Ringwald                         channel->remote_tx_window_size,
1835bbc0a9e7SMatthias Ringwald                         channel->remote_max_transmit,
1836bbc0a9e7SMatthias Ringwald                         channel->remote_retransmission_timeout_ms,
1837bbc0a9e7SMatthias Ringwald                         channel->remote_monitor_timeout_ms);
1838bbc0a9e7SMatthias Ringwald                     // we store remote MPS in remote_mtu, might need to get re-evaluated
1839bbc0a9e7SMatthias Ringwald                     channel->remote_mtu = little_endian_read_16(command, pos + 7);
184025cd60d3SMatthias Ringwald                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
184125cd60d3SMatthias Ringwald                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
184225cd60d3SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1843ac8f1300SMatthias Ringwald                     } else {
1844ac8f1300SMatthias Ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1845ac8f1300SMatthias Ringwald                     }
1846ac8f1300SMatthias Ringwald                     break;
1847ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
1848ac8f1300SMatthias Ringwald                     switch (mode){
1849ac8f1300SMatthias Ringwald                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
1850ac8f1300SMatthias Ringwald                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
1851ac8f1300SMatthias Ringwald                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
1852ac8f1300SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1853ac8f1300SMatthias Ringwald                             }
1854ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
1855ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1856ac8f1300SMatthias Ringwald                             break;
1857ac8f1300SMatthias Ringwald                         default: // case L2CAP_CHANNEL_MODE_BASIC:
1858ac8f1300SMatthias Ringwald                             // TODO store and evaluate configuration
1859ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1860ac8f1300SMatthias Ringwald                             break;
1861ac8f1300SMatthias Ringwald                     }
1862ac8f1300SMatthias Ringwald                     break;
1863ac8f1300SMatthias Ringwald                 default:
1864ac8f1300SMatthias Ringwald                     break;
1865ac8f1300SMatthias Ringwald             }
18663232a1c6SMatthias Ringwald         }
18676dca2a0cSMatthias Ringwald #endif
186863a7246aSmatthias.ringwald         // check for unknown options
186963a7246aSmatthias.ringwald         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
1870c177a91cS[email protected]             log_info("l2cap cid %u, unknown options", channel->local_cid);
187163a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
18721dc511deSmatthias.ringwald         }
18731dc511deSmatthias.ringwald         pos += length;
18741dc511deSmatthias.ringwald     }
18752784b77dSmatthias.ringwald }
18762784b77dSmatthias.ringwald 
1877f2fa388dSMatthias Ringwald static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
1878f2fa388dSMatthias Ringwald     log_info("l2cap_signaling_handle_configure_response");
18793232a1c6SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
18803232a1c6SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
1881f2fa388dSMatthias Ringwald     uint16_t pos     = 10;
18823232a1c6SMatthias Ringwald     while (pos < end_pos){
18833232a1c6SMatthias Ringwald         uint8_t option_hint = command[pos] >> 7;
18843232a1c6SMatthias Ringwald         uint8_t option_type = command[pos] & 0x7f;
18853232a1c6SMatthias Ringwald         log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
18863232a1c6SMatthias Ringwald         pos++;
18873232a1c6SMatthias Ringwald         uint8_t length = command[pos++];
18883232a1c6SMatthias Ringwald 
18893232a1c6SMatthias Ringwald         // Retransmission and Flow Control Option
18903232a1c6SMatthias Ringwald         if (option_type == 4 && length == 9){
1891ac8f1300SMatthias Ringwald             switch (channel->mode){
1892ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
1893f2fa388dSMatthias Ringwald                     if (channel->ertm_mandatory){
1894ac8f1300SMatthias Ringwald                         // ??
1895f2fa388dSMatthias Ringwald                     } else {
1896ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
1897ac8f1300SMatthias Ringwald                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
1898f2fa388dSMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
18993232a1c6SMatthias Ringwald                         }
19003232a1c6SMatthias Ringwald                     }
1901ac8f1300SMatthias Ringwald                     break;
1902ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
1903ac8f1300SMatthias Ringwald                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
1904ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
1905ac8f1300SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1906ac8f1300SMatthias Ringwald                     }
1907ac8f1300SMatthias Ringwald                     break;
1908ac8f1300SMatthias Ringwald                 default:
1909ac8f1300SMatthias Ringwald                     break;
19103232a1c6SMatthias Ringwald             }
1911f2fa388dSMatthias Ringwald         }
19123232a1c6SMatthias Ringwald 
19133232a1c6SMatthias Ringwald         // check for unknown options
19143232a1c6SMatthias Ringwald         if (option_hint == 0 && (option_type == 0 || option_type >= 0x07)){
19153232a1c6SMatthias Ringwald             log_info("l2cap cid %u, unknown options", channel->local_cid);
19163232a1c6SMatthias Ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
19173232a1c6SMatthias Ringwald         }
19183232a1c6SMatthias Ringwald 
19193232a1c6SMatthias Ringwald         pos += length;
19203232a1c6SMatthias Ringwald     }
19213232a1c6SMatthias Ringwald #endif
19223232a1c6SMatthias Ringwald }
19233232a1c6SMatthias Ringwald 
1924fa8473a4Smatthias.ringwald static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
19259da54300S[email protected]     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
192673cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
192773cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
1928019f9b43SMatthias Ringwald     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
1929019f9b43SMatthias Ringwald     if (channel->state == L2CAP_STATE_OPEN) return 0;
1930fa8473a4Smatthias.ringwald     return 1;
1931fa8473a4Smatthias.ringwald }
1932fa8473a4Smatthias.ringwald 
1933fa8473a4Smatthias.ringwald 
19347f02f414SMatthias Ringwald static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
19351e6aba47Smatthias.ringwald 
193600d93d79Smatthias.ringwald     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
193700d93d79Smatthias.ringwald     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
193838e5900eSmatthias.ringwald     uint16_t result = 0;
19391e6aba47Smatthias.ringwald 
19409da54300S[email protected]     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
1941b35f641cSmatthias.ringwald 
19429a011532Smatthias.ringwald     // handle DISCONNECT REQUESTS seperately
19439a011532Smatthias.ringwald     if (code == DISCONNECTION_REQUEST){
19449a011532Smatthias.ringwald         switch (channel->state){
1945fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
19469a011532Smatthias.ringwald             case L2CAP_STATE_OPEN:
19472b83fb7dSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
19489a011532Smatthias.ringwald             case L2CAP_STATE_WAIT_DISCONNECT:
19499a011532Smatthias.ringwald                 l2cap_handle_disconnect_request(channel, identifier);
19509a011532Smatthias.ringwald                 break;
19519a011532Smatthias.ringwald 
19529a011532Smatthias.ringwald             default:
19539a011532Smatthias.ringwald                 // ignore in other states
19549a011532Smatthias.ringwald                 break;
19559a011532Smatthias.ringwald         }
19569a011532Smatthias.ringwald         return;
19579a011532Smatthias.ringwald     }
19589a011532Smatthias.ringwald 
195956081214Smatthias.ringwald     // @STATEMACHINE(l2cap)
19601e6aba47Smatthias.ringwald     switch (channel->state) {
19611e6aba47Smatthias.ringwald 
19621e6aba47Smatthias.ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
19631e6aba47Smatthias.ringwald             switch (code){
19641e6aba47Smatthias.ringwald                 case CONNECTION_RESPONSE:
19655932bd7cS[email protected]                     l2cap_stop_rtx(channel);
1966f8fbdce0SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
196738e5900eSmatthias.ringwald                     switch (result) {
196838e5900eSmatthias.ringwald                         case 0:
1969169f8b28Smatthias.ringwald                             // successful connection
1970f8fbdce0SMatthias Ringwald                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
1971fa8473a4Smatthias.ringwald                             channel->state = L2CAP_STATE_CONFIG;
197228ca2b46S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
197338e5900eSmatthias.ringwald                             break;
197438e5900eSmatthias.ringwald                         case 1:
19755932bd7cS[email protected]                             // connection pending. get some coffee, but start the ERTX
19765932bd7cS[email protected]                             l2cap_start_ertx(channel);
197738e5900eSmatthias.ringwald                             break;
197838e5900eSmatthias.ringwald                         default:
1979eb920dbeSmatthias.ringwald                             // channel closed
1980eb920dbeSmatthias.ringwald                             channel->state = L2CAP_STATE_CLOSED;
1981f32b992eSmatthias.ringwald                             // map l2cap connection response result to BTstack status enumeration
198238e5900eSmatthias.ringwald                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
1983eb920dbeSmatthias.ringwald 
1984eb920dbeSmatthias.ringwald                             // drop link key if security block
1985eb920dbeSmatthias.ringwald                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
198615a95bd5SMatthias Ringwald                                 gap_drop_link_key_for_bd_addr(channel->address);
1987eb920dbeSmatthias.ringwald                             }
1988eb920dbeSmatthias.ringwald 
1989eb920dbeSmatthias.ringwald                             // discard channel
1990665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1991d3a9df87Smatthias.ringwald                             btstack_memory_l2cap_channel_free(channel);
199238e5900eSmatthias.ringwald                             break;
19931e6aba47Smatthias.ringwald                     }
19941e6aba47Smatthias.ringwald                     break;
199538e5900eSmatthias.ringwald 
199638e5900eSmatthias.ringwald                 default:
19971e6aba47Smatthias.ringwald                     //@TODO: implement other signaling packets
199838e5900eSmatthias.ringwald                     break;
19991e6aba47Smatthias.ringwald             }
20001e6aba47Smatthias.ringwald             break;
20011e6aba47Smatthias.ringwald 
2002fa8473a4Smatthias.ringwald         case L2CAP_STATE_CONFIG:
2003f8fbdce0SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2004ae280e73Smatthias.ringwald             switch (code) {
2005ae280e73Smatthias.ringwald                 case CONFIGURE_REQUEST:
200628ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
2007ae280e73Smatthias.ringwald                     l2cap_signaling_handle_configure_request(channel, command);
200863a7246aSmatthias.ringwald                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
200963a7246aSmatthias.ringwald                         // only done if continuation not set
201063a7246aSmatthias.ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
201163a7246aSmatthias.ringwald                     }
2012ae280e73Smatthias.ringwald                     break;
20131e6aba47Smatthias.ringwald                 case CONFIGURE_RESPONSE:
20145932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2015f2fa388dSMatthias Ringwald                     l2cap_signaling_handle_configure_response(channel, result, command);
20165932bd7cS[email protected]                     switch (result){
20175932bd7cS[email protected]                         case 0: // success
20185932bd7cS[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
20195932bd7cS[email protected]                             break;
20205932bd7cS[email protected]                         case 4: // pending
20215932bd7cS[email protected]                             l2cap_start_ertx(channel);
20225932bd7cS[email protected]                             break;
20235932bd7cS[email protected]                         default:
2024a32d6a03SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2025a32d6a03SMatthias Ringwald                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
2026a32d6a03SMatthias Ringwald                                 // remote does not offer ertm but it's required
2027a32d6a03SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2028a32d6a03SMatthias Ringwald                                 break;
2029a32d6a03SMatthias Ringwald                             }
2030a32d6a03SMatthias Ringwald #endif
2031fe9d8984S[email protected]                             // retry on negative result
2032fe9d8984S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2033fe9d8984S[email protected]                             break;
2034fe9d8984S[email protected]                     }
20355a67bd4aSmatthias.ringwald                     break;
20365a67bd4aSmatthias.ringwald                 default:
20375a67bd4aSmatthias.ringwald                     break;
20381e6aba47Smatthias.ringwald             }
2039fa8473a4Smatthias.ringwald             if (l2cap_channel_ready_for_open(channel)){
2040fa8473a4Smatthias.ringwald                 // for open:
20415a67bd4aSmatthias.ringwald                 channel->state = L2CAP_STATE_OPEN;
2042fa8473a4Smatthias.ringwald                 l2cap_emit_channel_opened(channel, 0);
2043c8e4258aSmatthias.ringwald             }
2044c8e4258aSmatthias.ringwald             break;
2045f62db1e3Smatthias.ringwald 
2046f62db1e3Smatthias.ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
2047f62db1e3Smatthias.ringwald             switch (code) {
2048f62db1e3Smatthias.ringwald                 case DISCONNECTION_RESPONSE:
204927a923d0Smatthias.ringwald                     l2cap_finialize_channel_close(channel);
205027a923d0Smatthias.ringwald                     break;
20515a67bd4aSmatthias.ringwald                 default:
20525a67bd4aSmatthias.ringwald                     //@TODO: implement other signaling packets
20535a67bd4aSmatthias.ringwald                     break;
205427a923d0Smatthias.ringwald             }
205527a923d0Smatthias.ringwald             break;
205684836b65Smatthias.ringwald 
205784836b65Smatthias.ringwald         case L2CAP_STATE_CLOSED:
205884836b65Smatthias.ringwald             // @TODO handle incoming requests
205984836b65Smatthias.ringwald             break;
206084836b65Smatthias.ringwald 
206184836b65Smatthias.ringwald         case L2CAP_STATE_OPEN:
206284836b65Smatthias.ringwald             //@TODO: implement other signaling packets, e.g. re-configure
206384836b65Smatthias.ringwald             break;
206410642e45Smatthias.ringwald         default:
206510642e45Smatthias.ringwald             break;
206627a923d0Smatthias.ringwald     }
20679da54300S[email protected]     // log_info("new state %u", channel->state);
206827a923d0Smatthias.ringwald }
206927a923d0Smatthias.ringwald 
207000d93d79Smatthias.ringwald 
20717f02f414SMatthias Ringwald static void l2cap_signaling_handler_dispatch( hci_con_handle_t handle, uint8_t * command){
207200d93d79Smatthias.ringwald 
20731b9cb13dSMatthias Ringwald     btstack_linked_list_iterator_t it;
20741b9cb13dSMatthias Ringwald 
207500d93d79Smatthias.ringwald     // get code, signalind identifier and command len
207600d93d79Smatthias.ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
207700d93d79Smatthias.ringwald     uint8_t sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
207800d93d79Smatthias.ringwald 
20791b9cb13dSMatthias Ringwald     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
20801b9cb13dSMatthias Ringwald     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_RESPONSE){
2081e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
208200d93d79Smatthias.ringwald         return;
208300d93d79Smatthias.ringwald     }
208400d93d79Smatthias.ringwald 
208500d93d79Smatthias.ringwald     // general commands without an assigned channel
208600d93d79Smatthias.ringwald     switch(code) {
208700d93d79Smatthias.ringwald 
208800d93d79Smatthias.ringwald         case CONNECTION_REQUEST: {
2089f8fbdce0SMatthias Ringwald             uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2090f8fbdce0SMatthias Ringwald             uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
209100d93d79Smatthias.ringwald             l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
20922b83fb7dSmatthias.ringwald             return;
209300d93d79Smatthias.ringwald         }
209400d93d79Smatthias.ringwald 
20952b360848Smatthias.ringwald         case ECHO_REQUEST:
2096e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
20972b83fb7dSmatthias.ringwald             return;
209800d93d79Smatthias.ringwald 
209900d93d79Smatthias.ringwald         case INFORMATION_REQUEST: {
2100f8fbdce0SMatthias Ringwald             uint16_t infoType = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2101e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, infoType);
21022b83fb7dSmatthias.ringwald             return;
210300d93d79Smatthias.ringwald         }
210400d93d79Smatthias.ringwald 
21051b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
21061b9cb13dSMatthias Ringwald         case INFORMATION_RESPONSE: {
21071b9cb13dSMatthias Ringwald             hci_connection_t * connection = hci_connection_for_handle(handle);
21081b9cb13dSMatthias Ringwald             if (!connection) return;
21091b9cb13dSMatthias Ringwald             uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
21101b9cb13dSMatthias Ringwald             uint16_t result =  little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
21111b9cb13dSMatthias Ringwald             if (result != 0) return;
2112543b84e4SMatthias Ringwald             if (info_type != 0x02) return;
21131b9cb13dSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
21141b9cb13dSMatthias Ringwald             connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2115543b84e4SMatthias Ringwald             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
21161b9cb13dSMatthias Ringwald             // trigger connection request
21171b9cb13dSMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
21181b9cb13dSMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
21191b9cb13dSMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2120543b84e4SMatthias Ringwald                 if (channel->con_handle != handle) continue;
2121543b84e4SMatthias Ringwald                 // bail if ERTM was requested but is not supported
2122543b84e4SMatthias Ringwald                 if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2123f073f086SMatthias Ringwald                     if (channel->ertm_mandatory){
2124543b84e4SMatthias Ringwald                         // channel closed
2125543b84e4SMatthias Ringwald                         channel->state = L2CAP_STATE_CLOSED;
2126543b84e4SMatthias Ringwald                         // map l2cap connection response result to BTstack status enumeration
2127543b84e4SMatthias Ringwald                         l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTD);
2128543b84e4SMatthias Ringwald                         // discard channel
2129543b84e4SMatthias Ringwald                         btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2130543b84e4SMatthias Ringwald                         btstack_memory_l2cap_channel_free(channel);
2131543b84e4SMatthias Ringwald                         continue;
2132f073f086SMatthias Ringwald                     } else {
2133f073f086SMatthias Ringwald                         // fallback to Basic mode
2134f073f086SMatthias Ringwald                         channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2135f073f086SMatthias Ringwald                     }
2136543b84e4SMatthias Ringwald                 }
2137543b84e4SMatthias Ringwald                 // start connecting
21381b9cb13dSMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
21391b9cb13dSMatthias Ringwald                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
21401b9cb13dSMatthias Ringwald                 }
214152606043SMatthias Ringwald                 // respond to connection request
214252606043SMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
214352606043SMatthias Ringwald                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
214452606043SMatthias Ringwald                     l2cap_emit_incoming_connection(channel);
214552606043SMatthias Ringwald                 }
21461b9cb13dSMatthias Ringwald             }
21471b9cb13dSMatthias Ringwald             return;
21481b9cb13dSMatthias Ringwald         }
21491b9cb13dSMatthias Ringwald #endif
21501b9cb13dSMatthias Ringwald 
215100d93d79Smatthias.ringwald         default:
215200d93d79Smatthias.ringwald             break;
215300d93d79Smatthias.ringwald     }
215400d93d79Smatthias.ringwald 
215500d93d79Smatthias.ringwald 
215600d93d79Smatthias.ringwald     // Get potential destination CID
2157f8fbdce0SMatthias Ringwald     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
215800d93d79Smatthias.ringwald 
215900d93d79Smatthias.ringwald     // Find channel for this sig_id and connection handle
2160665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2161665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2162665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2163fc64f94aSMatthias Ringwald         if (channel->con_handle != handle) continue;
216400d93d79Smatthias.ringwald         if (code & 1) {
2165b1988dceSmatthias.ringwald             // match odd commands (responses) by previous signaling identifier
2166b1988dceSmatthias.ringwald             if (channel->local_sig_id == sig_id) {
216700d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
21684e32727eSmatthias.ringwald                 break;
216900d93d79Smatthias.ringwald             }
217000d93d79Smatthias.ringwald         } else {
2171b1988dceSmatthias.ringwald             // match even commands (requests) by local channel id
217200d93d79Smatthias.ringwald             if (channel->local_cid == dest_cid) {
217300d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
21744e32727eSmatthias.ringwald                 break;
217500d93d79Smatthias.ringwald             }
217600d93d79Smatthias.ringwald         }
217700d93d79Smatthias.ringwald     }
217800d93d79Smatthias.ringwald }
217909e9d05bSMatthias Ringwald #endif
218000d93d79Smatthias.ringwald 
2181e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
218209e9d05bSMatthias Ringwald 
218309e9d05bSMatthias Ringwald static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
218409e9d05bSMatthias Ringwald     uint8_t event[6];
218509e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
218609e9d05bSMatthias Ringwald     event[1] = 4;
218709e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
218809e9d05bSMatthias Ringwald     little_endian_store_16(event, 4, result);
218909e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
219009e9d05bSMatthias Ringwald     if (!l2cap_event_packet_handler) return;
219109e9d05bSMatthias Ringwald     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
219209e9d05bSMatthias Ringwald }
219309e9d05bSMatthias Ringwald 
2194c48b2a2cSMatthias Ringwald // @returns valid
2195c48b2a2cSMatthias Ringwald static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
2196e7d0c9aaSMatthias Ringwald     hci_connection_t * connection;
2197c48b2a2cSMatthias Ringwald     uint16_t result;
2198c48b2a2cSMatthias Ringwald     uint8_t  event[10];
219983fd9c76SMatthias Ringwald 
2200cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2201a3dc965aSMatthias Ringwald     btstack_linked_list_iterator_t it;
2202a3dc965aSMatthias Ringwald     l2cap_channel_t * channel;
2203a3dc965aSMatthias Ringwald     uint16_t local_cid;
220483fd9c76SMatthias Ringwald     uint16_t le_psm;
220563f0ac45SMatthias Ringwald     uint16_t new_credits;
220663f0ac45SMatthias Ringwald     uint16_t credits_before;
2207e7d0c9aaSMatthias Ringwald     l2cap_service_t * service;
220811cae19eSMilanka Ringwald     uint16_t source_cid;
220983fd9c76SMatthias Ringwald #endif
221000d93d79Smatthias.ringwald 
22111b8b8d05SMatthias Ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
221223017473SMatthias Ringwald     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u", code, sig_id);
22131b8b8d05SMatthias Ringwald 
22141b8b8d05SMatthias Ringwald     switch (code){
221500d93d79Smatthias.ringwald 
2216c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
2217c48b2a2cSMatthias Ringwald             result = little_endian_read_16(command, 4);
2218ccf076adS[email protected]             l2cap_emit_connection_parameter_update_response(handle, result);
2219ccf076adS[email protected]             break;
2220da886c03S[email protected] 
2221c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_REQUEST:
2222e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
2223da886c03S[email protected]             if (connection){
22246d91fb6cSMatthias Ringwald                 if (connection->role != HCI_ROLE_MASTER){
22256d91fb6cSMatthias Ringwald                     // reject command without notifying upper layer when not in master role
2226c48b2a2cSMatthias Ringwald                     return 0;
22276d91fb6cSMatthias Ringwald                 }
2228da886c03S[email protected]                 int update_parameter = 1;
2229a4c06b28SMatthias Ringwald                 le_connection_parameter_range_t existing_range;
22304ced4e8cSMatthias Ringwald                 gap_get_connection_parameter_range(&existing_range);
2231c48b2a2cSMatthias Ringwald                 uint16_t le_conn_interval_min = little_endian_read_16(command,8);
2232c48b2a2cSMatthias Ringwald                 uint16_t le_conn_interval_max = little_endian_read_16(command,10);
2233c48b2a2cSMatthias Ringwald                 uint16_t le_conn_latency = little_endian_read_16(command,12);
2234c48b2a2cSMatthias Ringwald                 uint16_t le_supervision_timeout = little_endian_read_16(command,14);
2235da886c03S[email protected] 
2236da886c03S[email protected]                 if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
2237da886c03S[email protected]                 if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
2238da886c03S[email protected] 
2239da886c03S[email protected]                 if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
2240da886c03S[email protected]                 if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
2241da886c03S[email protected] 
2242da886c03S[email protected]                 if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
2243da886c03S[email protected]                 if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
2244da886c03S[email protected] 
2245da886c03S[email protected]                 if (update_parameter){
2246da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
2247da886c03S[email protected]                     connection->le_conn_interval_min = le_conn_interval_min;
2248da886c03S[email protected]                     connection->le_conn_interval_max = le_conn_interval_max;
2249da886c03S[email protected]                     connection->le_conn_latency = le_conn_latency;
2250da886c03S[email protected]                     connection->le_supervision_timeout = le_supervision_timeout;
2251da886c03S[email protected]                 } else {
2252da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
2253da886c03S[email protected]                 }
2254c48b2a2cSMatthias Ringwald                 connection->le_con_param_update_identifier = sig_id;
2255da886c03S[email protected]             }
2256da886c03S[email protected] 
225733c40538SMatthias Ringwald             if (!l2cap_event_packet_handler) break;
2258c48b2a2cSMatthias Ringwald 
2259c48b2a2cSMatthias Ringwald             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
2260c48b2a2cSMatthias Ringwald             event[1] = 8;
2261c48b2a2cSMatthias Ringwald             memcpy(&event[2], &command[4], 8);
2262c48b2a2cSMatthias Ringwald             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
226333c40538SMatthias Ringwald             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
2264ccf076adS[email protected]             break;
2265c48b2a2cSMatthias Ringwald 
2266a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2267a3dc965aSMatthias Ringwald 
226863f0ac45SMatthias Ringwald         case COMMAND_REJECT:
226963f0ac45SMatthias Ringwald             // Find channel for this sig_id and connection handle
227063f0ac45SMatthias Ringwald             channel = NULL;
227163f0ac45SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
227263f0ac45SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
227363f0ac45SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
227463f0ac45SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
227563f0ac45SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
227663f0ac45SMatthias Ringwald                 channel = a_channel;
227763f0ac45SMatthias Ringwald                 break;
227863f0ac45SMatthias Ringwald             }
227963f0ac45SMatthias Ringwald             if (!channel) break;
228063f0ac45SMatthias Ringwald 
228163f0ac45SMatthias Ringwald             // if received while waiting for le connection response, assume legacy device
228263f0ac45SMatthias Ringwald             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
228363f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
228463f0ac45SMatthias Ringwald                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
228544276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0x0002);
228663f0ac45SMatthias Ringwald 
228763f0ac45SMatthias Ringwald                 // discard channel
228863f0ac45SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
228963f0ac45SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
229063f0ac45SMatthias Ringwald                 break;
229163f0ac45SMatthias Ringwald             }
229263f0ac45SMatthias Ringwald             break;
229363f0ac45SMatthias Ringwald 
2294e7d0c9aaSMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_REQUEST:
2295e7d0c9aaSMatthias Ringwald 
2296e7d0c9aaSMatthias Ringwald             // get hci connection, bail if not found (must not happen)
2297e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
2298e7d0c9aaSMatthias Ringwald             if (!connection) return 0;
2299e7d0c9aaSMatthias Ringwald 
2300e7d0c9aaSMatthias Ringwald             // check if service registered
2301e7d0c9aaSMatthias Ringwald             le_psm  = little_endian_read_16(command, 4);
2302e7d0c9aaSMatthias Ringwald             service = l2cap_le_get_service(le_psm);
230311cae19eSMilanka Ringwald             source_cid = little_endian_read_16(command, 6);
2304e7d0c9aaSMatthias Ringwald 
2305e7d0c9aaSMatthias Ringwald             if (service){
2306e7d0c9aaSMatthias Ringwald                 if (source_cid < 0x40){
2307e7d0c9aaSMatthias Ringwald                     // 0x0009 Connection refused - Invalid Source CID
2308e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
2309e7d0c9aaSMatthias Ringwald                     return 1;
2310e7d0c9aaSMatthias Ringwald                 }
2311e7d0c9aaSMatthias Ringwald 
2312e7d0c9aaSMatthias Ringwald                 // go through list of channels for this ACL connection and check if we get a match
2313e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2314e7d0c9aaSMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&it)){
23151b8b8d05SMatthias Ringwald                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
23161b8b8d05SMatthias Ringwald                     if (a_channel->con_handle != handle) continue;
23171b8b8d05SMatthias Ringwald                     if (a_channel->remote_cid != source_cid) continue;
2318e7d0c9aaSMatthias Ringwald                     // 0x000a Connection refused - Source CID already allocated
2319e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
2320e7d0c9aaSMatthias Ringwald                     return 1;
2321e7d0c9aaSMatthias Ringwald                 }
2322e7d0c9aaSMatthias Ringwald 
232383fd9c76SMatthias Ringwald                 // security: check encryption
232483fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_2){
232583fd9c76SMatthias Ringwald                     if (sm_encryption_key_size(handle) == 0){
232683fd9c76SMatthias Ringwald                         // 0x0008 Connection refused - insufficient encryption
2327e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
232883fd9c76SMatthias Ringwald                         return 1;
232983fd9c76SMatthias Ringwald                     }
233083fd9c76SMatthias Ringwald                     // anything less than 16 byte key size is insufficient
233183fd9c76SMatthias Ringwald                     if (sm_encryption_key_size(handle) < 16){
233283fd9c76SMatthias Ringwald                         // 0x0007 Connection refused – insufficient encryption key size
2333e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
233483fd9c76SMatthias Ringwald                         return 1;
233583fd9c76SMatthias Ringwald                     }
233683fd9c76SMatthias Ringwald                 }
233783fd9c76SMatthias Ringwald 
233883fd9c76SMatthias Ringwald                 // security: check authencation
233983fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_3){
234083fd9c76SMatthias Ringwald                     if (!sm_authenticated(handle)){
234183fd9c76SMatthias Ringwald                         // 0x0005 Connection refused – insufficient authentication
2342e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
234383fd9c76SMatthias Ringwald                         return 1;
234483fd9c76SMatthias Ringwald                     }
234583fd9c76SMatthias Ringwald                 }
234683fd9c76SMatthias Ringwald 
234783fd9c76SMatthias Ringwald                 // security: check authorization
234883fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_4){
234983fd9c76SMatthias Ringwald                     if (sm_authorization_state(handle) != AUTHORIZATION_GRANTED){
235083fd9c76SMatthias Ringwald                         // 0x0006 Connection refused – insufficient authorization
2351e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
235283fd9c76SMatthias Ringwald                         return 1;
235383fd9c76SMatthias Ringwald                     }
235483fd9c76SMatthias Ringwald                 }
2355e7d0c9aaSMatthias Ringwald 
2356e7d0c9aaSMatthias Ringwald                 // allocate channel
23571b8b8d05SMatthias Ringwald                 channel = l2cap_create_channel_entry(service->packet_handler, connection->address,
2358e7d0c9aaSMatthias Ringwald                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
2359e7d0c9aaSMatthias Ringwald                 if (!channel){
2360e7d0c9aaSMatthias Ringwald                     // 0x0004 Connection refused – no resources available
2361e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2362e7d0c9aaSMatthias Ringwald                     return 1;
2363e7d0c9aaSMatthias Ringwald                 }
2364e7d0c9aaSMatthias Ringwald 
2365e7d0c9aaSMatthias Ringwald                 channel->con_handle = handle;
2366e7d0c9aaSMatthias Ringwald                 channel->remote_cid = source_cid;
2367e7d0c9aaSMatthias Ringwald                 channel->remote_sig_id = sig_id;
23687f107edaSMatthias Ringwald                 channel->remote_mtu = little_endian_read_16(command, 8);
23697f107edaSMatthias Ringwald                 channel->remote_mps = little_endian_read_16(command, 10);
23707f107edaSMatthias Ringwald                 channel->credits_outgoing = little_endian_read_16(command, 12);
2371e7d0c9aaSMatthias Ringwald 
2372e7d0c9aaSMatthias Ringwald                 // set initial state
2373e7d0c9aaSMatthias Ringwald                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2374c99bb618SMatthias Ringwald                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
2375e7d0c9aaSMatthias Ringwald 
2376e7d0c9aaSMatthias Ringwald                 // add to connections list
2377e7d0c9aaSMatthias Ringwald                 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2378e7d0c9aaSMatthias Ringwald 
2379e7d0c9aaSMatthias Ringwald                 // post connection request event
238044276248SMatthias Ringwald                 l2cap_emit_le_incoming_connection(channel);
2381e7d0c9aaSMatthias Ringwald 
2382e7d0c9aaSMatthias Ringwald             } else {
2383e7d0c9aaSMatthias Ringwald                 // Connection refused – LE_PSM not supported
2384e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2385e7d0c9aaSMatthias Ringwald             }
2386e7d0c9aaSMatthias Ringwald             break;
23871b8b8d05SMatthias Ringwald 
23881b8b8d05SMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
23891b8b8d05SMatthias Ringwald             // Find channel for this sig_id and connection handle
23901b8b8d05SMatthias Ringwald             channel = NULL;
23911b8b8d05SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
23921b8b8d05SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
23931b8b8d05SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
23941b8b8d05SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
23951b8b8d05SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
23961b8b8d05SMatthias Ringwald                 channel = a_channel;
23971b8b8d05SMatthias Ringwald                 break;
23981b8b8d05SMatthias Ringwald             }
23991b8b8d05SMatthias Ringwald             if (!channel) break;
24001b8b8d05SMatthias Ringwald 
24011b8b8d05SMatthias Ringwald             // cid + 0
24021b8b8d05SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
24031b8b8d05SMatthias Ringwald             if (result){
24041b8b8d05SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
24051b8b8d05SMatthias Ringwald                 // map l2cap connection response result to BTstack status enumeration
240644276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, result);
24071b8b8d05SMatthias Ringwald 
24081b8b8d05SMatthias Ringwald                 // discard channel
240963f0ac45SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
24101b8b8d05SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
24111b8b8d05SMatthias Ringwald                 break;
24121b8b8d05SMatthias Ringwald             }
24131b8b8d05SMatthias Ringwald 
24141b8b8d05SMatthias Ringwald             // success
24151b8b8d05SMatthias Ringwald             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
24161b8b8d05SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
24171b8b8d05SMatthias Ringwald             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
24181b8b8d05SMatthias Ringwald             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
24191b8b8d05SMatthias Ringwald             channel->state = L2CAP_STATE_OPEN;
242044276248SMatthias Ringwald             l2cap_emit_le_channel_opened(channel, result);
24211b8b8d05SMatthias Ringwald             break;
24221b8b8d05SMatthias Ringwald 
242385aeef60SMatthias Ringwald         case LE_FLOW_CONTROL_CREDIT:
242485aeef60SMatthias Ringwald             // find channel
242585aeef60SMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
242685aeef60SMatthias Ringwald             channel = l2cap_le_get_channel_for_local_cid(local_cid);
242763f0ac45SMatthias Ringwald             if (!channel) {
242863f0ac45SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
242963f0ac45SMatthias Ringwald                 break;
243063f0ac45SMatthias Ringwald             }
243163f0ac45SMatthias Ringwald             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
243263f0ac45SMatthias Ringwald             credits_before = channel->credits_outgoing;
243363f0ac45SMatthias Ringwald             channel->credits_outgoing += new_credits;
243463f0ac45SMatthias Ringwald             // check for credit overrun
243563f0ac45SMatthias Ringwald             if (credits_before > channel->credits_outgoing){
243663f0ac45SMatthias Ringwald                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
243763f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
243863f0ac45SMatthias Ringwald                 break;
243963f0ac45SMatthias Ringwald             }
244063f0ac45SMatthias Ringwald             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
244185aeef60SMatthias Ringwald             break;
244285aeef60SMatthias Ringwald 
2443828a7f7aSMatthias Ringwald         case DISCONNECTION_REQUEST:
2444828a7f7aSMatthias Ringwald             // find channel
2445828a7f7aSMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
2446828a7f7aSMatthias Ringwald             channel = l2cap_le_get_channel_for_local_cid(local_cid);
244763f34e00SMatthias Ringwald             if (!channel) {
244863f34e00SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
244963f34e00SMatthias Ringwald                 break;
245063f34e00SMatthias Ringwald             }
2451828a7f7aSMatthias Ringwald             channel->remote_sig_id = sig_id;
2452828a7f7aSMatthias Ringwald             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
2453828a7f7aSMatthias Ringwald             break;
2454828a7f7aSMatthias Ringwald 
2455a3dc965aSMatthias Ringwald #endif
2456a3dc965aSMatthias Ringwald 
245763f0ac45SMatthias Ringwald         case DISCONNECTION_RESPONSE:
245863f0ac45SMatthias Ringwald             break;
245963f0ac45SMatthias Ringwald 
2460c48b2a2cSMatthias Ringwald         default:
2461c48b2a2cSMatthias Ringwald             // command unknown -> reject command
2462c48b2a2cSMatthias Ringwald             return 0;
2463ccf076adS[email protected]     }
2464c48b2a2cSMatthias Ringwald     return 1;
2465c48b2a2cSMatthias Ringwald }
2466e7d0c9aaSMatthias Ringwald #endif
2467c48b2a2cSMatthias Ringwald 
2468c48b2a2cSMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size ){
24699ec2630cSMatthias Ringwald     UNUSED(packet_type);
24709ec2630cSMatthias Ringwald     UNUSED(channel);
2471c48b2a2cSMatthias Ringwald 
247209e9d05bSMatthias Ringwald     l2cap_channel_t * l2cap_channel;
2473f3963406SMatthias Ringwald     UNUSED(l2cap_channel);
247409e9d05bSMatthias Ringwald 
2475c48b2a2cSMatthias Ringwald     // Get Channel ID
2476c48b2a2cSMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
2477c48b2a2cSMatthias Ringwald     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
2478c48b2a2cSMatthias Ringwald 
2479c48b2a2cSMatthias Ringwald     switch (channel_id) {
2480c48b2a2cSMatthias Ringwald 
248109e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2482c48b2a2cSMatthias Ringwald         case L2CAP_CID_SIGNALING: {
2483c48b2a2cSMatthias Ringwald             uint16_t command_offset = 8;
2484c48b2a2cSMatthias Ringwald             while (command_offset < size) {
2485c48b2a2cSMatthias Ringwald                 // handle signaling commands
2486c48b2a2cSMatthias Ringwald                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
2487c48b2a2cSMatthias Ringwald 
2488c48b2a2cSMatthias Ringwald                 // increment command_offset
2489c48b2a2cSMatthias Ringwald                 command_offset += L2CAP_SIGNALING_COMMAND_DATA_OFFSET + little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2490c48b2a2cSMatthias Ringwald             }
2491c48b2a2cSMatthias Ringwald             break;
2492c48b2a2cSMatthias Ringwald         }
249309e9d05bSMatthias Ringwald #endif
2494c48b2a2cSMatthias Ringwald 
2495e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
2496e7d0c9aaSMatthias Ringwald         case L2CAP_CID_SIGNALING_LE: {
2497e7d0c9aaSMatthias Ringwald             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
2498e7d0c9aaSMatthias Ringwald             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
2499c48b2a2cSMatthias Ringwald             if (!valid){
2500e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2501ccf076adS[email protected]             }
2502ccf076adS[email protected]             break;
2503e7d0c9aaSMatthias Ringwald         }
2504e7d0c9aaSMatthias Ringwald #endif
2505c48b2a2cSMatthias Ringwald 
2506c48b2a2cSMatthias Ringwald         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
2507c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback) {
2508c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2509ccf076adS[email protected]             }
2510c48b2a2cSMatthias Ringwald             break;
2511c48b2a2cSMatthias Ringwald 
2512c48b2a2cSMatthias Ringwald         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
2513c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback) {
2514c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2515c48b2a2cSMatthias Ringwald             }
2516c48b2a2cSMatthias Ringwald             break;
2517c48b2a2cSMatthias Ringwald 
2518c48b2a2cSMatthias Ringwald         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
2519c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback) {
2520c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
2521c48b2a2cSMatthias Ringwald             }
2522c48b2a2cSMatthias Ringwald             break;
25231bbc0b23S[email protected] 
252409e9d05bSMatthias Ringwald         default:
252509e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
252600d93d79Smatthias.ringwald             // Find channel for this channel_id and connection handle
252764e11ca9SMatthias Ringwald             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
2528d1fd2a88SMatthias Ringwald             if (l2cap_channel) {
252927e0774aSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
253027e0774aSMatthias Ringwald                 if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
253127e0774aSMatthias Ringwald 
253227e0774aSMatthias Ringwald                     // verify FCS
253327e0774aSMatthias Ringwald                     uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
253427e0774aSMatthias Ringwald                     uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
253527e0774aSMatthias Ringwald                     log_info("Packet FCS 0x%04x, calculated FCS 0x%04x", fcs_packet, fcs_calculated);
253627e0774aSMatthias Ringwald                     if (fcs_calculated != fcs_packet){
253727e0774aSMatthias Ringwald                         log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
253827e0774aSMatthias Ringwald                         // TODO: trigger retransmission or something like that
253927e0774aSMatthias Ringwald                         break;
254027e0774aSMatthias Ringwald                     }
254127e0774aSMatthias Ringwald 
254227e0774aSMatthias Ringwald                     // switch on packet type
254327e0774aSMatthias Ringwald                     uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
254438f62777SMatthias Ringwald                     uint8_t  req_seq = (control >> 8) & 0x3f;
254527e0774aSMatthias Ringwald                     if (control & 1){
254627e0774aSMatthias Ringwald                         // S-Frame
2547*78cd8a22SMatthias Ringwald                         int poll = (control >> 4) & 0x01;
2548bdbe2e49SMatthias Ringwald                         l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
2549bdbe2e49SMatthias Ringwald                         switch (s){
2550bdbe2e49SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
25512a424812SMatthias Ringwald                                 l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
2552*78cd8a22SMatthias Ringwald                                 if (poll){
2553*78cd8a22SMatthias Ringwald                                     l2cap_channel->send_supervisor_frame_receiver_ready_final = 1;
2554*78cd8a22SMatthias Ringwald                                 }
2555bdbe2e49SMatthias Ringwald                                 break;
2556bdbe2e49SMatthias Ringwald                             default:
2557bdbe2e49SMatthias Ringwald                                 break;
2558bdbe2e49SMatthias Ringwald                         }
255927e0774aSMatthias Ringwald                         break;
256027e0774aSMatthias Ringwald                     } else {
256127e0774aSMatthias Ringwald                         // I-Frame
256227e0774aSMatthias Ringwald                         // get control
256327e0774aSMatthias Ringwald                         l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
256438f62777SMatthias Ringwald                         uint8_t tx_seq = (control >> 1) & 0x3f;
256538f62777SMatthias Ringwald                         log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
256638f62777SMatthias Ringwald                         log_info("SAR: pos %u", l2cap_channel->rx_packets_state->pos);
256738f62777SMatthias Ringwald                         log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
25682a424812SMatthias Ringwald                         l2cap_ertm_handle_req_seq(l2cap_channel, req_seq);
256938f62777SMatthias Ringwald                         // check ordering
257038f62777SMatthias Ringwald                         if (l2cap_channel->expected_tx_seq == tx_seq){
257138f62777SMatthias Ringwald                             log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
257238f62777SMatthias Ringwald                             l2cap_channel->req_seq = tx_seq;
2573d84e866fSMatthias Ringwald                             l2cap_channel->send_supervisor_frame_receiver_ready = 1;
257438f62777SMatthias Ringwald                             l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
2575ed971c5aSMatthias Ringwald                             uint16_t sdu_length;
2576ed971c5aSMatthias Ringwald                             uint16_t segment_length;
2577ed971c5aSMatthias Ringwald                             uint16_t payload_offset;
257827e0774aSMatthias Ringwald                             switch (sar){
257927e0774aSMatthias Ringwald                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
2580ed971c5aSMatthias Ringwald                                     payload_offset = COMPLETE_L2CAP_HEADER+2;
2581ed971c5aSMatthias Ringwald                                     segment_length = payload_offset-2;
2582ed971c5aSMatthias Ringwald                                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER+2], segment_length);
258327e0774aSMatthias Ringwald                                     break;
258427e0774aSMatthias Ringwald                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
2585ed971c5aSMatthias Ringwald                                     // TODO: use current packet
2586ed971c5aSMatthias Ringwald                                     // TODO: check if reassembly started
2587ed971c5aSMatthias Ringwald                                     // TODO: check len against local mtu
2588ed971c5aSMatthias Ringwald                                     sdu_length = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER+2);
2589ed971c5aSMatthias Ringwald                                     payload_offset = COMPLETE_L2CAP_HEADER+4;
2590ed971c5aSMatthias Ringwald                                     segment_length = size - payload_offset-2;
2591ed971c5aSMatthias Ringwald                                     memcpy(&l2cap_channel->rx_packets_data[0], &packet[payload_offset], segment_length);
2592ed971c5aSMatthias Ringwald                                     l2cap_channel->rx_packets_state->sdu_length = sdu_length;
2593ed971c5aSMatthias Ringwald                                     l2cap_channel->rx_packets_state->pos = segment_length;
2594ed971c5aSMatthias Ringwald                                     break;
259527e0774aSMatthias Ringwald                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
2596ed971c5aSMatthias Ringwald                                     payload_offset = COMPLETE_L2CAP_HEADER+2;
2597ed971c5aSMatthias Ringwald                                     segment_length = size - payload_offset-2;
2598ed971c5aSMatthias Ringwald                                     memcpy(&l2cap_channel->rx_packets_data[l2cap_channel->rx_packets_state->pos], &packet[payload_offset], segment_length);
2599ed971c5aSMatthias Ringwald                                     l2cap_channel->rx_packets_state->pos += segment_length;
2600ed971c5aSMatthias Ringwald                                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->rx_packets_data, l2cap_channel->rx_packets_state[0].pos);
2601ed971c5aSMatthias Ringwald                                     break;
260227e0774aSMatthias Ringwald                                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
2603ed971c5aSMatthias Ringwald                                     payload_offset = COMPLETE_L2CAP_HEADER+2;
2604ed971c5aSMatthias Ringwald                                     segment_length = size - payload_offset-2;
2605ed971c5aSMatthias Ringwald                                     memcpy(&l2cap_channel->rx_packets_data[l2cap_channel->rx_packets_state->pos], &packet[payload_offset], segment_length);
2606ed971c5aSMatthias Ringwald                                     l2cap_channel->rx_packets_state->pos += segment_length;
260727e0774aSMatthias Ringwald                                     break;
260827e0774aSMatthias Ringwald                                 }
260927e0774aSMatthias Ringwald                             }
261038f62777SMatthias Ringwald                         }
261127e0774aSMatthias Ringwald                     break;
261227e0774aSMatthias Ringwald                 }
261327e0774aSMatthias Ringwald #endif
26143d50b4baSMatthias Ringwald                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
261500d93d79Smatthias.ringwald             }
261609e9d05bSMatthias Ringwald #endif
2617a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
261864e11ca9SMatthias Ringwald             l2cap_channel = l2cap_le_get_channel_for_local_cid(channel_id);
261964e11ca9SMatthias Ringwald             if (l2cap_channel) {
262085aeef60SMatthias Ringwald                 // credit counting
262185aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming == 0){
262285aeef60SMatthias Ringwald                     log_error("LE Data Channel packet received but no incoming credits");
262385aeef60SMatthias Ringwald                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
262485aeef60SMatthias Ringwald                     break;
262585aeef60SMatthias Ringwald                 }
262685aeef60SMatthias Ringwald                 l2cap_channel->credits_incoming--;
262785aeef60SMatthias Ringwald 
262885aeef60SMatthias Ringwald                 // automatic credits
262985aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){
263085aeef60SMatthias Ringwald                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
263185aeef60SMatthias Ringwald                 }
263285aeef60SMatthias Ringwald 
2633cd529728SMatthias Ringwald                 // first fragment
2634cd529728SMatthias Ringwald                 uint16_t pos = 0;
2635cd529728SMatthias Ringwald                 if (!l2cap_channel->receive_sdu_len){
2636cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
2637cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_pos = 0;
2638cd529728SMatthias Ringwald                     pos  += 2;
2639cd529728SMatthias Ringwald                     size -= 2;
2640cd529728SMatthias Ringwald                 }
2641cd529728SMatthias Ringwald                 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], size-COMPLETE_L2CAP_HEADER);
2642cd529728SMatthias Ringwald                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
2643cd529728SMatthias Ringwald                 // done?
264463f0ac45SMatthias Ringwald                 log_info("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
2645cd529728SMatthias Ringwald                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
2646cd529728SMatthias Ringwald                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
2647cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = 0;
2648cd529728SMatthias Ringwald                 }
264963f0ac45SMatthias Ringwald             } else {
265063f0ac45SMatthias Ringwald                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
265164e11ca9SMatthias Ringwald             }
265264e11ca9SMatthias Ringwald #endif
26535652b5ffS[email protected]             break;
26545652b5ffS[email protected]     }
265500d93d79Smatthias.ringwald 
26561eb2563eS[email protected]     l2cap_run();
26572718e2e7Smatthias.ringwald }
265800d93d79Smatthias.ringwald 
265909e9d05bSMatthias Ringwald // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
266009e9d05bSMatthias Ringwald void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
266109e9d05bSMatthias Ringwald     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
266209e9d05bSMatthias Ringwald     if (index < 0) return;
266309e9d05bSMatthias Ringwald     fixed_channels[index].callback = the_packet_handler;
266409e9d05bSMatthias Ringwald }
266509e9d05bSMatthias Ringwald 
266609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
266715ec09bbSmatthias.ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
266827a923d0Smatthias.ringwald void l2cap_finialize_channel_close(l2cap_channel_t * channel){
2669f62db1e3Smatthias.ringwald     channel->state = L2CAP_STATE_CLOSED;
2670f62db1e3Smatthias.ringwald     l2cap_emit_channel_closed(channel);
2671f62db1e3Smatthias.ringwald     // discard channel
26729dcb2fb2S[email protected]     l2cap_stop_rtx(channel);
2673665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2674d3a9df87Smatthias.ringwald     btstack_memory_l2cap_channel_free(channel);
2675c8e4258aSmatthias.ringwald }
26761e6aba47Smatthias.ringwald 
26778f2a52f4SMatthias Ringwald static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
2678665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
2679665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, services);
2680665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2681665d90f2SMatthias Ringwald         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
26829d9bbc01Smatthias.ringwald         if ( service->psm == psm){
26839d9bbc01Smatthias.ringwald             return service;
26849d9bbc01Smatthias.ringwald         };
26859d9bbc01Smatthias.ringwald     }
26869d9bbc01Smatthias.ringwald     return NULL;
26879d9bbc01Smatthias.ringwald }
26889d9bbc01Smatthias.ringwald 
26897192e786SMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
26907192e786SMatthias Ringwald     return l2cap_get_service_internal(&l2cap_services, psm);
26917192e786SMatthias Ringwald }
26927192e786SMatthias Ringwald 
2693e0abb8e7S[email protected] 
2694be2053a6SMatthias 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){
2695be2053a6SMatthias Ringwald 
2696be2053a6SMatthias Ringwald     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
2697e0abb8e7S[email protected] 
26984bb582b6Smatthias.ringwald     // check for alread registered psm
26999d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
2700277abc2cSmatthias.ringwald     if (service) {
2701be2053a6SMatthias Ringwald         log_error("l2cap_register_service: PSM %u already registered", psm);
2702be2053a6SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
2703277abc2cSmatthias.ringwald     }
27049d9bbc01Smatthias.ringwald 
27054bb582b6Smatthias.ringwald     // alloc structure
2706bb69aaaeS[email protected]     service = btstack_memory_l2cap_service_get();
2707277abc2cSmatthias.ringwald     if (!service) {
2708be2053a6SMatthias Ringwald         log_error("l2cap_register_service: no memory for l2cap_service_t");
2709be2053a6SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
2710277abc2cSmatthias.ringwald     }
27119d9bbc01Smatthias.ringwald 
27129d9bbc01Smatthias.ringwald     // fill in
27139d9bbc01Smatthias.ringwald     service->psm = psm;
27149d9bbc01Smatthias.ringwald     service->mtu = mtu;
271505ae8de3SMatthias Ringwald     service->packet_handler = service_packet_handler;
2716df3354fcS[email protected]     service->required_security_level = security_level;
27179d9bbc01Smatthias.ringwald 
27189d9bbc01Smatthias.ringwald     // add to services list
2719665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
2720c0e866bfSmatthias.ringwald 
2721c0e866bfSmatthias.ringwald     // enable page scan
272215a95bd5SMatthias Ringwald     gap_connectable_control(1);
27235842b6d9Smatthias.ringwald 
2724be2053a6SMatthias Ringwald     return 0;
27259d9bbc01Smatthias.ringwald }
27269d9bbc01Smatthias.ringwald 
27277e8856ebSMatthias Ringwald uint8_t l2cap_unregister_service(uint16_t psm){
2728e0abb8e7S[email protected] 
2729e0abb8e7S[email protected]     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
2730e0abb8e7S[email protected] 
27319d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
27327e8856ebSMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2733665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
2734d3a9df87Smatthias.ringwald     btstack_memory_l2cap_service_free(service);
2735c0e866bfSmatthias.ringwald 
2736c0e866bfSmatthias.ringwald     // disable page scan when no services registered
27377e8856ebSMatthias Ringwald     if (btstack_linked_list_empty(&l2cap_services)) {
273815a95bd5SMatthias Ringwald         gap_connectable_control(0);
27399d9bbc01Smatthias.ringwald     }
27407e8856ebSMatthias Ringwald     return 0;
27417e8856ebSMatthias Ringwald }
274209e9d05bSMatthias Ringwald #endif
27439d9bbc01Smatthias.ringwald 
27447192e786SMatthias Ringwald 
2745cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
274683fd9c76SMatthias Ringwald 
274757be49d6SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
274857be49d6SMatthias Ringwald     if (!channel->waiting_for_can_send_now) return;
274957be49d6SMatthias Ringwald     if (channel->send_sdu_buffer) return;
275057be49d6SMatthias Ringwald     channel->waiting_for_can_send_now = 0;
275157be49d6SMatthias Ringwald     log_info("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
275257be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
275357be49d6SMatthias Ringwald }
275457be49d6SMatthias Ringwald 
275557be49d6SMatthias Ringwald // 1BH2222
275657be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
275757be49d6SMatthias 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",
275857be49d6SMatthias Ringwald              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
275957be49d6SMatthias Ringwald     uint8_t event[19];
276057be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
276157be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
276257be49d6SMatthias Ringwald     event[2] = channel->address_type;
276357be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
276457be49d6SMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
276557be49d6SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
276657be49d6SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
276757be49d6SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
276857be49d6SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_mtu);
276957be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
277057be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
277157be49d6SMatthias Ringwald }
277257be49d6SMatthias Ringwald // 11BH22222
277357be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
277457be49d6SMatthias 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",
277557be49d6SMatthias Ringwald              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
277657be49d6SMatthias Ringwald              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
2777c99bb618SMatthias Ringwald     uint8_t event[23];
277857be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
277957be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
278057be49d6SMatthias Ringwald     event[2] = status;
278157be49d6SMatthias Ringwald     event[3] = channel->address_type;
278257be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[4]);
278357be49d6SMatthias Ringwald     little_endian_store_16(event, 10, channel->con_handle);
2784c99bb618SMatthias Ringwald     event[12] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
2785c99bb618SMatthias Ringwald     little_endian_store_16(event, 13, channel->psm);
2786c99bb618SMatthias Ringwald     little_endian_store_16(event, 15, channel->local_cid);
2787c99bb618SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_cid);
2788c99bb618SMatthias Ringwald     little_endian_store_16(event, 19, channel->local_mtu);
2789c99bb618SMatthias Ringwald     little_endian_store_16(event, 21, channel->remote_mtu);
279057be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
279157be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
279257be49d6SMatthias Ringwald }
279357be49d6SMatthias Ringwald 
279457be49d6SMatthias Ringwald static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid){
279557be49d6SMatthias Ringwald     btstack_linked_list_iterator_t it;
279657be49d6SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
279757be49d6SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
279857be49d6SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
279957be49d6SMatthias Ringwald         if ( channel->local_cid == local_cid) {
280057be49d6SMatthias Ringwald             return channel;
280157be49d6SMatthias Ringwald         }
280257be49d6SMatthias Ringwald     }
280357be49d6SMatthias Ringwald     return NULL;
280457be49d6SMatthias Ringwald }
280557be49d6SMatthias Ringwald 
280657be49d6SMatthias Ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
280757be49d6SMatthias Ringwald void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
280857be49d6SMatthias Ringwald     channel->state = L2CAP_STATE_CLOSED;
280957be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
281057be49d6SMatthias Ringwald     // discard channel
281157be49d6SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
281257be49d6SMatthias Ringwald     btstack_memory_l2cap_channel_free(channel);
281357be49d6SMatthias Ringwald }
281457be49d6SMatthias Ringwald 
2815e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
2816e7d0c9aaSMatthias Ringwald     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
28177192e786SMatthias Ringwald }
2818efedfb4cSMatthias Ringwald 
2819da144af5SMatthias Ringwald uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
28207192e786SMatthias Ringwald 
2821da144af5SMatthias Ringwald     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
28227192e786SMatthias Ringwald 
28237192e786SMatthias Ringwald     // check for alread registered psm
28247192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
28257192e786SMatthias Ringwald     if (service) {
2826da144af5SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
28277192e786SMatthias Ringwald     }
28287192e786SMatthias Ringwald 
28297192e786SMatthias Ringwald     // alloc structure
28307192e786SMatthias Ringwald     service = btstack_memory_l2cap_service_get();
28317192e786SMatthias Ringwald     if (!service) {
28327192e786SMatthias Ringwald         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
2833da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
28347192e786SMatthias Ringwald     }
28357192e786SMatthias Ringwald 
28367192e786SMatthias Ringwald     // fill in
28377192e786SMatthias Ringwald     service->psm = psm;
2838da144af5SMatthias Ringwald     service->mtu = 0;
28397192e786SMatthias Ringwald     service->packet_handler = packet_handler;
28407192e786SMatthias Ringwald     service->required_security_level = security_level;
28417192e786SMatthias Ringwald 
28427192e786SMatthias Ringwald     // add to services list
2843665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
28447192e786SMatthias Ringwald 
28457192e786SMatthias Ringwald     // done
2846da144af5SMatthias Ringwald     return 0;
28477192e786SMatthias Ringwald }
28487192e786SMatthias Ringwald 
2849da144af5SMatthias Ringwald uint8_t l2cap_le_unregister_service(uint16_t psm) {
28507192e786SMatthias Ringwald     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
28517192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
28529367f9b0SMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
2853da144af5SMatthias Ringwald 
2854665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
28557192e786SMatthias Ringwald     btstack_memory_l2cap_service_free(service);
2856da144af5SMatthias Ringwald     return 0;
28577192e786SMatthias Ringwald }
2858da144af5SMatthias Ringwald 
2859da144af5SMatthias Ringwald uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
2860e7d0c9aaSMatthias Ringwald     // get channel
2861e7d0c9aaSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2862e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2863e7d0c9aaSMatthias Ringwald 
2864e7d0c9aaSMatthias Ringwald     // validate state
2865e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2866e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
2867e7d0c9aaSMatthias Ringwald     }
2868e7d0c9aaSMatthias Ringwald 
2869efedfb4cSMatthias Ringwald     // set state accept connection
287023017473SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
287123017473SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
287223017473SMatthias Ringwald     channel->local_mtu = mtu;
287385aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
287485aeef60SMatthias Ringwald     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
287585aeef60SMatthias Ringwald 
287685aeef60SMatthias Ringwald     // test
287763f0ac45SMatthias Ringwald     // channel->new_credits_incoming = 1;
2878e7d0c9aaSMatthias Ringwald 
2879e7d0c9aaSMatthias Ringwald     // go
2880e7d0c9aaSMatthias Ringwald     l2cap_run();
2881da144af5SMatthias Ringwald     return 0;
2882da144af5SMatthias Ringwald }
2883da144af5SMatthias Ringwald 
2884da144af5SMatthias Ringwald /**
2885da144af5SMatthias Ringwald  * @brief Deny incoming LE Data Channel connection due to resource constraints
2886da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2887da144af5SMatthias Ringwald  */
2888da144af5SMatthias Ringwald 
2889da144af5SMatthias Ringwald uint8_t l2cap_le_decline_connection(uint16_t local_cid){
2890e7d0c9aaSMatthias Ringwald     // get channel
2891e7d0c9aaSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
2892e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2893e7d0c9aaSMatthias Ringwald 
2894e7d0c9aaSMatthias Ringwald     // validate state
2895e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
2896e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
2897e7d0c9aaSMatthias Ringwald     }
2898e7d0c9aaSMatthias Ringwald 
2899efedfb4cSMatthias Ringwald     // set state decline connection
2900e7d0c9aaSMatthias Ringwald     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
2901e7d0c9aaSMatthias Ringwald     channel->reason = 0x04; // no resources available
2902e7d0c9aaSMatthias Ringwald     l2cap_run();
2903da144af5SMatthias Ringwald     return 0;
2904da144af5SMatthias Ringwald }
2905da144af5SMatthias Ringwald 
29067dafa750SMatthias Ringwald uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
2907da144af5SMatthias Ringwald     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
2908efedfb4cSMatthias Ringwald     uint16_t * out_local_cid) {
2909efedfb4cSMatthias Ringwald 
29107dafa750SMatthias Ringwald     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
2911da144af5SMatthias Ringwald 
29127dafa750SMatthias Ringwald 
29137dafa750SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
29147dafa750SMatthias Ringwald     if (!connection) {
29157dafa750SMatthias Ringwald         log_error("no hci_connection for handle 0x%04x", con_handle);
29167dafa750SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
29177dafa750SMatthias Ringwald     }
29187dafa750SMatthias Ringwald 
29197dafa750SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, connection->address, connection->address_type, psm, mtu, security_level);
2920da144af5SMatthias Ringwald     if (!channel) {
2921da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
2922da144af5SMatthias Ringwald     }
2923e7d0c9aaSMatthias Ringwald     log_info("l2cap_le_create_channel %p", channel);
2924da144af5SMatthias Ringwald 
2925da144af5SMatthias Ringwald     // store local_cid
2926da144af5SMatthias Ringwald     if (out_local_cid){
2927da144af5SMatthias Ringwald        *out_local_cid = channel->local_cid;
2928da144af5SMatthias Ringwald     }
2929da144af5SMatthias Ringwald 
29307dafa750SMatthias Ringwald     // provide buffer
29317dafa750SMatthias Ringwald     channel->con_handle = con_handle;
2932cd529728SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
29337dafa750SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
293485aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
293585aeef60SMatthias Ringwald     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
293685aeef60SMatthias Ringwald 
2937efedfb4cSMatthias Ringwald     // add to connections list
2938efedfb4cSMatthias Ringwald     btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2939efedfb4cSMatthias Ringwald 
29407dafa750SMatthias Ringwald     // go
294163f0ac45SMatthias Ringwald     l2cap_run();
2942da144af5SMatthias Ringwald     return 0;
2943da144af5SMatthias Ringwald }
2944da144af5SMatthias Ringwald 
2945da144af5SMatthias Ringwald /**
2946da144af5SMatthias Ringwald  * @brief Provide credtis for LE Data Channel
2947da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2948da144af5SMatthias Ringwald  * @param credits               Number additional credits for peer
2949da144af5SMatthias Ringwald  */
295064e11ca9SMatthias Ringwald uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
295163f0ac45SMatthias Ringwald 
295263f0ac45SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
295363f0ac45SMatthias Ringwald     if (!channel) {
295463f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
295563f0ac45SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
295663f0ac45SMatthias Ringwald     }
295763f0ac45SMatthias Ringwald 
2958efedfb4cSMatthias Ringwald     // check state
295963f0ac45SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN){
296063f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
296163f0ac45SMatthias Ringwald     }
296263f0ac45SMatthias Ringwald 
296363f0ac45SMatthias Ringwald     // assert incoming credits + credits <= 0xffff
296463f0ac45SMatthias Ringwald     uint32_t total_credits = channel->credits_incoming;
296563f0ac45SMatthias Ringwald     total_credits += channel->new_credits_incoming;
296663f0ac45SMatthias Ringwald     total_credits += credits;
296763f0ac45SMatthias Ringwald     if (total_credits > 0xffff){
296863f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
296963f0ac45SMatthias Ringwald             channel->new_credits_incoming, credits);
297063f0ac45SMatthias Ringwald     }
297163f0ac45SMatthias Ringwald 
2972efedfb4cSMatthias Ringwald     // set credits_granted
297363f0ac45SMatthias Ringwald     channel->new_credits_incoming += credits;
297463f0ac45SMatthias Ringwald 
297563f0ac45SMatthias Ringwald     // go
297663f0ac45SMatthias Ringwald     l2cap_run();
2977da144af5SMatthias Ringwald     return 0;
2978da144af5SMatthias Ringwald }
2979da144af5SMatthias Ringwald 
2980da144af5SMatthias Ringwald /**
2981da144af5SMatthias Ringwald  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
2982da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
2983da144af5SMatthias Ringwald  */
298464e11ca9SMatthias Ringwald int l2cap_le_can_send_now(uint16_t local_cid){
298544276248SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
298644276248SMatthias Ringwald     if (!channel) {
298744276248SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
2988da144af5SMatthias Ringwald         return 0;
2989da144af5SMatthias Ringwald     }
2990da144af5SMatthias Ringwald 
299144276248SMatthias Ringwald     // check state
299244276248SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN) return 0;
299344276248SMatthias Ringwald 
299444276248SMatthias Ringwald     // check queue
299544276248SMatthias Ringwald     if (channel->send_sdu_buffer) return 0;
299644276248SMatthias Ringwald 
299744276248SMatthias Ringwald     // fine, go ahead
299844276248SMatthias Ringwald     return 1;
299944276248SMatthias Ringwald }
300044276248SMatthias Ringwald 
3001da144af5SMatthias Ringwald /**
3002da144af5SMatthias Ringwald  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
3003da144af5SMatthias Ringwald  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
3004da144af5SMatthias Ringwald  *       so packet handler should be ready to handle it
3005da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3006da144af5SMatthias Ringwald  */
300764e11ca9SMatthias Ringwald uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
300844276248SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
300944276248SMatthias Ringwald     if (!channel) {
301044276248SMatthias Ringwald         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
301144276248SMatthias Ringwald         return 0;
301244276248SMatthias Ringwald     }
301344276248SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
301444276248SMatthias Ringwald     l2cap_le_notify_channel_can_send(channel);
3015da144af5SMatthias Ringwald     return 0;
3016da144af5SMatthias Ringwald }
3017da144af5SMatthias Ringwald 
3018da144af5SMatthias Ringwald /**
3019da144af5SMatthias Ringwald  * @brief Send data via LE Data Channel
3020da144af5SMatthias Ringwald  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
3021da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3022da144af5SMatthias Ringwald  * @param data                  data to send
3023da144af5SMatthias Ringwald  * @param size                  data size
3024da144af5SMatthias Ringwald  */
302564e11ca9SMatthias Ringwald uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
302664e11ca9SMatthias Ringwald 
302764e11ca9SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
302864e11ca9SMatthias Ringwald     if (!channel) {
302964e11ca9SMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
3030828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
303164e11ca9SMatthias Ringwald     }
303264e11ca9SMatthias Ringwald 
303364e11ca9SMatthias Ringwald     if (len > channel->remote_mtu){
303464e11ca9SMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
303564e11ca9SMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
303664e11ca9SMatthias Ringwald     }
303764e11ca9SMatthias Ringwald 
30387f107edaSMatthias Ringwald     if (channel->send_sdu_buffer){
303964e11ca9SMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
304064e11ca9SMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
304164e11ca9SMatthias Ringwald     }
304264e11ca9SMatthias Ringwald 
30437f107edaSMatthias Ringwald     channel->send_sdu_buffer = data;
30447f107edaSMatthias Ringwald     channel->send_sdu_len    = len;
30457f107edaSMatthias Ringwald     channel->send_sdu_pos    = 0;
304664e11ca9SMatthias Ringwald 
30477f107edaSMatthias Ringwald     l2cap_run();
30487f107edaSMatthias Ringwald     return 0;
3049da144af5SMatthias Ringwald }
3050da144af5SMatthias Ringwald 
3051da144af5SMatthias Ringwald /**
3052da144af5SMatthias Ringwald  * @brief Disconnect from LE Data Channel
3053da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3054da144af5SMatthias Ringwald  */
3055828a7f7aSMatthias Ringwald uint8_t l2cap_le_disconnect(uint16_t local_cid)
3056da144af5SMatthias Ringwald {
3057828a7f7aSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3058828a7f7aSMatthias Ringwald     if (!channel) {
3059828a7f7aSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
3060828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3061828a7f7aSMatthias Ringwald     }
3062828a7f7aSMatthias Ringwald 
3063828a7f7aSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3064828a7f7aSMatthias Ringwald     l2cap_run();
3065da144af5SMatthias Ringwald     return 0;
3066da144af5SMatthias Ringwald }
3067da144af5SMatthias Ringwald 
30687f02f414SMatthias Ringwald #endif
3069