xref: /btstack/src/l2cap.c (revision 817374d9311d11f758da54058db0409ee4e27a6c)
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 
38e501bae0SMatthias 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"
5284e3541eSMilanka Ringwald #include "bluetooth_psm.h"
5316ece135SMatthias Ringwald #include "btstack_debug.h"
540e2df43fSMatthias Ringwald #include "btstack_event.h"
55d3a9df87Smatthias.ringwald #include "btstack_memory.h"
5643625864Smatthias.ringwald 
5743625864Smatthias.ringwald #include <stdarg.h>
5843625864Smatthias.ringwald #include <string.h>
5943625864Smatthias.ringwald 
6043625864Smatthias.ringwald #include <stdio.h>
6143625864Smatthias.ringwald 
62a6e314f1SMatthias Ringwald /*
63a6e314f1SMatthias Ringwald  * @brief L2CAP Supervisory function in S-Frames
64a6e314f1SMatthias Ringwald  */
65a6e314f1SMatthias Ringwald typedef enum {
66a6e314f1SMatthias Ringwald     L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY = 0,
67a6e314f1SMatthias Ringwald     L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT,
68a6e314f1SMatthias Ringwald     L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY,
69a6e314f1SMatthias Ringwald     L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT
70a6e314f1SMatthias Ringwald } l2cap_supervisory_function_t;
71a6e314f1SMatthias Ringwald 
72a6e314f1SMatthias Ringwald /**
73a6e314f1SMatthias Ringwald  * @brief L2CAP Information Types used in Information Request & Response
74a6e314f1SMatthias Ringwald  */
75a6e314f1SMatthias Ringwald typedef enum {
76a6e314f1SMatthias Ringwald   L2CAP_INFO_TYPE_CONNECTIONLESS_MTU = 1,
77a6e314f1SMatthias Ringwald   L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED,
78a6e314f1SMatthias Ringwald   L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED,
79a6e314f1SMatthias Ringwald } l2cap_info_type_t;
80a6e314f1SMatthias Ringwald 
81a6e314f1SMatthias Ringwald /**
82a6e314f1SMatthias Ringwald  * @brief L2CAP Configuration Option Types used in Configurateion Request & Response
83a6e314f1SMatthias Ringwald  */
84a6e314f1SMatthias Ringwald typedef enum {
85a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT = 1,
86a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT,
87a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_QUALITY_OF_SERVICE,
88a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL,
89a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE,
90a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_EXTENDED_FLOW_SPECIFICATION,
91a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE,
92a6e314f1SMatthias Ringwald } l2cap_config_option_type_t;
93a6e314f1SMatthias Ringwald 
94a6e314f1SMatthias Ringwald 
95a6e314f1SMatthias Ringwald #define L2CAP_SIG_ID_INVALID 0
96a6e314f1SMatthias Ringwald 
97a6e314f1SMatthias Ringwald // size of HCI ACL + L2CAP Header for regular data packets (8)
98a6e314f1SMatthias Ringwald #define COMPLETE_L2CAP_HEADER (HCI_ACL_HEADER_SIZE + L2CAP_HEADER_SIZE)
99a6e314f1SMatthias Ringwald 
100a6e314f1SMatthias Ringwald // L2CAP Configuration Result Codes
101a6e314f1SMatthias Ringwald #define L2CAP_CONF_RESULT_SUCCESS                  0x0000
102a6e314f1SMatthias Ringwald #define L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS  0x0001
103a6e314f1SMatthias Ringwald #define L2CAP_CONF_RESULT_REJECT                   0x0002
104a6e314f1SMatthias Ringwald #define L2CAP_CONF_RESULT_UNKNOWN_OPTIONS          0x0003
105a6e314f1SMatthias Ringwald #define L2CAP_CONF_RESULT_PENDING                  0x0004
106a6e314f1SMatthias Ringwald #define L2CAP_CONF_RESULT_FLOW_SPEC_REJECTED       0x0005
107a6e314f1SMatthias Ringwald 
108a6e314f1SMatthias Ringwald // L2CAP Reject Result Codes
109a6e314f1SMatthias Ringwald #define L2CAP_REJ_CMD_UNKNOWN                      0x0000
110a6e314f1SMatthias Ringwald 
111a6e314f1SMatthias Ringwald // Response Timeout eXpired
112a6e314f1SMatthias Ringwald #define L2CAP_RTX_TIMEOUT_MS   10000
113a6e314f1SMatthias Ringwald 
114a6e314f1SMatthias Ringwald // Extended Response Timeout eXpired
115a6e314f1SMatthias Ringwald #define L2CAP_ERTX_TIMEOUT_MS 120000
116a6e314f1SMatthias Ringwald 
1174c744e21Smatthias.ringwald // nr of buffered acl packets in outgoing queue to get max performance
1184c744e21Smatthias.ringwald #define NR_BUFFERED_ACL_PACKETS 3
1194c744e21Smatthias.ringwald 
12039bda6d5Smatthias.ringwald // used to cache l2cap rejects, echo, and informational requests
121e16a9cacSmatthias.ringwald #define NR_PENDING_SIGNALING_RESPONSES 3
12239bda6d5Smatthias.ringwald 
12385aeef60SMatthias Ringwald // nr of credits provided to remote if credits fall below watermark
12485aeef60SMatthias Ringwald #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK 5
12585aeef60SMatthias Ringwald #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT 5
12685aeef60SMatthias Ringwald 
12700d93d79Smatthias.ringwald // offsets for L2CAP SIGNALING COMMANDS
12800d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
12900d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
13000d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
13100d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
13200d93d79Smatthias.ringwald 
13309e9d05bSMatthias Ringwald #if defined(ENABLE_LE_DATA_CHANNELS) || defined(ENABLE_CLASSIC)
13409e9d05bSMatthias Ringwald #define L2CAP_USES_CHANNELS
13509e9d05bSMatthias Ringwald #endif
13609e9d05bSMatthias Ringwald 
13733c40538SMatthias Ringwald // prototypes
138675e6881SMatthias Ringwald static void l2cap_run(void);
13933c40538SMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
1403d50b4baSMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size );
14130725612SMatthias Ringwald static void l2cap_notify_channel_can_send(void);
14209e9d05bSMatthias Ringwald static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel);
1436ddef68dSMilanka Ringwald static uint8_t  l2cap_next_sig_id(void);
1447740e150SMatthias Ringwald static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid);
14509e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
146474f5c3fSMatthias Ringwald static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel);
147474f5c3fSMatthias Ringwald static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel);
14809e9d05bSMatthias Ringwald static void l2cap_finialize_channel_close(l2cap_channel_t *channel);
14909e9d05bSMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm);
15009e9d05bSMatthias Ringwald static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
15109e9d05bSMatthias Ringwald static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
15209e9d05bSMatthias Ringwald static void l2cap_emit_incoming_connection(l2cap_channel_t *channel);
15309e9d05bSMatthias Ringwald static int  l2cap_channel_ready_for_open(l2cap_channel_t *channel);
15409e9d05bSMatthias Ringwald #endif
155cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
15657be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status);
15787050a0bSMatthias Ringwald static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel);
15857be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel);
15944276248SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel);
160828a7f7aSMatthias Ringwald static void l2cap_le_finialize_channel_close(l2cap_channel_t *channel);
1616774d5c9SMatthias Ringwald static void l2cap_le_send_pdu(l2cap_channel_t *channel);
162e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t psm);
163e7d0c9aaSMatthias Ringwald #endif
164474f5c3fSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
1656a5ffed8SMatthias Ringwald static uint16_t l2cap_next_local_cid(void);
1666a5ffed8SMatthias Ringwald static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid);
167836ae835SMatthias Ringwald static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code);
168474f5c3fSMatthias Ringwald static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size);
169474f5c3fSMatthias Ringwald static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid);
1705d18f623SMatthias Ringwald static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, l2cap_channel_type_t channel_type, bd_addr_t address, bd_addr_type_t address_type,
171474f5c3fSMatthias Ringwald         uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level);
172c45d6b2cSMatthias Ringwald static void l2cap_free_channel_entry(l2cap_channel_t * channel);
173474f5c3fSMatthias Ringwald #endif
174212b6be2SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
17596646001SMatthias Ringwald static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel);
176c9300dcaSMatthias Ringwald static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts);
1778a700052SMatthias Ringwald static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts);
178212b6be2SMatthias Ringwald #endif
17933c40538SMatthias Ringwald 
180fad84cafSMatthias Ringwald // l2cap_fixed_channel_t entries
18124eb964eSMatthias Ringwald #ifdef ENABLE_BLE
182fad84cafSMatthias Ringwald static l2cap_fixed_channel_t l2cap_fixed_channel_att;
183fad84cafSMatthias Ringwald static l2cap_fixed_channel_t l2cap_fixed_channel_sm;
18424eb964eSMatthias Ringwald #endif
18524eb964eSMatthias Ringwald #ifdef ENABLE_CLASSIC
186fad84cafSMatthias Ringwald static l2cap_fixed_channel_t l2cap_fixed_channel_connectionless;
18724eb964eSMatthias Ringwald #endif
1885628cf69SMatthias Ringwald 
18909e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1905628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_services;
19109e9d05bSMatthias Ringwald static uint8_t require_security_level2_for_outgoing_sdp;
192ece97caeSMatthias Ringwald static bd_addr_t l2cap_outgoing_classic_addr;
19309e9d05bSMatthias Ringwald #endif
19457be49d6SMatthias Ringwald 
19557be49d6SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1965628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_le_services;
19757be49d6SMatthias Ringwald #endif
19839bda6d5Smatthias.ringwald 
199fad84cafSMatthias Ringwald // single list of channels for Classic Channels, LE Data Channels, Classic Connectionless, ATT, and SM
200421cb104SMatthias Ringwald static btstack_linked_list_t l2cap_channels;
2016a5ffed8SMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
2026ddef68dSMilanka Ringwald // next channel id for new connections
2036ddef68dSMilanka Ringwald static uint16_t  local_source_cid  = 0x40;
2046a5ffed8SMatthias Ringwald #endif
2056ddef68dSMilanka Ringwald // next signaling sequence number
2066ddef68dSMilanka Ringwald static uint8_t   sig_seq_nr  = 0xff;
207421cb104SMatthias Ringwald 
20839bda6d5Smatthias.ringwald // used to cache l2cap rejects, echo, and informational requests
2092b83fb7dSmatthias.ringwald static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
2102b83fb7dSmatthias.ringwald static int signaling_responses_pending;
211fb37a842SMatthias Ringwald static btstack_packet_callback_registration_t hci_event_callback_registration;
21239bda6d5Smatthias.ringwald 
213d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
214d6ed9f9cSMatthias Ringwald // only used for connection parameter update events
215d6ed9f9cSMatthias Ringwald static btstack_packet_handler_t l2cap_event_packet_handler;
21625818320SMatthias Ringwald static uint16_t l2cap_le_custom_max_mtu;
217d6ed9f9cSMatthias Ringwald #endif
218d6ed9f9cSMatthias Ringwald 
21985ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
22085ddcd84SMatthias Ringwald 
221e288be62SMatthias Ringwald // enable for testing
222e288be62SMatthias Ringwald // #define L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL 16
223e288be62SMatthias Ringwald 
22485ddcd84SMatthias Ringwald /*
22585ddcd84SMatthias Ringwald  * CRC lookup table for generator polynom D^16 + D^15 + D^2 + 1
22685ddcd84SMatthias Ringwald  */
22785ddcd84SMatthias Ringwald static const uint16_t crc16_table[256] = {
22885ddcd84SMatthias Ringwald     0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
22985ddcd84SMatthias Ringwald     0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841,
23085ddcd84SMatthias Ringwald     0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41,
23185ddcd84SMatthias Ringwald     0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040,
23285ddcd84SMatthias Ringwald     0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441,
23385ddcd84SMatthias Ringwald     0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840,
23485ddcd84SMatthias Ringwald     0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40,
23585ddcd84SMatthias Ringwald     0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041,
23685ddcd84SMatthias Ringwald     0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
23785ddcd84SMatthias Ringwald     0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840,
23885ddcd84SMatthias Ringwald     0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
23985ddcd84SMatthias Ringwald     0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041,
24085ddcd84SMatthias Ringwald     0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440,
24185ddcd84SMatthias Ringwald     0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841,
24285ddcd84SMatthias Ringwald     0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41,
24385ddcd84SMatthias Ringwald     0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040,
24485ddcd84SMatthias Ringwald };
24585ddcd84SMatthias Ringwald 
24685ddcd84SMatthias Ringwald static uint16_t crc16_calc(uint8_t * data, uint16_t len){
24785ddcd84SMatthias Ringwald     uint16_t crc = 0;   // initial value = 0
24885ddcd84SMatthias Ringwald     while (len--){
24985ddcd84SMatthias Ringwald         crc = (crc >> 8) ^ crc16_table[ (crc ^ ((uint16_t) *data++)) & 0x00FF ];
25085ddcd84SMatthias Ringwald     }
25185ddcd84SMatthias Ringwald     return crc;
25285ddcd84SMatthias Ringwald }
25385ddcd84SMatthias Ringwald 
254474f5c3fSMatthias 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){
255474f5c3fSMatthias Ringwald     return (((uint16_t) sar) << 14) | (req_seq << 8) | (final << 7) | (tx_seq << 1) | 0;
256474f5c3fSMatthias Ringwald }
257474f5c3fSMatthias Ringwald 
258474f5c3fSMatthias 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){
259474f5c3fSMatthias Ringwald     return (req_seq << 8) | (final << 7) | (poll << 4) | (((int) supervisory_function) << 2) | 1;
260474f5c3fSMatthias Ringwald }
261474f5c3fSMatthias Ringwald 
262474f5c3fSMatthias Ringwald static int l2cap_next_ertm_seq_nr(int seq_nr){
263474f5c3fSMatthias Ringwald     return (seq_nr + 1) & 0x3f;
264474f5c3fSMatthias Ringwald }
265474f5c3fSMatthias Ringwald 
266474f5c3fSMatthias Ringwald static int l2cap_ertm_can_store_packet_now(l2cap_channel_t * channel){
267474f5c3fSMatthias Ringwald     // get num free tx buffers
268a8409e80SMatthias Ringwald     int num_free_tx_buffers = channel->num_tx_buffers - channel->num_stored_tx_frames;
269474f5c3fSMatthias Ringwald     // calculate num tx buffers for remote MTU
270474f5c3fSMatthias Ringwald     int num_tx_buffers_for_max_remote_mtu;
271b90eac91SMatthias Ringwald     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
272b90eac91SMatthias Ringwald     if (channel->remote_mtu <= effective_mps){
273474f5c3fSMatthias Ringwald         // MTU fits into single packet
274474f5c3fSMatthias Ringwald         num_tx_buffers_for_max_remote_mtu = 1;
275474f5c3fSMatthias Ringwald     } else {
276474f5c3fSMatthias Ringwald         // include SDU Length
277b90eac91SMatthias Ringwald         num_tx_buffers_for_max_remote_mtu = (channel->remote_mtu + 2 + (effective_mps - 1)) / effective_mps;
278474f5c3fSMatthias Ringwald     }
279a8409e80SMatthias Ringwald     log_debug("num_free_tx_buffers %u, num_tx_buffers_for_max_remote_mtu %u", num_free_tx_buffers, num_tx_buffers_for_max_remote_mtu);
280474f5c3fSMatthias Ringwald     return num_tx_buffers_for_max_remote_mtu <= num_free_tx_buffers;
281474f5c3fSMatthias Ringwald }
282474f5c3fSMatthias Ringwald 
283ef2faf56SMatthias Ringwald static void l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel_t * l2cap_channel){
284ef2faf56SMatthias Ringwald     log_info("Retransmit unacknowleged frames");
285ef2faf56SMatthias Ringwald     l2cap_channel->unacked_frames = 0;;
286ef2faf56SMatthias Ringwald     l2cap_channel->tx_send_index  = l2cap_channel->tx_read_index;
287ef2faf56SMatthias Ringwald }
288ef2faf56SMatthias Ringwald 
289474f5c3fSMatthias Ringwald static void l2cap_ertm_next_tx_write_index(l2cap_channel_t * channel){
290474f5c3fSMatthias Ringwald     channel->tx_write_index++;
291474f5c3fSMatthias Ringwald     if (channel->tx_write_index < channel->num_tx_buffers) return;
292474f5c3fSMatthias Ringwald     channel->tx_write_index = 0;
293474f5c3fSMatthias Ringwald }
294474f5c3fSMatthias Ringwald 
295474f5c3fSMatthias Ringwald static void l2cap_ertm_start_monitor_timer(l2cap_channel_t * channel){
296550189ffSMatthias Ringwald     log_info("Start Monitor timer");
297474f5c3fSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->monitor_timer);
298474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->monitor_timer, &l2cap_ertm_monitor_timeout_callback);
299474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer_context(&channel->monitor_timer, channel);
300474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer(&channel->monitor_timer, channel->local_monitor_timeout_ms);
301474f5c3fSMatthias Ringwald     btstack_run_loop_add_timer(&channel->monitor_timer);
302474f5c3fSMatthias Ringwald }
303474f5c3fSMatthias Ringwald 
304550189ffSMatthias Ringwald static void l2cap_ertm_stop_monitor_timer(l2cap_channel_t * channel){
305550189ffSMatthias Ringwald     log_info("Stop Monitor timer");
306550189ffSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->monitor_timer);
307550189ffSMatthias Ringwald }
308474f5c3fSMatthias Ringwald 
309474f5c3fSMatthias Ringwald static void l2cap_ertm_start_retransmission_timer(l2cap_channel_t * channel){
310550189ffSMatthias Ringwald     log_info("Start Retransmission timer");
311474f5c3fSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->retransmission_timer);
312474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->retransmission_timer, &l2cap_ertm_retransmission_timeout_callback);
313474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer_context(&channel->retransmission_timer, channel);
314474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer(&channel->retransmission_timer, channel->local_retransmission_timeout_ms);
315474f5c3fSMatthias Ringwald     btstack_run_loop_add_timer(&channel->retransmission_timer);
316474f5c3fSMatthias Ringwald }
317474f5c3fSMatthias Ringwald 
318474f5c3fSMatthias Ringwald static void l2cap_ertm_stop_retransmission_timer(l2cap_channel_t * l2cap_channel){
319550189ffSMatthias Ringwald     log_info("Stop Retransmission timer");
320474f5c3fSMatthias Ringwald     btstack_run_loop_remove_timer(&l2cap_channel->retransmission_timer);
321474f5c3fSMatthias Ringwald }
322474f5c3fSMatthias Ringwald 
323474f5c3fSMatthias Ringwald static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts){
324550189ffSMatthias Ringwald     log_info("Monitor timeout");
325474f5c3fSMatthias Ringwald     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
326474f5c3fSMatthias Ringwald 
327474f5c3fSMatthias Ringwald     // TODO: we assume that it's the oldest packet
328474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
329474f5c3fSMatthias Ringwald     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
330474f5c3fSMatthias Ringwald 
331474f5c3fSMatthias Ringwald     // check retry count
332474f5c3fSMatthias Ringwald     if (tx_state->retry_count < l2cap_channel->remote_max_transmit){
333474f5c3fSMatthias Ringwald         // increment retry count
334474f5c3fSMatthias Ringwald         tx_state->retry_count++;
335474f5c3fSMatthias Ringwald 
336ef2faf56SMatthias Ringwald         // start retransmit
337ef2faf56SMatthias Ringwald         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
338ef2faf56SMatthias Ringwald 
339ef2faf56SMatthias Ringwald         // start monitor timer
340474f5c3fSMatthias Ringwald         l2cap_ertm_start_monitor_timer(l2cap_channel);
341474f5c3fSMatthias Ringwald 
342474f5c3fSMatthias Ringwald         // send RR/P=1
343474f5c3fSMatthias Ringwald         l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
344474f5c3fSMatthias Ringwald     } else {
345474f5c3fSMatthias Ringwald         log_info("Monitor timer expired & retry count >= max transmit -> disconnect");
346474f5c3fSMatthias Ringwald         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
347474f5c3fSMatthias Ringwald     }
348474f5c3fSMatthias Ringwald     l2cap_run();
349474f5c3fSMatthias Ringwald }
350474f5c3fSMatthias Ringwald 
351474f5c3fSMatthias Ringwald static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts){
352550189ffSMatthias Ringwald     log_info("Retransmission timeout");
353474f5c3fSMatthias Ringwald     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
354474f5c3fSMatthias Ringwald 
355474f5c3fSMatthias Ringwald     // TODO: we assume that it's the oldest packet
356474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
357474f5c3fSMatthias Ringwald     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
358474f5c3fSMatthias Ringwald 
359474f5c3fSMatthias Ringwald     // set retry count = 1
360474f5c3fSMatthias Ringwald     tx_state->retry_count = 1;
361474f5c3fSMatthias Ringwald 
362ef2faf56SMatthias Ringwald     // start retransmit
363ef2faf56SMatthias Ringwald     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
364ef2faf56SMatthias Ringwald 
365474f5c3fSMatthias Ringwald     // start monitor timer
366474f5c3fSMatthias Ringwald     l2cap_ertm_start_monitor_timer(l2cap_channel);
367474f5c3fSMatthias Ringwald 
368474f5c3fSMatthias Ringwald     // send RR/P=1
369474f5c3fSMatthias Ringwald     l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
370474f5c3fSMatthias Ringwald     l2cap_run();
371474f5c3fSMatthias Ringwald }
372474f5c3fSMatthias Ringwald 
373474f5c3fSMatthias Ringwald static int l2cap_ertm_send_information_frame(l2cap_channel_t * channel, int index, int final){
374474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
375474f5c3fSMatthias Ringwald     hci_reserve_packet_buffer();
376474f5c3fSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
377474f5c3fSMatthias Ringwald     uint16_t control = l2cap_encanced_control_field_for_information_frame(tx_state->tx_seq, final, channel->req_seq, tx_state->sar);
378474f5c3fSMatthias Ringwald     log_info("I-Frame: control 0x%04x", control);
379474f5c3fSMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
3806535961aSMatthias Ringwald     (void)memcpy(&acl_buffer[8 + 2],
3816535961aSMatthias Ringwald                  &channel->tx_packets_data[index * channel->local_mps],
3826535961aSMatthias Ringwald                  tx_state->len);
3831e1a46bbSMatthias Ringwald     // (re-)start retransmission timer on
3841e1a46bbSMatthias Ringwald     l2cap_ertm_start_retransmission_timer(channel);
385474f5c3fSMatthias Ringwald     // send
386474f5c3fSMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2 + tx_state->len);
387474f5c3fSMatthias Ringwald }
388474f5c3fSMatthias Ringwald 
389474f5c3fSMatthias Ringwald static void l2cap_ertm_store_fragment(l2cap_channel_t * channel, l2cap_segmentation_and_reassembly_t sar, uint16_t sdu_length, uint8_t * data, uint16_t len){
390474f5c3fSMatthias Ringwald     // get next index for storing packets
391474f5c3fSMatthias Ringwald     int index = channel->tx_write_index;
392474f5c3fSMatthias Ringwald 
393474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
394474f5c3fSMatthias Ringwald     tx_state->tx_seq = channel->next_tx_seq;
395474f5c3fSMatthias Ringwald     tx_state->sar = sar;
396474f5c3fSMatthias Ringwald     tx_state->retry_count = 0;
397474f5c3fSMatthias Ringwald 
3983b81f0d3SMatthias Ringwald     uint8_t * tx_packet = &channel->tx_packets_data[index * channel->local_mps];
399b90eac91SMatthias Ringwald     log_debug("index %u, local mps %u, remote mps %u, packet tx %p, len %u", index, channel->local_mps, channel->remote_mps, tx_packet, len);
400474f5c3fSMatthias Ringwald     int pos = 0;
401474f5c3fSMatthias Ringwald     if (sar == L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU){
402474f5c3fSMatthias Ringwald         little_endian_store_16(tx_packet, 0, sdu_length);
403474f5c3fSMatthias Ringwald         pos += 2;
404474f5c3fSMatthias Ringwald     }
4056535961aSMatthias Ringwald     (void)memcpy(&tx_packet[pos], data, len);
406b90eac91SMatthias Ringwald     tx_state->len = pos + len;
407474f5c3fSMatthias Ringwald 
408474f5c3fSMatthias Ringwald     // update
409a8409e80SMatthias Ringwald     channel->num_stored_tx_frames++;
410474f5c3fSMatthias Ringwald     channel->next_tx_seq = l2cap_next_ertm_seq_nr(channel->next_tx_seq);
411474f5c3fSMatthias Ringwald     l2cap_ertm_next_tx_write_index(channel);
41294301352SMatthias Ringwald 
413a8409e80SMatthias Ringwald     log_info("l2cap_ertm_store_fragment: tx_read_index %u, tx_write_index %u, num stored %u", channel->tx_read_index, channel->tx_write_index, channel->num_stored_tx_frames);
41494301352SMatthias Ringwald 
415474f5c3fSMatthias Ringwald }
416474f5c3fSMatthias Ringwald 
417474f5c3fSMatthias Ringwald static int l2cap_ertm_send(l2cap_channel_t * channel, uint8_t * data, uint16_t len){
418474f5c3fSMatthias Ringwald     if (len > channel->remote_mtu){
419a8409e80SMatthias Ringwald         log_error("l2cap_ertm_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
420474f5c3fSMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
421474f5c3fSMatthias Ringwald     }
422474f5c3fSMatthias Ringwald 
423a8409e80SMatthias Ringwald     if (!l2cap_ertm_can_store_packet_now(channel)){
424a8409e80SMatthias Ringwald         log_error("l2cap_ertm_send cid 0x%02x, fragment store full", channel->local_cid);
425a8409e80SMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
426a8409e80SMatthias Ringwald     }
427a8409e80SMatthias Ringwald 
428474f5c3fSMatthias Ringwald     // check if it needs to get fragmented
429b90eac91SMatthias Ringwald     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
430b90eac91SMatthias Ringwald     if (len > effective_mps){
431474f5c3fSMatthias Ringwald         // fragmentation needed.
432474f5c3fSMatthias Ringwald         l2cap_segmentation_and_reassembly_t sar =  L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU;
433474f5c3fSMatthias Ringwald         int chunk_len;
434474f5c3fSMatthias Ringwald         while (len){
435474f5c3fSMatthias Ringwald             switch (sar){
436474f5c3fSMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
437b90eac91SMatthias Ringwald                     chunk_len = effective_mps - 2;    // sdu_length
438474f5c3fSMatthias Ringwald                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
439474f5c3fSMatthias Ringwald                     len -= chunk_len;
440474f5c3fSMatthias Ringwald                     sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU;
441474f5c3fSMatthias Ringwald                     break;
442474f5c3fSMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
443b90eac91SMatthias Ringwald                     chunk_len = effective_mps;
444474f5c3fSMatthias Ringwald                     if (chunk_len >= len){
445474f5c3fSMatthias Ringwald                         sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU;
446474f5c3fSMatthias Ringwald                         chunk_len = len;
447474f5c3fSMatthias Ringwald                     }
448474f5c3fSMatthias Ringwald                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
449474f5c3fSMatthias Ringwald                     len -= chunk_len;
450474f5c3fSMatthias Ringwald                     break;
451474f5c3fSMatthias Ringwald                 default:
452474f5c3fSMatthias Ringwald                     break;
453474f5c3fSMatthias Ringwald             }
454474f5c3fSMatthias Ringwald         }
455474f5c3fSMatthias Ringwald 
456474f5c3fSMatthias Ringwald     } else {
457474f5c3fSMatthias Ringwald         l2cap_ertm_store_fragment(channel, L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU, 0, data, len);
458474f5c3fSMatthias Ringwald     }
459474f5c3fSMatthias Ringwald 
460474f5c3fSMatthias Ringwald     // try to send
461d89ab698SMatthias Ringwald     l2cap_notify_channel_can_send();
462474f5c3fSMatthias Ringwald     return 0;
463474f5c3fSMatthias Ringwald }
464474f5c3fSMatthias Ringwald 
4657cbe539fSMatthias Ringwald static uint16_t l2cap_setup_options_ertm_request(l2cap_channel_t * channel, uint8_t * config_options){
466fcb125edSMatthias Ringwald     int pos = 0;
467fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
468fcb125edSMatthias Ringwald     config_options[pos++] = 9;      // length
469fcb125edSMatthias Ringwald     config_options[pos++] = (uint8_t) channel->mode;
470fcb125edSMatthias Ringwald     config_options[pos++] = channel->num_rx_buffers;    // == TxWindows size
471fcb125edSMatthias Ringwald     config_options[pos++] = channel->local_max_transmit;
472fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
473fcb125edSMatthias Ringwald     pos += 2;
474fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
475fcb125edSMatthias Ringwald     pos += 2;
476fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_mps);
477fcb125edSMatthias Ringwald     pos += 2;
4786574158aSMatthias Ringwald     //
479fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT;
480fcb125edSMatthias Ringwald     config_options[pos++] = 2;     // length
481fcb125edSMatthias Ringwald     little_endian_store_16(config_options, pos, channel->local_mtu);
482fcb125edSMatthias Ringwald     pos += 2;
483c425ea4aSMatthias Ringwald 
484c425ea4aSMatthias Ringwald     // Issue: iOS (e.g. 10.2) uses "No FCS" as default while Core 5.0 specifies "FCS" as default
485c425ea4aSMatthias Ringwald     // Workaround: try to actively negotiate FCS option
486fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
487fcb125edSMatthias Ringwald     config_options[pos++] = 1;     // length
488fcb125edSMatthias Ringwald     config_options[pos++] = channel->fcs_option;
489f2c70799Sandryblack     return pos; // 11+4+3=18
490474f5c3fSMatthias Ringwald }
491474f5c3fSMatthias Ringwald 
4927cbe539fSMatthias Ringwald static uint16_t l2cap_setup_options_ertm_response(l2cap_channel_t * channel, uint8_t * config_options){
493fcb125edSMatthias Ringwald     int pos = 0;
494fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
495fcb125edSMatthias Ringwald     config_options[pos++] = 9;      // length
496fcb125edSMatthias Ringwald     config_options[pos++] = (uint8_t) channel->mode;
4977cbe539fSMatthias Ringwald     // less or equal to remote tx window size
498fcb125edSMatthias Ringwald     config_options[pos++] = btstack_min(channel->num_tx_buffers, channel->remote_tx_window_size);
4997cbe539fSMatthias Ringwald     // max transmit in response shall be ignored -> use sender values
500fcb125edSMatthias Ringwald     config_options[pos++] = channel->remote_max_transmit;
5017cbe539fSMatthias Ringwald     // A value for the Retransmission time-out shall be sent in a positive Configuration Response
5027cbe539fSMatthias Ringwald     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
503fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
504fcb125edSMatthias Ringwald     pos += 2;
5057cbe539fSMatthias Ringwald     // A value for the Monitor time-out shall be sent in a positive Configuration Response
5067cbe539fSMatthias Ringwald     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
507fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
508fcb125edSMatthias Ringwald     pos += 2;
5097cbe539fSMatthias Ringwald     // less or equal to remote mps
510b90eac91SMatthias Ringwald     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
511b90eac91SMatthias Ringwald     little_endian_store_16( config_options, pos, effective_mps);
512fcb125edSMatthias Ringwald     pos += 2;
5136574158aSMatthias Ringwald     //
514fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
515fcb125edSMatthias Ringwald     config_options[pos++] = 2;     // length
516fcb125edSMatthias Ringwald     little_endian_store_16(config_options, pos, channel->remote_mtu);
517fcb125edSMatthias Ringwald     pos += 2;
518fcb125edSMatthias Ringwald #if 0
519d64e9771SMatthias Ringwald     //
520fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
521fcb125edSMatthias Ringwald     config_options[pos++] = 1;     // length
522fcb125edSMatthias Ringwald     config_options[pos++] = channel->fcs_option;
523fcb125edSMatthias Ringwald #endif
524f2c70799Sandryblack     return pos; // 11+4=15
5257cbe539fSMatthias Ringwald }
5267cbe539fSMatthias Ringwald 
527474f5c3fSMatthias Ringwald static int l2cap_ertm_send_supervisor_frame(l2cap_channel_t * channel, uint16_t control){
528474f5c3fSMatthias Ringwald     hci_reserve_packet_buffer();
529474f5c3fSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
530474f5c3fSMatthias Ringwald     log_info("S-Frame: control 0x%04x", control);
531474f5c3fSMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
532474f5c3fSMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2);
533474f5c3fSMatthias Ringwald }
534474f5c3fSMatthias Ringwald 
5355774a392SMatthias Ringwald static uint8_t l2cap_ertm_validate_local_config(l2cap_ertm_config_t * ertm_config){
536474f5c3fSMatthias Ringwald 
537474f5c3fSMatthias Ringwald     uint8_t result = ERROR_CODE_SUCCESS;
5389c0e62d3SMatthias Ringwald     if (ertm_config->max_transmit < 1){
539474f5c3fSMatthias Ringwald         log_error("max_transmit must be >= 1");
540474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
541474f5c3fSMatthias Ringwald     }
5429c0e62d3SMatthias Ringwald     if (ertm_config->retransmission_timeout_ms < 2000){
543474f5c3fSMatthias Ringwald         log_error("retransmission_timeout_ms must be >= 2000 ms");
544474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
545474f5c3fSMatthias Ringwald     }
5469c0e62d3SMatthias Ringwald     if (ertm_config->monitor_timeout_ms < 12000){
547474f5c3fSMatthias Ringwald         log_error("monitor_timeout_ms must be >= 12000 ms");
548474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
549474f5c3fSMatthias Ringwald     }
5509c0e62d3SMatthias Ringwald     if (ertm_config->local_mtu < 48){
551474f5c3fSMatthias Ringwald         log_error("local_mtu must be >= 48");
552474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
553474f5c3fSMatthias Ringwald     }
5549c0e62d3SMatthias Ringwald     if (ertm_config->num_rx_buffers < 1){
555474f5c3fSMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
556474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
557474f5c3fSMatthias Ringwald     }
5589c0e62d3SMatthias Ringwald     if (ertm_config->num_tx_buffers < 1){
559474f5c3fSMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
560474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
561474f5c3fSMatthias Ringwald     }
562474f5c3fSMatthias Ringwald     return result;
563474f5c3fSMatthias Ringwald }
564474f5c3fSMatthias Ringwald 
5659c0e62d3SMatthias Ringwald static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
566474f5c3fSMatthias Ringwald 
567474f5c3fSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
5689c0e62d3SMatthias Ringwald     channel->ertm_mandatory = ertm_config->ertm_mandatory;
5699c0e62d3SMatthias Ringwald     channel->local_max_transmit = ertm_config->max_transmit;
5709c0e62d3SMatthias Ringwald     channel->local_retransmission_timeout_ms = ertm_config->retransmission_timeout_ms;
5719c0e62d3SMatthias Ringwald     channel->local_monitor_timeout_ms = ertm_config->monitor_timeout_ms;
5729c0e62d3SMatthias Ringwald     channel->local_mtu = ertm_config->local_mtu;
5739c0e62d3SMatthias Ringwald     channel->num_rx_buffers = ertm_config->num_rx_buffers;
5749c0e62d3SMatthias Ringwald     channel->num_tx_buffers = ertm_config->num_tx_buffers;
575474f5c3fSMatthias Ringwald 
576c342091bSMatthias Ringwald     // align buffer to 16-byte boundary to assert l2cap_ertm_rx_packet_state_t is aligned
577474f5c3fSMatthias Ringwald     int bytes_till_alignment = 16 - (((uintptr_t) buffer) & 0x0f);
578474f5c3fSMatthias Ringwald     buffer += bytes_till_alignment;
579474f5c3fSMatthias Ringwald     size   -= bytes_till_alignment;
580474f5c3fSMatthias Ringwald 
581c342091bSMatthias Ringwald     // setup state buffers - use void cast to avoid -Wcast-align warning
582474f5c3fSMatthias Ringwald     uint32_t pos = 0;
583c342091bSMatthias Ringwald     channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) (void *) &buffer[pos];
5849c0e62d3SMatthias Ringwald     pos += ertm_config->num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
585c342091bSMatthias Ringwald     channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) (void *) &buffer[pos];
5869c0e62d3SMatthias Ringwald     pos += ertm_config->num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
587474f5c3fSMatthias Ringwald 
588474f5c3fSMatthias Ringwald     // setup reassembly buffer
589474f5c3fSMatthias Ringwald     channel->reassembly_buffer = &buffer[pos];
5909c0e62d3SMatthias Ringwald     pos += ertm_config->local_mtu;
591474f5c3fSMatthias Ringwald 
592474f5c3fSMatthias Ringwald     // divide rest of data equally
5939c0e62d3SMatthias Ringwald     channel->local_mps = (size - pos) / (ertm_config->num_rx_buffers + ertm_config->num_tx_buffers);
5940d3ee2efSMatthias Ringwald     log_info("Local MPS: %u", channel->local_mps);
595474f5c3fSMatthias Ringwald     channel->rx_packets_data = &buffer[pos];
5960d3ee2efSMatthias Ringwald     pos += ertm_config->num_rx_buffers * channel->local_mps;
597474f5c3fSMatthias Ringwald     channel->tx_packets_data = &buffer[pos];
5986574158aSMatthias Ringwald 
599c425ea4aSMatthias Ringwald     channel->fcs_option = ertm_config->fcs_option;
600474f5c3fSMatthias Ringwald }
601474f5c3fSMatthias Ringwald 
602474f5c3fSMatthias Ringwald uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
6039c0e62d3SMatthias Ringwald     l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
604474f5c3fSMatthias Ringwald 
6059c0e62d3SMatthias Ringwald     log_info("L2CAP_CREATE_ERTM_CHANNEL addr %s, psm 0x%x, local mtu %u", bd_addr_to_str(address), psm, ertm_config->local_mtu);
606474f5c3fSMatthias Ringwald 
607474f5c3fSMatthias Ringwald     // validate local config
6085774a392SMatthias Ringwald     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
609474f5c3fSMatthias Ringwald     if (result) return result;
610474f5c3fSMatthias Ringwald 
611f16129ceSMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, address, BD_ADDR_TYPE_ACL, psm, ertm_config->local_mtu, LEVEL_0);
612474f5c3fSMatthias Ringwald     if (!channel) {
613474f5c3fSMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
614474f5c3fSMatthias Ringwald     }
615474f5c3fSMatthias Ringwald 
616474f5c3fSMatthias Ringwald     // configure ERTM
6179c0e62d3SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
618474f5c3fSMatthias Ringwald 
619474f5c3fSMatthias Ringwald     // add to connections list
620474f5c3fSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
621474f5c3fSMatthias Ringwald 
622474f5c3fSMatthias Ringwald     // store local_cid
623474f5c3fSMatthias Ringwald     if (out_local_cid){
624474f5c3fSMatthias Ringwald        *out_local_cid = channel->local_cid;
625474f5c3fSMatthias Ringwald     }
626474f5c3fSMatthias Ringwald 
627474f5c3fSMatthias Ringwald     // check if hci connection is already usable
628f16129ceSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
629474f5c3fSMatthias Ringwald     if (conn){
630474f5c3fSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
631474f5c3fSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
632474f5c3fSMatthias Ringwald         // check if remote supported fearures are already received
633474f5c3fSMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
634474f5c3fSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
635474f5c3fSMatthias Ringwald         }
636474f5c3fSMatthias Ringwald     }
637474f5c3fSMatthias Ringwald 
638474f5c3fSMatthias Ringwald     l2cap_run();
639474f5c3fSMatthias Ringwald 
640474f5c3fSMatthias Ringwald     return 0;
641474f5c3fSMatthias Ringwald }
642474f5c3fSMatthias Ringwald 
643474f5c3fSMatthias Ringwald static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel){
644474f5c3fSMatthias Ringwald     if (l2cap_ertm_can_store_packet_now(channel)){
645474f5c3fSMatthias Ringwald         channel->waiting_for_can_send_now = 0;
646474f5c3fSMatthias Ringwald         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
647474f5c3fSMatthias Ringwald     }
648474f5c3fSMatthias Ringwald }
649474f5c3fSMatthias Ringwald 
6509c0e62d3SMatthias Ringwald uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
651474f5c3fSMatthias Ringwald 
652474f5c3fSMatthias Ringwald     log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
653f68b21d7SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
654474f5c3fSMatthias Ringwald     if (!channel) {
655474f5c3fSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
656474f5c3fSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
657474f5c3fSMatthias Ringwald     }
658474f5c3fSMatthias Ringwald 
659474f5c3fSMatthias Ringwald     // validate local config
6605774a392SMatthias Ringwald     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
661474f5c3fSMatthias Ringwald     if (result) return result;
662474f5c3fSMatthias Ringwald 
663474f5c3fSMatthias Ringwald     // configure L2CAP ERTM
6649c0e62d3SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
665474f5c3fSMatthias Ringwald 
666836ae835SMatthias Ringwald     // default: continue
667474f5c3fSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
668474f5c3fSMatthias Ringwald 
6698b7155e0SMatthias Ringwald     // verify remote ERTM support
670836ae835SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
671836ae835SMatthias Ringwald     if (connection == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
672836ae835SMatthias Ringwald 
673836ae835SMatthias Ringwald     if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
6748b7155e0SMatthias Ringwald         // ERTM not possible, select basic mode and release buffer
6758b7155e0SMatthias Ringwald         channel->mode = L2CAP_CHANNEL_MODE_BASIC;
6768b7155e0SMatthias Ringwald         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
677836ae835SMatthias Ringwald 
6788b7155e0SMatthias Ringwald         // bail if ERTM is mandatory
679836ae835SMatthias Ringwald         if (channel->ertm_mandatory){
680836ae835SMatthias Ringwald             // We chose 'no resources available' for "ERTM mandatory but you don't even know ERTM exists"
6818b7155e0SMatthias Ringwald             log_info("ERTM mandatory -> reject connection");
682836ae835SMatthias Ringwald             channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
683836ae835SMatthias Ringwald             channel->reason = 0x04; // no resources available
6848b7155e0SMatthias Ringwald         }  else {
6858b7155e0SMatthias Ringwald             log_info("ERTM not supported by remote -> use Basic mode");
686836ae835SMatthias Ringwald         }
687836ae835SMatthias Ringwald     }
688836ae835SMatthias Ringwald 
689474f5c3fSMatthias Ringwald     // process
690474f5c3fSMatthias Ringwald     l2cap_run();
691474f5c3fSMatthias Ringwald 
692474f5c3fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
693474f5c3fSMatthias Ringwald }
694474f5c3fSMatthias Ringwald 
695474f5c3fSMatthias Ringwald uint8_t l2cap_ertm_set_busy(uint16_t local_cid){
696f68b21d7SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
697474f5c3fSMatthias Ringwald     if (!channel) {
698474f5c3fSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
699474f5c3fSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
700474f5c3fSMatthias Ringwald     }
701474f5c3fSMatthias Ringwald     if (!channel->local_busy){
702474f5c3fSMatthias Ringwald         channel->local_busy = 1;
703474f5c3fSMatthias Ringwald         channel->send_supervisor_frame_receiver_not_ready = 1;
704474f5c3fSMatthias Ringwald         l2cap_run();
705474f5c3fSMatthias Ringwald     }
706474f5c3fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
707474f5c3fSMatthias Ringwald }
708474f5c3fSMatthias Ringwald 
709474f5c3fSMatthias Ringwald uint8_t l2cap_ertm_set_ready(uint16_t local_cid){
710f68b21d7SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
711474f5c3fSMatthias Ringwald     if (!channel) {
712474f5c3fSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
713474f5c3fSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
714474f5c3fSMatthias Ringwald     }
715474f5c3fSMatthias Ringwald     if (channel->local_busy){
716474f5c3fSMatthias Ringwald         channel->local_busy = 0;
717474f5c3fSMatthias Ringwald         channel->send_supervisor_frame_receiver_ready_poll = 1;
718474f5c3fSMatthias Ringwald         l2cap_run();
719474f5c3fSMatthias Ringwald     }
720474f5c3fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
721474f5c3fSMatthias Ringwald }
722474f5c3fSMatthias Ringwald 
7231e1a46bbSMatthias Ringwald // Process-ReqSeq
7241e1a46bbSMatthias Ringwald static void l2cap_ertm_process_req_seq(l2cap_channel_t * l2cap_channel, uint8_t req_seq){
725474f5c3fSMatthias Ringwald     int num_buffers_acked = 0;
726474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
72794301352SMatthias Ringwald     log_info("l2cap_ertm_process_req_seq: tx_read_index %u, tx_write_index %u, req_seq %u", l2cap_channel->tx_read_index, l2cap_channel->tx_write_index, req_seq);
728ff3cc4a5SMatthias Ringwald     while (true){
7291e1a46bbSMatthias Ringwald 
73094301352SMatthias Ringwald         // no unack packets left
73194301352SMatthias Ringwald         if (l2cap_channel->unacked_frames == 0) {
7321e1a46bbSMatthias Ringwald             // stop retransmission timer
7331e1a46bbSMatthias Ringwald             l2cap_ertm_stop_retransmission_timer(l2cap_channel);
7341e1a46bbSMatthias Ringwald             break;
7351e1a46bbSMatthias Ringwald         }
7361e1a46bbSMatthias Ringwald 
737474f5c3fSMatthias Ringwald         tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
738474f5c3fSMatthias Ringwald         // calc delta
739474f5c3fSMatthias Ringwald         int delta = (req_seq - tx_state->tx_seq) & 0x03f;
740474f5c3fSMatthias Ringwald         if (delta == 0) break;  // all packets acknowledged
741474f5c3fSMatthias Ringwald         if (delta > l2cap_channel->remote_tx_window_size) break;
742474f5c3fSMatthias Ringwald 
743474f5c3fSMatthias Ringwald         num_buffers_acked++;
744a8409e80SMatthias Ringwald         l2cap_channel->num_stored_tx_frames--;
74594301352SMatthias Ringwald         l2cap_channel->unacked_frames--;
746474f5c3fSMatthias Ringwald         log_info("RR seq %u => packet with tx_seq %u done", req_seq, tx_state->tx_seq);
747474f5c3fSMatthias Ringwald 
748474f5c3fSMatthias Ringwald         l2cap_channel->tx_read_index++;
749474f5c3fSMatthias Ringwald         if (l2cap_channel->tx_read_index >= l2cap_channel->num_rx_buffers){
750474f5c3fSMatthias Ringwald             l2cap_channel->tx_read_index = 0;
751474f5c3fSMatthias Ringwald         }
752474f5c3fSMatthias Ringwald     }
753474f5c3fSMatthias Ringwald     if (num_buffers_acked){
754a8409e80SMatthias Ringwald         log_info("num_buffers_acked %u", num_buffers_acked);
755474f5c3fSMatthias Ringwald     l2cap_ertm_notify_channel_can_send(l2cap_channel);
756474f5c3fSMatthias Ringwald }
757474f5c3fSMatthias Ringwald }
758474f5c3fSMatthias Ringwald 
759474f5c3fSMatthias Ringwald static l2cap_ertm_tx_packet_state_t * l2cap_ertm_get_tx_state(l2cap_channel_t * l2cap_channel, uint8_t tx_seq){
760474f5c3fSMatthias Ringwald     int i;
761474f5c3fSMatthias Ringwald     for (i=0;i<l2cap_channel->num_tx_buffers;i++){
762474f5c3fSMatthias Ringwald         l2cap_ertm_tx_packet_state_t * tx_state = &l2cap_channel->tx_packets_state[i];
763474f5c3fSMatthias Ringwald         if (tx_state->tx_seq == tx_seq) return tx_state;
764474f5c3fSMatthias Ringwald     }
765474f5c3fSMatthias Ringwald     return NULL;
766474f5c3fSMatthias Ringwald }
767474f5c3fSMatthias Ringwald 
768474f5c3fSMatthias Ringwald // @param delta number of frames in the future, >= 1
769122c2b05SMatthias Ringwald // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
7703d244bfaSMatthias Ringwald static void l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel_t * l2cap_channel, l2cap_segmentation_and_reassembly_t sar, int delta, const uint8_t * payload, uint16_t size){
771474f5c3fSMatthias Ringwald     log_info("Store SDU with delta %u", delta);
772474f5c3fSMatthias Ringwald     // get rx state for packet to store
773474f5c3fSMatthias Ringwald     int index = l2cap_channel->rx_store_index + delta - 1;
774474f5c3fSMatthias Ringwald     if (index > l2cap_channel->num_rx_buffers){
775474f5c3fSMatthias Ringwald         index -= l2cap_channel->num_rx_buffers;
776474f5c3fSMatthias Ringwald     }
777474f5c3fSMatthias Ringwald     log_info("Index of packet to store %u", index);
778474f5c3fSMatthias Ringwald     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
779474f5c3fSMatthias Ringwald     // check if buffer is free
780474f5c3fSMatthias Ringwald     if (rx_state->valid){
781474f5c3fSMatthias Ringwald         log_error("Packet buffer already used");
782474f5c3fSMatthias Ringwald         return;
783474f5c3fSMatthias Ringwald     }
784474f5c3fSMatthias Ringwald     rx_state->valid = 1;
785474f5c3fSMatthias Ringwald     rx_state->sar = sar;
786474f5c3fSMatthias Ringwald     rx_state->len = size;
787474f5c3fSMatthias Ringwald     uint8_t * rx_buffer = &l2cap_channel->rx_packets_data[index];
7886535961aSMatthias Ringwald     (void)memcpy(rx_buffer, payload, size);
789474f5c3fSMatthias Ringwald }
790474f5c3fSMatthias Ringwald 
791122c2b05SMatthias Ringwald // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
7923d244bfaSMatthias Ringwald static void l2cap_ertm_handle_in_sequence_sdu(l2cap_channel_t * l2cap_channel, l2cap_segmentation_and_reassembly_t sar, const uint8_t * payload, uint16_t size){
793122c2b05SMatthias Ringwald     uint16_t reassembly_sdu_length;
794474f5c3fSMatthias Ringwald     switch (sar){
795474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
796122c2b05SMatthias Ringwald             // assert total packet size <= our mtu
797122c2b05SMatthias Ringwald             if (size > l2cap_channel->local_mtu) break;
798474f5c3fSMatthias Ringwald             // packet complete -> disapatch
7993d244bfaSMatthias Ringwald             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, (uint8_t*) payload, size);
800474f5c3fSMatthias Ringwald             break;
801474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
802122c2b05SMatthias Ringwald             // read SDU len
803122c2b05SMatthias Ringwald             reassembly_sdu_length = little_endian_read_16(payload, 0);
804474f5c3fSMatthias Ringwald             payload += 2;
805474f5c3fSMatthias Ringwald             size    -= 2;
806122c2b05SMatthias Ringwald             // assert reassembled size <= our mtu
807122c2b05SMatthias Ringwald             if (reassembly_sdu_length > l2cap_channel->local_mtu) break;
808122c2b05SMatthias Ringwald             // store start segment
809122c2b05SMatthias Ringwald             l2cap_channel->reassembly_sdu_length = reassembly_sdu_length;
8106535961aSMatthias Ringwald             (void)memcpy(&l2cap_channel->reassembly_buffer[0], payload, size);
811474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos = size;
812474f5c3fSMatthias Ringwald             break;
813474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
814122c2b05SMatthias Ringwald             // assert size of reassembled data <= our mtu
815122c2b05SMatthias Ringwald             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
816122c2b05SMatthias Ringwald             // store continuation segment
8176535961aSMatthias Ringwald             (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
8186535961aSMatthias Ringwald                          payload, size);
819474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos += size;
820474f5c3fSMatthias Ringwald             break;
821474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
822122c2b05SMatthias Ringwald             // assert size of reassembled data <= our mtu
823122c2b05SMatthias Ringwald             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
824122c2b05SMatthias Ringwald             // store continuation segment
8256535961aSMatthias Ringwald             (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
8266535961aSMatthias Ringwald                          payload, size);
827474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos += size;
828122c2b05SMatthias Ringwald             // assert size of reassembled data matches announced sdu length
829122c2b05SMatthias Ringwald             if (l2cap_channel->reassembly_pos != l2cap_channel->reassembly_sdu_length) break;
830474f5c3fSMatthias Ringwald             // packet complete -> disapatch
831474f5c3fSMatthias Ringwald             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->reassembly_buffer, l2cap_channel->reassembly_pos);
832474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos = 0;
833474f5c3fSMatthias Ringwald             break;
834474f5c3fSMatthias Ringwald     }
835474f5c3fSMatthias Ringwald }
836474f5c3fSMatthias Ringwald 
837d89ab698SMatthias Ringwald static void l2cap_ertm_channel_send_information_frame(l2cap_channel_t * channel){
838d89ab698SMatthias Ringwald     channel->unacked_frames++;
839d89ab698SMatthias Ringwald     int index = channel->tx_send_index;
840d89ab698SMatthias Ringwald     channel->tx_send_index++;
841d89ab698SMatthias Ringwald     if (channel->tx_send_index >= channel->num_tx_buffers){
842d89ab698SMatthias Ringwald         channel->tx_send_index = 0;
843d89ab698SMatthias Ringwald     }
844d89ab698SMatthias Ringwald     l2cap_ertm_send_information_frame(channel, index, 0);   // final = 0
845d89ab698SMatthias Ringwald }
846d89ab698SMatthias Ringwald 
84785ddcd84SMatthias Ringwald #endif
84885ddcd84SMatthias Ringwald 
8496a5ffed8SMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
8506ddef68dSMilanka Ringwald static uint16_t l2cap_next_local_cid(void){
8516268fbfeSMilanka Ringwald     do {
8526268fbfeSMilanka Ringwald         if (local_source_cid == 0xffff) {
8536268fbfeSMilanka Ringwald             local_source_cid = 0x40;
8546268fbfeSMilanka Ringwald         } else {
8556268fbfeSMilanka Ringwald             local_source_cid++;
8566268fbfeSMilanka Ringwald         }
8576268fbfeSMilanka Ringwald     } while (l2cap_get_channel_for_local_cid(local_source_cid) != NULL);
8586268fbfeSMilanka Ringwald     return local_source_cid;
8596ddef68dSMilanka Ringwald }
8606a5ffed8SMatthias Ringwald #endif
8616ddef68dSMilanka Ringwald 
8626ddef68dSMilanka Ringwald static uint8_t l2cap_next_sig_id(void){
8636ddef68dSMilanka Ringwald     if (sig_seq_nr == 0xff) {
8646ddef68dSMilanka Ringwald         sig_seq_nr = 1;
8656ddef68dSMilanka Ringwald     } else {
8666ddef68dSMilanka Ringwald         sig_seq_nr++;
8676ddef68dSMilanka Ringwald     }
8686ddef68dSMilanka Ringwald     return sig_seq_nr;
8696ddef68dSMilanka Ringwald }
8706ddef68dSMilanka Ringwald 
87171de195eSMatthias Ringwald void l2cap_init(void){
8722b83fb7dSmatthias.ringwald     signaling_responses_pending = 0;
873808a48abSmatthias.ringwald 
874f5454fc6Smatthias.ringwald     l2cap_channels = NULL;
875fad84cafSMatthias Ringwald 
876fad84cafSMatthias Ringwald #ifdef ENABLE_CLASSIC
877f5454fc6Smatthias.ringwald     l2cap_services = NULL;
87809e9d05bSMatthias Ringwald     require_security_level2_for_outgoing_sdp = 0;
879fad84cafSMatthias Ringwald 
880fad84cafSMatthias Ringwald     // Setup Connectionless Channel
881fad84cafSMatthias Ringwald     l2cap_fixed_channel_connectionless.local_cid     = L2CAP_CID_CONNECTIONLESS_CHANNEL;
8827740e150SMatthias Ringwald     l2cap_fixed_channel_connectionless.channel_type  = L2CAP_CHANNEL_TYPE_CONNECTIONLESS;
883fad84cafSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_connectionless);
88409e9d05bSMatthias Ringwald #endif
885a3dc965aSMatthias Ringwald 
886a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
8877192e786SMatthias Ringwald     l2cap_le_services = NULL;
888a3dc965aSMatthias Ringwald #endif
889f5454fc6Smatthias.ringwald 
890d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
89133c40538SMatthias Ringwald     l2cap_event_packet_handler = NULL;
89225818320SMatthias Ringwald     l2cap_le_custom_max_mtu = 0;
893fad84cafSMatthias Ringwald 
894fad84cafSMatthias Ringwald     // Setup fixed ATT Channel
895fad84cafSMatthias Ringwald     l2cap_fixed_channel_att.local_cid    = L2CAP_CID_ATTRIBUTE_PROTOCOL;
8967740e150SMatthias Ringwald     l2cap_fixed_channel_att.channel_type = L2CAP_CHANNEL_TYPE_LE_FIXED;
897fad84cafSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_att);
898fad84cafSMatthias Ringwald 
899fad84cafSMatthias Ringwald     // Setup fixed SM Channel
900fad84cafSMatthias Ringwald     l2cap_fixed_channel_sm.local_cid     = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
9017740e150SMatthias Ringwald     l2cap_fixed_channel_sm.channel_type  = L2CAP_CHANNEL_TYPE_LE_FIXED;
902fad84cafSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_sm);
903d6ed9f9cSMatthias Ringwald #endif
904f5454fc6Smatthias.ringwald 
905fcadd0caSmatthias.ringwald     //
9062718e2e7Smatthias.ringwald     // register callback with HCI
907fcadd0caSmatthias.ringwald     //
908d9a7306aSMatthias Ringwald     hci_event_callback_registration.callback = &l2cap_hci_event_handler;
909fb37a842SMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
910fb37a842SMatthias Ringwald 
911d9a7306aSMatthias Ringwald     hci_register_acl_packet_handler(&l2cap_acl_handler);
912fb37a842SMatthias Ringwald 
913be005ed6SMatthias Ringwald #ifdef ENABLE_CLASSIC
91415a95bd5SMatthias Ringwald     gap_connectable_control(0); // no services yet
915be005ed6SMatthias Ringwald #endif
916fcadd0caSmatthias.ringwald }
917fcadd0caSmatthias.ringwald 
918ffbf8201SMatthias Ringwald void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
919d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
92033c40538SMatthias Ringwald     l2cap_event_packet_handler = handler;
921d6ed9f9cSMatthias Ringwald #else
9225774a392SMatthias Ringwald     UNUSED(handler);    // ok: no code
923d6ed9f9cSMatthias Ringwald #endif
9241e6aba47Smatthias.ringwald }
9251e6aba47Smatthias.ringwald 
92609e9d05bSMatthias Ringwald void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
927fad84cafSMatthias Ringwald     UNUSED(con_handle);  // ok: there is no con handle
9289ec2630cSMatthias Ringwald 
929f68b21d7SMatthias Ringwald     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
930fad84cafSMatthias Ringwald     if (!channel) return;
931fad84cafSMatthias Ringwald     channel->waiting_for_can_send_now = 1;
93209e9d05bSMatthias Ringwald     l2cap_notify_channel_can_send();
93309e9d05bSMatthias Ringwald }
93409e9d05bSMatthias Ringwald 
93509e9d05bSMatthias Ringwald int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
9365774a392SMatthias Ringwald     UNUSED(channel_id); // ok: only depends on Controller LE buffers
9379ec2630cSMatthias Ringwald 
93809e9d05bSMatthias Ringwald     return hci_can_send_acl_packet_now(con_handle);
93909e9d05bSMatthias Ringwald }
94009e9d05bSMatthias Ringwald 
94109e9d05bSMatthias Ringwald uint8_t *l2cap_get_outgoing_buffer(void){
94209e9d05bSMatthias Ringwald     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
94309e9d05bSMatthias Ringwald }
94409e9d05bSMatthias Ringwald 
9454e6fa3a2SMatthias Ringwald // only for L2CAP Basic Channels
94609e9d05bSMatthias Ringwald int l2cap_reserve_packet_buffer(void){
94709e9d05bSMatthias Ringwald     return hci_reserve_packet_buffer();
94809e9d05bSMatthias Ringwald }
94909e9d05bSMatthias Ringwald 
9504e6fa3a2SMatthias Ringwald // only for L2CAP Basic Channels
95109e9d05bSMatthias Ringwald void l2cap_release_packet_buffer(void){
95209e9d05bSMatthias Ringwald     hci_release_packet_buffer();
95309e9d05bSMatthias Ringwald }
95409e9d05bSMatthias Ringwald 
955f511cefaSMatthias 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){
95609e9d05bSMatthias Ringwald     // 0 - Connection handle : PB=pb : BC=00
957f511cefaSMatthias Ringwald     little_endian_store_16(acl_buffer, 0, con_handle | (packet_boundary << 12) | (0 << 14));
95809e9d05bSMatthias Ringwald     // 2 - ACL length
95909e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 2,  len + 4);
96009e9d05bSMatthias Ringwald     // 4 - L2CAP packet length
96109e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 4,  len + 0);
96209e9d05bSMatthias Ringwald     // 6 - L2CAP channel DEST
96309e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 6,  remote_cid);
96409e9d05bSMatthias Ringwald }
96509e9d05bSMatthias Ringwald 
966f511cefaSMatthias Ringwald // assumption - only on LE connections
96709e9d05bSMatthias Ringwald int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
96809e9d05bSMatthias Ringwald 
96909e9d05bSMatthias Ringwald     if (!hci_is_packet_buffer_reserved()){
97009e9d05bSMatthias Ringwald         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
97109e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
97209e9d05bSMatthias Ringwald     }
97309e9d05bSMatthias Ringwald 
97409e9d05bSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
97509e9d05bSMatthias Ringwald         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
97609e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
97709e9d05bSMatthias Ringwald     }
97809e9d05bSMatthias Ringwald 
97909e9d05bSMatthias Ringwald     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
98009e9d05bSMatthias Ringwald 
98109e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
982f511cefaSMatthias Ringwald     l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
98309e9d05bSMatthias Ringwald     // send
98409e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len+8);
98509e9d05bSMatthias Ringwald }
98609e9d05bSMatthias Ringwald 
987f511cefaSMatthias Ringwald // assumption - only on LE connections
98809e9d05bSMatthias Ringwald int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
98909e9d05bSMatthias Ringwald 
99009e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(con_handle)){
99109e9d05bSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", cid);
99209e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
99309e9d05bSMatthias Ringwald     }
99409e9d05bSMatthias Ringwald 
99509e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
99609e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
99709e9d05bSMatthias Ringwald 
9986535961aSMatthias Ringwald     (void)memcpy(&acl_buffer[8], data, len);
99909e9d05bSMatthias Ringwald 
100009e9d05bSMatthias Ringwald     return l2cap_send_prepared_connectionless(con_handle, cid, len);
100109e9d05bSMatthias Ringwald }
100209e9d05bSMatthias Ringwald 
100309e9d05bSMatthias Ringwald static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
1004d9d23054SMatthias Ringwald     log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
100509e9d05bSMatthias Ringwald     uint8_t event[4];
100609e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
100709e9d05bSMatthias Ringwald     event[1] = sizeof(event) - 2;
100809e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, channel);
100909e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
101009e9d05bSMatthias Ringwald     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
101109e9d05bSMatthias Ringwald }
101209e9d05bSMatthias Ringwald 
101309e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
101417a9b554SMatthias Ringwald static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
101558de5610Smatthias.ringwald     (* (channel->packet_handler))(type, channel->local_cid, data, size);
101658de5610Smatthias.ringwald }
101758de5610Smatthias.ringwald 
101844276248SMatthias Ringwald static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
101944276248SMatthias Ringwald     uint8_t event[4];
102044276248SMatthias Ringwald     event[0] = event_code;
102144276248SMatthias Ringwald     event[1] = sizeof(event) - 2;
102244276248SMatthias Ringwald     little_endian_store_16(event, 2, channel->local_cid);
102344276248SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
102444276248SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
102544276248SMatthias Ringwald }
102609e9d05bSMatthias Ringwald #endif
102744276248SMatthias Ringwald 
102809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
102958de5610Smatthias.ringwald void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
1030c9dc710bS[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",
1031fc64f94aSMatthias Ringwald              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
1032c9dc710bS[email protected]              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
10337f1690cfSMatthias Ringwald     uint8_t event[26];
103458de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
103558de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
103658de5610Smatthias.ringwald     event[2] = status;
1037724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
1038fc64f94aSMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
1039f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
1040f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
1041f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
1042f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 17, channel->local_mtu);
1043f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 19, channel->remote_mtu);
1044f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 21, channel->flush_timeout);
1045c1ab6cc1SMatthias Ringwald     event[23] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
10467f1690cfSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
10477f1690cfSMatthias Ringwald     log_info("ERTM mode %u, fcs enabled %u", channel->mode, channel->fcs_option);
10487f1690cfSMatthias Ringwald     event[24] = channel->mode;
10497f1690cfSMatthias Ringwald     event[25] = channel->fcs_option;
10507f1690cfSMatthias Ringwald 
10517f1690cfSMatthias Ringwald #else
10527f1690cfSMatthias Ringwald     event[24] = L2CAP_CHANNEL_MODE_BASIC;
10537f1690cfSMatthias Ringwald     event[25] = 0;
10547f1690cfSMatthias Ringwald #endif
105558de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
105617a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
105758de5610Smatthias.ringwald }
105858de5610Smatthias.ringwald 
105944276248SMatthias Ringwald static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
1060e0abb8e7S[email protected]     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
106144276248SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
106258de5610Smatthias.ringwald }
106358de5610Smatthias.ringwald 
106444276248SMatthias Ringwald static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
1065e0abb8e7S[email protected]     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
1066fc64f94aSMatthias Ringwald              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
106758de5610Smatthias.ringwald     uint8_t event[16];
106858de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
106958de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
1070724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[2]);
1071fc64f94aSMatthias Ringwald     little_endian_store_16(event,  8, channel->con_handle);
1072f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 10, channel->psm);
1073f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 12, channel->local_cid);
1074f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 14, channel->remote_cid);
107558de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
107617a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
10770af41d30Smatthias.ringwald }
1078f62db1e3Smatthias.ringwald 
107966a72640SMatthias Ringwald static void l2cap_handle_channel_open_failed(l2cap_channel_t * channel, uint8_t status){
108066a72640SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
108166a72640SMatthias Ringwald     // emit ertm buffer released, as it's not needed. if in basic mode, it was either not allocated or already released
108266a72640SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
108366a72640SMatthias Ringwald         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
108466a72640SMatthias Ringwald     }
108566a72640SMatthias Ringwald #endif
1086624873c3SMatthias Ringwald     l2cap_emit_channel_opened(channel, status);
1087624873c3SMatthias Ringwald }
1088624873c3SMatthias Ringwald 
108966a72640SMatthias Ringwald static void l2cap_handle_channel_closed(l2cap_channel_t * channel){
109066a72640SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
109166a72640SMatthias Ringwald     // emit ertm buffer released, as it's not needed anymore. if in basic mode, it was either not allocated or already released
109266a72640SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
109366a72640SMatthias Ringwald         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
109466a72640SMatthias Ringwald     }
109566a72640SMatthias Ringwald #endif
109666a72640SMatthias Ringwald     l2cap_emit_channel_closed(channel);
109766a72640SMatthias Ringwald }
1098dd3bf36fSMatthias Ringwald #endif
1099dd3bf36fSMatthias Ringwald 
1100dd3bf36fSMatthias Ringwald static l2cap_fixed_channel_t * l2cap_channel_item_by_cid(uint16_t cid){
1101dd3bf36fSMatthias Ringwald     btstack_linked_list_iterator_t it;
1102dd3bf36fSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1103dd3bf36fSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1104dd3bf36fSMatthias Ringwald         l2cap_fixed_channel_t * channel = (l2cap_fixed_channel_t*) btstack_linked_list_iterator_next(&it);
1105dd3bf36fSMatthias Ringwald         if (channel->local_cid == cid) {
1106dd3bf36fSMatthias Ringwald             return channel;
1107dd3bf36fSMatthias Ringwald         }
1108dd3bf36fSMatthias Ringwald     }
1109dd3bf36fSMatthias Ringwald     return NULL;
1110dd3bf36fSMatthias Ringwald }
111166a72640SMatthias Ringwald 
1112fad84cafSMatthias Ringwald // used for fixed channels in LE (ATT/SM) and Classic (Connectionless Channel). CID < 0x04
1113fad84cafSMatthias Ringwald static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid){
1114fad84cafSMatthias Ringwald     if (local_cid >= 0x40) return NULL;
1115fad84cafSMatthias Ringwald     return (l2cap_fixed_channel_t*) l2cap_channel_item_by_cid(local_cid);
1116fad84cafSMatthias Ringwald }
111724eb964eSMatthias Ringwald 
111824eb964eSMatthias Ringwald // used for Classic Channels + LE Data Channels. local_cid >= 0x40
111924eb964eSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
112024eb964eSMatthias Ringwald static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
112124eb964eSMatthias Ringwald     if (local_cid < 0x40) return NULL;
112224eb964eSMatthias Ringwald     return (l2cap_channel_t*) l2cap_channel_item_by_cid(local_cid);
112324eb964eSMatthias Ringwald }
11240b9d7e78SMatthias Ringwald 
112530725612SMatthias Ringwald void l2cap_request_can_send_now_event(uint16_t local_cid){
112630725612SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
112730725612SMatthias Ringwald     if (!channel) return;
112830725612SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
112996646001SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
113096646001SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
113196646001SMatthias Ringwald         l2cap_ertm_notify_channel_can_send(channel);
113296646001SMatthias Ringwald         return;
113396646001SMatthias Ringwald     }
113496646001SMatthias Ringwald #endif
113530725612SMatthias Ringwald     l2cap_notify_channel_can_send();
113630725612SMatthias Ringwald }
113730725612SMatthias Ringwald 
113896646001SMatthias Ringwald int  l2cap_can_send_packet_now(uint16_t local_cid){
113996646001SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
114096646001SMatthias Ringwald     if (!channel) return 0;
114196646001SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
114296646001SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
114396646001SMatthias Ringwald         return l2cap_ertm_can_store_packet_now(channel);
114496646001SMatthias Ringwald     }
114596646001SMatthias Ringwald #endif
11460b9d7e78SMatthias Ringwald     return hci_can_send_acl_packet_now(channel->con_handle);
11477856fb31S[email protected] }
11487856fb31S[email protected] 
114983e7cdd9SMatthias Ringwald int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
115083e7cdd9SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
115183e7cdd9SMatthias Ringwald     if (!channel) return 0;
11520b20b13bSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
11530b20b13bSMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
11540b20b13bSMatthias Ringwald         return 0;
11550b20b13bSMatthias Ringwald     }
11560b20b13bSMatthias Ringwald #endif
11570b9d7e78SMatthias Ringwald     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
115883e7cdd9SMatthias Ringwald }
11590b20b13bSMatthias Ringwald 
116096cbd662Smatthias.ringwald uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
116196cbd662Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
116296cbd662Smatthias.ringwald     if (channel) {
116396cbd662Smatthias.ringwald         return channel->remote_mtu;
116496cbd662Smatthias.ringwald     }
116596cbd662Smatthias.ringwald     return 0;
116696cbd662Smatthias.ringwald }
116724eb964eSMatthias Ringwald #endif
116896cbd662Smatthias.ringwald 
116924eb964eSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
1170fad84cafSMatthias Ringwald static int l2cap_is_dynamic_channel_type(l2cap_channel_type_t channel_type){
1171fad84cafSMatthias Ringwald     switch (channel_type){
1172fad84cafSMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CLASSIC:
1173fad84cafSMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
1174fad84cafSMatthias Ringwald             return 1;
1175fad84cafSMatthias Ringwald         default:
1176fad84cafSMatthias Ringwald             return 0;
1177fad84cafSMatthias Ringwald     }
1178fad84cafSMatthias Ringwald }
117924eb964eSMatthias Ringwald #endif
1180fad84cafSMatthias Ringwald 
118124eb964eSMatthias Ringwald #ifdef ENABLE_CLASSIC
1182fad84cafSMatthias Ringwald // RTX Timer only exist for dynamic channels
1183ec820d77SMatthias Ringwald static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
1184665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1185665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1186665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1187665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1188fad84cafSMatthias Ringwald         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
11895932bd7cS[email protected]         if (&channel->rtx == ts) {
11905932bd7cS[email protected]             return channel;
11915932bd7cS[email protected]         }
11925932bd7cS[email protected]     }
11935932bd7cS[email protected]     return NULL;
11945932bd7cS[email protected] }
11955932bd7cS[email protected] 
1196ec820d77SMatthias Ringwald static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
11975932bd7cS[email protected]     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
119895d2c8f4SMatthias Ringwald     if (!channel) return;
11995932bd7cS[email protected] 
12005932bd7cS[email protected]     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
12015932bd7cS[email protected] 
12025932bd7cS[email protected]     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
12035932bd7cS[email protected]     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
12045932bd7cS[email protected]     // notify client
120566a72640SMatthias Ringwald     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
12065932bd7cS[email protected] 
12075932bd7cS[email protected]     // discard channel
1208665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1209c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
12105932bd7cS[email protected] }
12115932bd7cS[email protected] 
121213aa3e4bSMatthias Ringwald #endif
121313aa3e4bSMatthias Ringwald 
121413aa3e4bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
12155932bd7cS[email protected] static void l2cap_stop_rtx(l2cap_channel_t * channel){
12165932bd7cS[email protected]     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
1217528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->rtx);
12185932bd7cS[email protected] }
121913aa3e4bSMatthias Ringwald #endif
122013aa3e4bSMatthias Ringwald 
122113aa3e4bSMatthias Ringwald #ifdef ENABLE_CLASSIC
12225932bd7cS[email protected] 
12235932bd7cS[email protected] static void l2cap_start_rtx(l2cap_channel_t * channel){
12245932bd7cS[email protected]     l2cap_stop_rtx(channel);
1225cb0ff06bS[email protected]     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
1226528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1227528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
1228528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
12295932bd7cS[email protected] }
12305932bd7cS[email protected] 
12315932bd7cS[email protected] static void l2cap_start_ertx(l2cap_channel_t * channel){
12325932bd7cS[email protected]     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
12335932bd7cS[email protected]     l2cap_stop_rtx(channel);
1234528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1235528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
1236528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
12375932bd7cS[email protected] }
12385932bd7cS[email protected] 
123971de195eSMatthias Ringwald void l2cap_require_security_level_2_for_outgoing_sdp(void){
1240ac301f95S[email protected]     require_security_level2_for_outgoing_sdp = 1;
1241ac301f95S[email protected] }
1242ac301f95S[email protected] 
1243df3354fcS[email protected] static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
124484e3541eSMilanka Ringwald     return (psm == BLUETOOTH_PSM_SDP) && (!require_security_level2_for_outgoing_sdp);
1245df3354fcS[email protected] }
12465932bd7cS[email protected] 
124763854e74SMatthias Ringwald static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1248a35252c8S[email protected]     if (!hci_can_send_acl_packet_now(handle)){
12499da54300S[email protected]         log_info("l2cap_send_signaling_packet, cannot send");
1250b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
1251b1d43497Smatthias.ringwald     }
1252b1d43497Smatthias.ringwald 
12539da54300S[email protected]     // log_info("l2cap_send_signaling_packet type %u", cmd);
12542a373862S[email protected]     hci_reserve_packet_buffer();
1255facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
125658de5610Smatthias.ringwald     va_list argptr;
125758de5610Smatthias.ringwald     va_start(argptr, identifier);
125870efece1S[email protected]     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
125958de5610Smatthias.ringwald     va_end(argptr);
12609da54300S[email protected]     // log_info("l2cap_send_signaling_packet con %u!", handle);
1261826f7347S[email protected]     return hci_send_acl_packet_buffer(len);
126258de5610Smatthias.ringwald }
126358de5610Smatthias.ringwald 
1264f511cefaSMatthias Ringwald // assumption - only on Classic connections
12654e6fa3a2SMatthias Ringwald // cannot be used for L2CAP ERTM
1266b1d43497Smatthias.ringwald int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
1267b1d43497Smatthias.ringwald 
1268c8b9416aS[email protected]     if (!hci_is_packet_buffer_reserved()){
1269c8b9416aS[email protected]         log_error("l2cap_send_prepared called without reserving packet first");
1270c8b9416aS[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
1271c8b9416aS[email protected]     }
1272c8b9416aS[email protected] 
127358de5610Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1274b1d43497Smatthias.ringwald     if (!channel) {
12759da54300S[email protected]         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
1276b1d43497Smatthias.ringwald         return -1;   // TODO: define error
12776218e6f1Smatthias.ringwald     }
12786218e6f1Smatthias.ringwald 
1279fc64f94aSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
12809da54300S[email protected]         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
1281a35252c8S[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
1282a35252c8S[email protected]     }
1283a35252c8S[email protected] 
1284fc64f94aSMatthias Ringwald     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
1285b1d43497Smatthias.ringwald 
128685ddcd84SMatthias Ringwald     int fcs_size = 0;
128785ddcd84SMatthias Ringwald 
128885ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
12896574158aSMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->fcs_option){
129085ddcd84SMatthias Ringwald         fcs_size = 2;
129185ddcd84SMatthias Ringwald     }
129285ddcd84SMatthias Ringwald #endif
129385ddcd84SMatthias Ringwald 
1294f511cefaSMatthias Ringwald     // set non-flushable packet boundary flag if supported on Controller
1295facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1296f511cefaSMatthias Ringwald     uint8_t packet_boundary_flag = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
129785ddcd84SMatthias Ringwald     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
129885ddcd84SMatthias Ringwald 
129985ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1300b72f6906SMatthias Ringwald     if (fcs_size){
130185ddcd84SMatthias Ringwald         // calculate FCS over l2cap data
130285ddcd84SMatthias Ringwald         uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
130385ddcd84SMatthias Ringwald         log_info("I-Frame: fcs 0x%04x", fcs);
130485ddcd84SMatthias Ringwald         little_endian_store_16(acl_buffer, 8 + len, fcs);
130558de5610Smatthias.ringwald     }
130685ddcd84SMatthias Ringwald #endif
130785ddcd84SMatthias Ringwald 
130885ddcd84SMatthias Ringwald     // send
130985ddcd84SMatthias Ringwald     return hci_send_acl_packet_buffer(len+8+fcs_size);
131085ddcd84SMatthias Ringwald }
131185ddcd84SMatthias Ringwald 
1312f511cefaSMatthias Ringwald // assumption - only on Classic connections
1313ce8f182eSMatthias Ringwald int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
1314a35252c8S[email protected]     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1315a35252c8S[email protected]     if (!channel) {
1316ce8f182eSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
1317a35252c8S[email protected]         return -1;   // TODO: define error
1318a35252c8S[email protected]     }
1319a35252c8S[email protected] 
1320f0fb4cd7SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1321f0fb4cd7SMatthias Ringwald     // send in ERTM
1322f0fb4cd7SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1323f0fb4cd7SMatthias Ringwald         return l2cap_ertm_send(channel, data, len);
1324f0fb4cd7SMatthias Ringwald     }
1325f0fb4cd7SMatthias Ringwald #endif
1326f0fb4cd7SMatthias Ringwald 
1327f0efaa57S[email protected]     if (len > channel->remote_mtu){
1328ce8f182eSMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
1329f0efaa57S[email protected]         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
1330f0efaa57S[email protected]     }
1331f0efaa57S[email protected] 
1332fc64f94aSMatthias Ringwald     if (!hci_can_send_acl_packet_now(channel->con_handle)){
1333ce8f182eSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
1334b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
1335b1d43497Smatthias.ringwald     }
1336b1d43497Smatthias.ringwald 
13372a373862S[email protected]     hci_reserve_packet_buffer();
1338facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
13396535961aSMatthias Ringwald     (void)memcpy(&acl_buffer[8], data, len);
1340f0fb4cd7SMatthias Ringwald     return l2cap_send_prepared(local_cid, len);
1341b1d43497Smatthias.ringwald }
1342b1d43497Smatthias.ringwald 
1343fc64f94aSMatthias Ringwald int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
1344fc64f94aSMatthias Ringwald     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
13450e37e417S[email protected] }
13460e37e417S[email protected] 
134728ca2b46S[email protected] static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
134828ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
134928ca2b46S[email protected] }
135028ca2b46S[email protected] 
135128ca2b46S[email protected] static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
135228ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
135328ca2b46S[email protected] }
135409e9d05bSMatthias Ringwald #endif
135528ca2b46S[email protected] 
135628ca2b46S[email protected] 
135709e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
135863854e74SMatthias Ringwald static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
135909e9d05bSMatthias Ringwald 
136009e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(handle)){
136109e9d05bSMatthias Ringwald         log_info("l2cap_send_le_signaling_packet, cannot send");
136209e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
136309e9d05bSMatthias Ringwald     }
136409e9d05bSMatthias Ringwald 
136509e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
136609e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
136709e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
136809e9d05bSMatthias Ringwald     va_list argptr;
136909e9d05bSMatthias Ringwald     va_start(argptr, identifier);
137009e9d05bSMatthias Ringwald     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
137109e9d05bSMatthias Ringwald     va_end(argptr);
137209e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
137309e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len);
137409e9d05bSMatthias Ringwald }
137509e9d05bSMatthias Ringwald #endif
137609e9d05bSMatthias Ringwald 
137709e9d05bSMatthias Ringwald uint16_t l2cap_max_mtu(void){
137809e9d05bSMatthias Ringwald     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
137909e9d05bSMatthias Ringwald }
138009e9d05bSMatthias Ringwald 
13813e329ddfSandryblack #ifdef ENABLE_BLE
138209e9d05bSMatthias Ringwald uint16_t l2cap_max_le_mtu(void){
138325818320SMatthias Ringwald     if (l2cap_le_custom_max_mtu != 0) return l2cap_le_custom_max_mtu;
138409e9d05bSMatthias Ringwald     return l2cap_max_mtu();
138509e9d05bSMatthias Ringwald }
1386b1d43497Smatthias.ringwald 
138725818320SMatthias Ringwald void l2cap_set_max_le_mtu(uint16_t max_mtu){
138825818320SMatthias Ringwald     if (max_mtu < l2cap_max_mtu()){
138925818320SMatthias Ringwald         l2cap_le_custom_max_mtu = max_mtu;
139025818320SMatthias Ringwald     }
139125818320SMatthias Ringwald }
13923e329ddfSandryblack #endif
139325818320SMatthias Ringwald 
1394d2afdd38SMatthias Ringwald #ifdef ENABLE_CLASSIC
1395d2afdd38SMatthias Ringwald 
13966b99230fSMatthias Ringwald static uint16_t l2cap_setup_options_mtu(uint8_t * config_options, uint16_t mtu){
1397d64e9771SMatthias Ringwald     config_options[0] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
1398d2afdd38SMatthias Ringwald     config_options[1] = 2; // len param
13996b99230fSMatthias Ringwald     little_endian_store_16(config_options, 2, mtu);
1400d2afdd38SMatthias Ringwald     return 4;
1401d2afdd38SMatthias Ringwald }
1402d2afdd38SMatthias Ringwald 
1403450ad7ecSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
14046b99230fSMatthias Ringwald static int l2cap_ertm_mode(l2cap_channel_t * channel){
1405450ad7ecSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
14066b99230fSMatthias Ringwald     return ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE)
14076b99230fSMatthias Ringwald         &&  (connection->l2cap_state.extended_feature_mask & 0x08));
1408450ad7ecSMatthias Ringwald }
1409450ad7ecSMatthias Ringwald #endif
14106b99230fSMatthias Ringwald 
14116b99230fSMatthias Ringwald static uint16_t l2cap_setup_options_request(l2cap_channel_t * channel, uint8_t * config_options){
14126b99230fSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1413313d3a26SMatthias Ringwald     // use ERTM options if supported by remote and channel ready to use it
1414313d3a26SMatthias Ringwald     if (l2cap_ertm_mode(channel) && channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
14157cbe539fSMatthias Ringwald         return l2cap_setup_options_ertm_request(channel, config_options);
14166b99230fSMatthias Ringwald     }
14176b99230fSMatthias Ringwald #endif
14186b99230fSMatthias Ringwald     uint16_t mtu = channel->local_mtu;
14196b99230fSMatthias Ringwald     return l2cap_setup_options_mtu(config_options, mtu);
14206b99230fSMatthias Ringwald }
14216b99230fSMatthias Ringwald 
1422b8134563SMatthias Ringwald static uint16_t l2cap_setup_options_mtu_response(l2cap_channel_t * channel, uint8_t * config_options){
142332717978SMatthias Ringwald     uint16_t mtu = btstack_min(channel->local_mtu, channel->remote_mtu);
14246b99230fSMatthias Ringwald     return l2cap_setup_options_mtu(config_options, mtu);
14256dca2a0cSMatthias Ringwald }
14266dca2a0cSMatthias Ringwald 
14271b9cb13dSMatthias Ringwald static uint32_t l2cap_extended_features_mask(void){
14281b9cb13dSMatthias Ringwald     // extended features request supported, features: fixed channels, unicast connectionless data reception
14291b9cb13dSMatthias Ringwald     uint32_t features = 0x280;
14301b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
143154901195SMatthias Ringwald     features |= 0x0028;
14321b9cb13dSMatthias Ringwald #endif
14331b9cb13dSMatthias Ringwald     return features;
14341b9cb13dSMatthias Ringwald }
1435d2afdd38SMatthias Ringwald #endif
14361b9cb13dSMatthias Ringwald 
14378158c421Smatthias.ringwald // MARK: L2CAP_RUN
14382cd0be45Smatthias.ringwald // process outstanding signaling tasks
14397f02f414SMatthias Ringwald static void l2cap_run(void){
14402b83fb7dSmatthias.ringwald 
144122c29ab4SMatthias Ringwald     // log_info("l2cap_run: entered");
144222c29ab4SMatthias Ringwald 
14432b83fb7dSmatthias.ringwald     // check pending signaling responses
14442b83fb7dSmatthias.ringwald     while (signaling_responses_pending){
14452b83fb7dSmatthias.ringwald 
14462b83fb7dSmatthias.ringwald         hci_con_handle_t handle = signaling_responses[0].handle;
1447a35252c8S[email protected] 
1448a35252c8S[email protected]         if (!hci_can_send_acl_packet_now(handle)) break;
1449a35252c8S[email protected] 
14502b83fb7dSmatthias.ringwald         uint8_t  sig_id        = signaling_responses[0].sig_id;
1451e74c5f58SMatthias Ringwald         uint8_t  response_code = signaling_responses[0].code;
145263a7246aSmatthias.ringwald         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
1453b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
14545774a392SMatthias Ringwald         uint16_t info_type     = signaling_responses[0].data;  // INFORMATION_REQUEST
1455b3264428SMatthias Ringwald         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
1456b3264428SMatthias Ringwald #endif
145709e9d05bSMatthias Ringwald 
1458f53da564S[email protected]         // remove first item before sending (to avoid sending response mutliple times)
1459f53da564S[email protected]         signaling_responses_pending--;
1460f53da564S[email protected]         int i;
1461f53da564S[email protected]         for (i=0; i < signaling_responses_pending; i++){
14626535961aSMatthias Ringwald             (void)memcpy(&signaling_responses[i],
14636535961aSMatthias Ringwald                          &signaling_responses[i + 1],
14646535961aSMatthias Ringwald                          sizeof(l2cap_signaling_response_t));
1465f53da564S[email protected]         }
1466f53da564S[email protected] 
1467f53da564S[email protected]         switch (response_code){
146809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
14692b360848Smatthias.ringwald             case CONNECTION_REQUEST:
1470e74c5f58SMatthias Ringwald                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
14712bd8b7e7S[email protected]                 // also disconnect if result is 0x0003 - security blocked
14724d816277S[email protected]                 if (result == 0x0003){
14732bd8b7e7S[email protected]                     hci_disconnect_security_block(handle);
14744d816277S[email protected]                 }
14752b360848Smatthias.ringwald                 break;
14762b83fb7dSmatthias.ringwald             case ECHO_REQUEST:
14772b83fb7dSmatthias.ringwald                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
14782b83fb7dSmatthias.ringwald                 break;
14792b83fb7dSmatthias.ringwald             case INFORMATION_REQUEST:
14803e64cb44SMatthias Ringwald                 switch (info_type){
14813e64cb44SMatthias Ringwald                     case L2CAP_INFO_TYPE_CONNECTIONLESS_MTU: {
14823b0484b3S[email protected]                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
14833e64cb44SMatthias Ringwald                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(connectionless_mtu), &connectionless_mtu);
14843b0484b3S[email protected]                         }
1485202c8a4cSMatthias Ringwald                         break;
14863e64cb44SMatthias Ringwald                     case L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED: {
14871b9cb13dSMatthias Ringwald                             uint32_t features = l2cap_extended_features_mask();
14883e64cb44SMatthias Ringwald                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(features), &features);
14893b0484b3S[email protected]                         }
1490202c8a4cSMatthias Ringwald                         break;
14913e64cb44SMatthias Ringwald                     case L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED: {
14923b0484b3S[email protected]                             uint8_t map[8];
14933b0484b3S[email protected]                             memset(map, 0, 8);
1494288636a2SMatthias Ringwald                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
14953e64cb44SMatthias Ringwald                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(map), &map);
14963b0484b3S[email protected]                         }
1497202c8a4cSMatthias Ringwald                         break;
14983b0484b3S[email protected]                     default:
14992b83fb7dSmatthias.ringwald                         // all other types are not supported
15003e64cb44SMatthias Ringwald                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 1, 0, NULL);
15013b0484b3S[email protected]                         break;
15022b83fb7dSmatthias.ringwald                 }
15032b83fb7dSmatthias.ringwald                 break;
150463a7246aSmatthias.ringwald             case COMMAND_REJECT:
15055ca8d57bS[email protected]                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
150663f0ac45SMatthias Ringwald                 break;
150709e9d05bSMatthias Ringwald #endif
1508a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
150963f0ac45SMatthias Ringwald             case LE_CREDIT_BASED_CONNECTION_REQUEST:
151063f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
151163f0ac45SMatthias Ringwald                 break;
151270efece1S[email protected]             case COMMAND_REJECT_LE:
151370efece1S[email protected]                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
151463a7246aSmatthias.ringwald                 break;
151570efece1S[email protected] #endif
15162b83fb7dSmatthias.ringwald             default:
15172b83fb7dSmatthias.ringwald                 // should not happen
15182b83fb7dSmatthias.ringwald                 break;
15192b83fb7dSmatthias.ringwald         }
15202b83fb7dSmatthias.ringwald     }
15212b83fb7dSmatthias.ringwald 
1522959f646aSMatthias Ringwald #if defined(ENABLE_CLASSIC) || defined(ENABLE_BLE)
1523665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
15245774a392SMatthias Ringwald #endif
152509e9d05bSMatthias Ringwald 
15261b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
15271b9cb13dSMatthias Ringwald     // send l2cap information request if neccessary
15281b9cb13dSMatthias Ringwald     hci_connections_get_iterator(&it);
15291b9cb13dSMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
15301b9cb13dSMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
15311b9cb13dSMatthias Ringwald         if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST){
153293d791b2SMatthias Ringwald             if (!hci_can_send_acl_packet_now(connection->con_handle)) break;
15331b9cb13dSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
15341b9cb13dSMatthias Ringwald             uint8_t sig_id = l2cap_next_sig_id();
15353e64cb44SMatthias Ringwald             uint8_t info_type = L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED;
15361b9cb13dSMatthias Ringwald             l2cap_send_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
15371b9cb13dSMatthias Ringwald             return;
15381b9cb13dSMatthias Ringwald         }
15391b9cb13dSMatthias Ringwald     }
15401b9cb13dSMatthias Ringwald #endif
15411b9cb13dSMatthias Ringwald 
154209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1543f2c70799Sandryblack #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1544f2c70799Sandryblack     uint8_t  config_options[18];
1545f2c70799Sandryblack #else
154643ec931dSMatthias Ringwald     uint8_t  config_options[10];
1547f2c70799Sandryblack #endif
1548665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1549665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1550baf94f06S[email protected] 
1551665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1552421cb104SMatthias Ringwald 
1553421cb104SMatthias Ringwald         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CLASSIC) continue;
1554421cb104SMatthias Ringwald 
155522c29ab4SMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
15562cd0be45Smatthias.ringwald         switch (channel->state){
15572cd0be45Smatthias.ringwald 
1558df3354fcS[email protected]             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1559ad671560S[email protected]             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
1560fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1561a00031e2S[email protected]                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
1562ad671560S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
1563fc64f94aSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
1564ad671560S[email protected]                 }
1565ad671560S[email protected]                 break;
1566ad671560S[email protected] 
156702b22dc4Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1568baf94f06S[email protected]                 if (!hci_can_send_command_packet_now()) break;
156964472d52Smatthias.ringwald                 // send connection request - set state first
157064472d52Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
157102b22dc4Smatthias.ringwald                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
15726535961aSMatthias Ringwald                 (void)memcpy(l2cap_outgoing_classic_addr, channel->address, 6);
15738f8108aaSmatthias.ringwald                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
157402b22dc4Smatthias.ringwald                 break;
157502b22dc4Smatthias.ringwald 
1576e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
1577fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
157822c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1579fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
1580e7ff783cSmatthias.ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1581*817374d9SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1582c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
158375e67d8aSMatthias Ringwald                 channel = NULL;
1584e7ff783cSmatthias.ringwald                 break;
1585e7ff783cSmatthias.ringwald 
1586552d92a1Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
1587fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1588fa8473a4Smatthias.ringwald                 channel->state = L2CAP_STATE_CONFIG;
158928ca2b46S[email protected]                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1590fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
1591552d92a1Smatthias.ringwald                 break;
1592552d92a1Smatthias.ringwald 
15936fdcc387Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
1594fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
15956fdcc387Smatthias.ringwald                 // success, start l2cap handshake
1596b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
15976fdcc387Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
1598fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
15995932bd7cS[email protected]                 l2cap_start_rtx(channel);
16006fdcc387Smatthias.ringwald                 break;
16016fdcc387Smatthias.ringwald 
1602fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
1603fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
160461c3f6deSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
160561c3f6deSMatthias Ringwald                     // fallback to basic mode if ERTM requested but not not supported by remote
160661c3f6deSMatthias Ringwald                      if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
160761c3f6deSMatthias Ringwald                         if (!l2cap_ertm_mode(channel)){
160861c3f6deSMatthias Ringwald                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
160961c3f6deSMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
161061c3f6deSMatthias Ringwald                         }
161161c3f6deSMatthias Ringwald                     }
161261c3f6deSMatthias Ringwald #endif
161373cf2b3dSmatthias.ringwald                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
161463a7246aSmatthias.ringwald                     uint16_t flags = 0;
161528ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
161663a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
161763a7246aSmatthias.ringwald                         flags = 1;
161863a7246aSmatthias.ringwald                     } else {
161928ca2b46S[email protected]                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
162063a7246aSmatthias.ringwald                     }
162163a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
1622ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1623fc64f94aSMatthias 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);
1624ac8f1300SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1625ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
1626ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1627ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1628b8134563SMatthias Ringwald                         uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1629ac8f1300SMatthias 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);
1630b8134563SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM){
1631b8134563SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
1632b8134563SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1633b8134563SMatthias Ringwald                         uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1634b8134563SMatthias 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);
1635ac8f1300SMatthias Ringwald #endif
1636ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
163763a7246aSmatthias.ringwald                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1638b8134563SMatthias Ringwald                         uint16_t options_size = l2cap_setup_options_mtu_response(channel, config_options);
1639ac8f1300SMatthias 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);
164063a7246aSmatthias.ringwald                     } else {
1641ac8f1300SMatthias Ringwald                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
164263a7246aSmatthias.ringwald                     }
164363a7246aSmatthias.ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1644fa8473a4Smatthias.ringwald                 }
164573cf2b3dSmatthias.ringwald                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
164628ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
164728ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
1648b1988dceSmatthias.ringwald                     channel->local_sig_id = l2cap_next_sig_id();
16496b99230fSMatthias Ringwald                     uint16_t options_size = l2cap_setup_options_request(channel, config_options);
16506dca2a0cSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options);
16515932bd7cS[email protected]                     l2cap_start_rtx(channel);
1652fa8473a4Smatthias.ringwald                 }
1653fa8473a4Smatthias.ringwald                 if (l2cap_channel_ready_for_open(channel)){
1654552d92a1Smatthias.ringwald                     channel->state = L2CAP_STATE_OPEN;
1655552d92a1Smatthias.ringwald                     l2cap_emit_channel_opened(channel, 0);  // success
1656fa8473a4Smatthias.ringwald                 }
1657552d92a1Smatthias.ringwald                 break;
1658552d92a1Smatthias.ringwald 
1659e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1660fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
166122c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1662fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
16635932bd7cS[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 :)
1664756102d3Smatthias.ringwald                 l2cap_finialize_channel_close(channel);  // -- remove from list
166564cb054cSMatthias Ringwald                 channel = NULL;
1666e7ff783cSmatthias.ringwald                 break;
1667e7ff783cSmatthias.ringwald 
1668e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1669fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1670b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
16712cd0be45Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1672fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
16732cd0be45Smatthias.ringwald                 break;
16742cd0be45Smatthias.ringwald             default:
16752cd0be45Smatthias.ringwald                 break;
16762cd0be45Smatthias.ringwald         }
167738f62777SMatthias Ringwald 
167838f62777SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
167964cb054cSMatthias Ringwald 
168075e67d8aSMatthias Ringwald         // handle channel finalize on L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE and L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE
168164cb054cSMatthias Ringwald         if (!channel) continue;
16829700d53bSMilanka Ringwald 
16839700d53bSMilanka Ringwald         // ERTM mode
16849700d53bSMilanka Ringwald         if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
16859700d53bSMilanka Ringwald 
16869700d53bSMilanka Ringwald             // check if we can still send
1687e0780573SMatthias Ringwald             if (channel->con_handle == HCI_CON_HANDLE_INVALID) continue;
168838f62777SMatthias Ringwald             if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
1689675e6881SMatthias Ringwald 
1690d84e866fSMatthias Ringwald             if (channel->send_supervisor_frame_receiver_ready){
169178cd8a22SMatthias Ringwald                 channel->send_supervisor_frame_receiver_ready = 0;
1692d2afdd38SMatthias Ringwald                 log_info("Send S-Frame: RR %u, final %u", channel->req_seq, channel->set_final_bit_after_packet_with_poll_bit_set);
1693d2afdd38SMatthias Ringwald                 uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 0,  channel->set_final_bit_after_packet_with_poll_bit_set, channel->req_seq);
1694d2afdd38SMatthias Ringwald                 channel->set_final_bit_after_packet_with_poll_bit_set = 0;
169538f62777SMatthias Ringwald                 l2cap_ertm_send_supervisor_frame(channel, control);
1696675e6881SMatthias Ringwald                 continue;
169738f62777SMatthias Ringwald             }
169862041d70SMatthias Ringwald             if (channel->send_supervisor_frame_receiver_ready_poll){
169978cd8a22SMatthias Ringwald                 channel->send_supervisor_frame_receiver_ready_poll = 0;
170062041d70SMatthias Ringwald                 log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
170162041d70SMatthias Ringwald                 uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
170262041d70SMatthias Ringwald                 l2cap_ertm_send_supervisor_frame(channel, control);
170362041d70SMatthias Ringwald                 continue;
170462041d70SMatthias Ringwald             }
17058f1c9639SMatthias Ringwald             if (channel->send_supervisor_frame_receiver_not_ready){
170678cd8a22SMatthias Ringwald                 channel->send_supervisor_frame_receiver_not_ready = 0;
17078f1c9639SMatthias Ringwald                 log_info("Send S-Frame: RNR %u", channel->req_seq);
17088f1c9639SMatthias Ringwald                 uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
17098f1c9639SMatthias Ringwald                 l2cap_ertm_send_supervisor_frame(channel, control);
17108f1c9639SMatthias Ringwald                 continue;
17118f1c9639SMatthias Ringwald             }
1712c7309e8dSMatthias Ringwald             if (channel->send_supervisor_frame_reject){
1713c7309e8dSMatthias Ringwald                 channel->send_supervisor_frame_reject = 0;
1714c7309e8dSMatthias Ringwald                 log_info("Send S-Frame: REJ %u", channel->req_seq);
1715c7309e8dSMatthias Ringwald                 uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 0, 0, channel->req_seq);
1716c7309e8dSMatthias Ringwald                 l2cap_ertm_send_supervisor_frame(channel, control);
1717c7309e8dSMatthias Ringwald                 continue;
1718c7309e8dSMatthias Ringwald             }
1719df2191a7SMatthias Ringwald             if (channel->send_supervisor_frame_selective_reject){
1720df2191a7SMatthias Ringwald                 channel->send_supervisor_frame_selective_reject = 0;
1721df2191a7SMatthias Ringwald                 log_info("Send S-Frame: SREJ %u", channel->expected_tx_seq);
1722f85ade6bSMatthias Ringwald                 uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT, 0, channel->set_final_bit_after_packet_with_poll_bit_set, channel->expected_tx_seq);
1723f85ade6bSMatthias Ringwald                 channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1724df2191a7SMatthias Ringwald                 l2cap_ertm_send_supervisor_frame(channel, control);
1725df2191a7SMatthias Ringwald                 continue;
1726df2191a7SMatthias Ringwald             }
17277b7901d8SMatthias Ringwald 
17287b7901d8SMatthias Ringwald             if (channel->srej_active){
17297b7901d8SMatthias Ringwald                 int i;
17307b7901d8SMatthias Ringwald                 for (i=0;i<channel->num_tx_buffers;i++){
17317b7901d8SMatthias Ringwald                     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
17327b7901d8SMatthias Ringwald                     if (tx_state->retransmission_requested) {
17337b7901d8SMatthias Ringwald                         tx_state->retransmission_requested = 0;
1734d2afdd38SMatthias Ringwald                         uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set;
1735d2afdd38SMatthias Ringwald                         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1736d2afdd38SMatthias Ringwald                         l2cap_ertm_send_information_frame(channel, i, final);
17377b7901d8SMatthias Ringwald                         break;
17387b7901d8SMatthias Ringwald                     }
17397b7901d8SMatthias Ringwald                 }
17407b7901d8SMatthias Ringwald                 if (i == channel->num_tx_buffers){
17417b7901d8SMatthias Ringwald                     // no retransmission request found
17427b7901d8SMatthias Ringwald                     channel->srej_active = 0;
17437b7901d8SMatthias Ringwald                 } else {
17447b7901d8SMatthias Ringwald                     // packet was sent
17457b7901d8SMatthias Ringwald                     continue;
17467b7901d8SMatthias Ringwald                 }
17477b7901d8SMatthias Ringwald             }
17489700d53bSMilanka Ringwald         }
174938f62777SMatthias Ringwald #endif
175038f62777SMatthias Ringwald 
17512cd0be45Smatthias.ringwald     }
175209e9d05bSMatthias Ringwald #endif
1753da886c03S[email protected] 
1754cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1755421cb104SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1756efedfb4cSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1757b5803aafSMatthias Ringwald         uint16_t mps;
1758efedfb4cSMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1759421cb104SMatthias Ringwald 
1760421cb104SMatthias Ringwald         if (channel->channel_type != L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL) continue;
1761421cb104SMatthias Ringwald 
1762efedfb4cSMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1763efedfb4cSMatthias Ringwald         switch (channel->state){
17645cb87675SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
17655cb87675SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
17665cb87675SMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
17675cb87675SMatthias Ringwald                 // le psm, source cid, mtu, mps, initial credits
17681b8b8d05SMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
176963f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
177063f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
1771b5803aafSMatthias Ringwald                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
1772b5803aafSMatthias 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, mps, channel->credits_incoming);
17735cb87675SMatthias Ringwald                 break;
177423017473SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
177523017473SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
177623017473SMatthias Ringwald                 // TODO: support larger MPS
177723017473SMatthias Ringwald                 channel->state = L2CAP_STATE_OPEN;
177863f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
177963f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
1780b5803aafSMatthias Ringwald                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
1781b5803aafSMatthias Ringwald                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->local_mtu, mps, channel->credits_incoming, 0);
178264e11ca9SMatthias Ringwald                 // notify client
178344276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0);
178423017473SMatthias Ringwald                 break;
1785e7d0c9aaSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
1786e7d0c9aaSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1787e7d0c9aaSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
178863f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
1789e7d0c9aaSMatthias Ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1790e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1791c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
1792e7d0c9aaSMatthias Ringwald                 break;
17937f107edaSMatthias Ringwald             case L2CAP_STATE_OPEN:
179485aeef60SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
179585aeef60SMatthias Ringwald 
179685aeef60SMatthias Ringwald                 // send credits
179785aeef60SMatthias Ringwald                 if (channel->new_credits_incoming){
179885aeef60SMatthias Ringwald                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
179985aeef60SMatthias Ringwald                     channel->local_sig_id = l2cap_next_sig_id();
180085aeef60SMatthias Ringwald                     uint16_t new_credits = channel->new_credits_incoming;
180185aeef60SMatthias Ringwald                     channel->new_credits_incoming = 0;
180285aeef60SMatthias Ringwald                     channel->credits_incoming += new_credits;
180385aeef60SMatthias Ringwald                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
18046774d5c9SMatthias Ringwald                 }
180585aeef60SMatthias Ringwald                 break;
180685aeef60SMatthias Ringwald 
1807828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1808828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1809828a7f7aSMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
1810828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1811828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1812828a7f7aSMatthias Ringwald                 break;
1813828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1814828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1815828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1816828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1817828a7f7aSMatthias Ringwald                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
1818828a7f7aSMatthias Ringwald                 break;
1819efedfb4cSMatthias Ringwald             default:
1820efedfb4cSMatthias Ringwald                 break;
1821efedfb4cSMatthias Ringwald         }
1822efedfb4cSMatthias Ringwald     }
182309e9d05bSMatthias Ringwald #endif
1824efedfb4cSMatthias Ringwald 
182509e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
1826da886c03S[email protected]     // send l2cap con paramter update if necessary
1827da886c03S[email protected]     hci_connections_get_iterator(&it);
1828665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
1829665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1830c1ab6cc1SMatthias Ringwald         if ((connection->address_type != BD_ADDR_TYPE_LE_PUBLIC) && (connection->address_type != BD_ADDR_TYPE_LE_RANDOM)) continue;
1831b68d7bc3SMatthias Ringwald         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
1832da886c03S[email protected]         switch (connection->le_con_parameter_update_state){
1833b68d7bc3SMatthias Ringwald             case CON_PARAMETER_UPDATE_SEND_REQUEST:
1834b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1835fe8aebe6SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, l2cap_next_sig_id(),
1836b68d7bc3SMatthias Ringwald                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
1837b68d7bc3SMatthias Ringwald                 break;
1838da886c03S[email protected]             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
1839b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
1840b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
1841da886c03S[email protected]                 break;
1842da886c03S[email protected]             case CON_PARAMETER_UPDATE_DENY:
1843b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1844b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
1845da886c03S[email protected]                 break;
1846da886c03S[email protected]             default:
1847da886c03S[email protected]                 break;
1848da886c03S[email protected]         }
1849da886c03S[email protected]     }
18504d7157c3S[email protected] #endif
1851da886c03S[email protected] 
185222c29ab4SMatthias Ringwald     // log_info("l2cap_run: exit");
18532cd0be45Smatthias.ringwald }
18542cd0be45Smatthias.ringwald 
185509e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1856fc64f94aSMatthias Ringwald static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
1857505f1c30SMatthias Ringwald     if ((channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE) || (channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION)) {
1858e5ac0afcSMatthias Ringwald         log_info("connection complete con_handle %04x - for channel %p cid 0x%04x", (int) con_handle, channel, channel->local_cid);
18592df5dadcS[email protected]         // success, start l2cap handshake
1860fc64f94aSMatthias Ringwald         channel->con_handle = con_handle;
18612df5dadcS[email protected]         // check remote SSP feature first
18622df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
18632df5dadcS[email protected]     }
18642df5dadcS[email protected] }
18652df5dadcS[email protected] 
18661b9cb13dSMatthias Ringwald static void l2cap_ready_to_connect(l2cap_channel_t * channel){
18671b9cb13dSMatthias Ringwald 
18681b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
186927e0774aSMatthias Ringwald     // assumption: outgoing connection
18701b9cb13dSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
18711b9cb13dSMatthias Ringwald     if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
18721b9cb13dSMatthias Ringwald         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
18731b9cb13dSMatthias Ringwald         channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
18741b9cb13dSMatthias Ringwald         return;
18751b9cb13dSMatthias Ringwald     }
18761b9cb13dSMatthias Ringwald #endif
18771b9cb13dSMatthias Ringwald 
18781b9cb13dSMatthias Ringwald     // fine, go ahead
18791b9cb13dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
18801b9cb13dSMatthias Ringwald }
18811b9cb13dSMatthias Ringwald 
18822df5dadcS[email protected] static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
18832df5dadcS[email protected]     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
18842df5dadcS[email protected] 
18852df5dadcS[email protected]     // we have been waiting for remote supported features, if both support SSP,
1886ac301f95S[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));
1887fc64f94aSMatthias Ringwald     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
18882df5dadcS[email protected]         // request security level 2
18892df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
1890dfce2622SMilanka Ringwald         channel->required_security_level = LEVEL_2;
1891fc64f94aSMatthias Ringwald         gap_request_security_level(channel->con_handle, LEVEL_2);
18922df5dadcS[email protected]         return;
18932df5dadcS[email protected]     }
18941b9cb13dSMatthias Ringwald 
18951b9cb13dSMatthias Ringwald     l2cap_ready_to_connect(channel);
18962df5dadcS[email protected] }
189709e9d05bSMatthias Ringwald #endif
18982df5dadcS[email protected] 
189909e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
19005d18f623SMatthias Ringwald static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, l2cap_channel_type_t channel_type, bd_addr_t address, bd_addr_type_t address_type,
1901da144af5SMatthias Ringwald     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
1902da144af5SMatthias Ringwald 
1903da144af5SMatthias Ringwald     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1904da144af5SMatthias Ringwald     if (!channel) {
1905da144af5SMatthias Ringwald         return NULL;
1906da144af5SMatthias Ringwald     }
1907da144af5SMatthias Ringwald 
1908da144af5SMatthias Ringwald     // fill in
1909da144af5SMatthias Ringwald     channel->packet_handler = packet_handler;
19105d18f623SMatthias Ringwald     channel->channel_type   = channel_type;
1911da144af5SMatthias Ringwald     bd_addr_copy(channel->address, address);
1912da144af5SMatthias Ringwald     channel->address_type = address_type;
1913da144af5SMatthias Ringwald     channel->psm = psm;
1914da144af5SMatthias Ringwald     channel->local_mtu  = local_mtu;
1915b37a9357SMatthias Ringwald     channel->remote_mtu = L2CAP_DEFAULT_MTU;
1916da144af5SMatthias Ringwald     channel->required_security_level = security_level;
1917da144af5SMatthias Ringwald 
1918da144af5SMatthias Ringwald     //
1919da144af5SMatthias Ringwald     channel->local_cid = l2cap_next_local_cid();
1920e0780573SMatthias Ringwald     channel->con_handle = HCI_CON_HANDLE_INVALID;
1921da144af5SMatthias Ringwald 
1922da144af5SMatthias Ringwald     // set initial state
1923da144af5SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
1924da144af5SMatthias Ringwald     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
1925da144af5SMatthias Ringwald     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
1926da144af5SMatthias Ringwald     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
192738f62777SMatthias Ringwald 
1928c45d6b2cSMatthias Ringwald     log_info("create channel %p, local_cid 0x%04x", channel, channel->local_cid);
1929e5ac0afcSMatthias Ringwald 
1930da144af5SMatthias Ringwald     return channel;
1931da144af5SMatthias Ringwald }
1932c45d6b2cSMatthias Ringwald 
1933c45d6b2cSMatthias Ringwald static void l2cap_free_channel_entry(l2cap_channel_t * channel){
1934c45d6b2cSMatthias Ringwald     log_info("free channel %p, local_cid 0x%04x", channel, channel->local_cid);
19358f4dd6c1SMatthias Ringwald     // assert all timers are stopped
1936b5bab9c8SMatthias Ringwald     l2cap_stop_rtx(channel);
19378f4dd6c1SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
19388f4dd6c1SMatthias Ringwald     l2cap_ertm_stop_retransmission_timer(channel);
19398f4dd6c1SMatthias Ringwald     l2cap_ertm_stop_monitor_timer(channel);
19408f4dd6c1SMatthias Ringwald #endif
1941b5bab9c8SMatthias Ringwald     // free  memory
1942c45d6b2cSMatthias Ringwald     btstack_memory_l2cap_channel_free(channel);
1943c45d6b2cSMatthias Ringwald }
194409e9d05bSMatthias Ringwald #endif
194509e9d05bSMatthias Ringwald 
194609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1947da144af5SMatthias Ringwald 
19489077cb15SMatthias Ringwald /**
19499077cb15SMatthias Ringwald  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
19509077cb15SMatthias Ringwald  * @param packet_handler
19519077cb15SMatthias Ringwald  * @param address
19529077cb15SMatthias Ringwald  * @param psm
19539077cb15SMatthias Ringwald  * @param mtu
19549077cb15SMatthias Ringwald  * @param local_cid
19559077cb15SMatthias Ringwald  */
19569077cb15SMatthias Ringwald 
19579d139fbaSMatthias 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){
19589d139fbaSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
19599d139fbaSMatthias Ringwald     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1960da144af5SMatthias Ringwald 
19619d139fbaSMatthias 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);
1962da144af5SMatthias Ringwald 
1963f16129ceSMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, address, BD_ADDR_TYPE_ACL, psm, local_mtu, LEVEL_0);
1964fc64f94aSMatthias Ringwald     if (!channel) {
19659077cb15SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
19669077cb15SMatthias Ringwald     }
19679077cb15SMatthias Ringwald 
19681b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
19691b9cb13dSMatthias Ringwald     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
19701b9cb13dSMatthias Ringwald #endif
19711b9cb13dSMatthias Ringwald 
19729077cb15SMatthias Ringwald     // add to connections list
1973fc64f94aSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
19749077cb15SMatthias Ringwald 
19759077cb15SMatthias Ringwald     // store local_cid
19769077cb15SMatthias Ringwald     if (out_local_cid){
1977fc64f94aSMatthias Ringwald        *out_local_cid = channel->local_cid;
19789077cb15SMatthias Ringwald     }
19799077cb15SMatthias Ringwald 
19809077cb15SMatthias Ringwald     // check if hci connection is already usable
1981f16129ceSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
198257a9eeaeSMatthias Ringwald     if (conn && conn->con_handle != HCI_CON_HANDLE_INVALID){
1983e5ac0afcSMatthias Ringwald         log_info("l2cap_create_channel, hci connection 0x%04x already exists", conn->con_handle);
1984fc64f94aSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
19859077cb15SMatthias Ringwald         // check if remote supported fearures are already received
19869077cb15SMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
1987fc64f94aSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
19889077cb15SMatthias Ringwald         }
19899077cb15SMatthias Ringwald     }
19909077cb15SMatthias Ringwald 
19919077cb15SMatthias Ringwald     l2cap_run();
19929077cb15SMatthias Ringwald 
1993c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
19949077cb15SMatthias Ringwald }
19959077cb15SMatthias Ringwald 
19961ea99aafSMilanka Ringwald void l2cap_disconnect(uint16_t local_cid, uint8_t reason){
1997e0abb8e7S[email protected]     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
1998b35f641cSmatthias.ringwald     // find channel for local_cid
1999b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2000f62db1e3Smatthias.ringwald     if (channel) {
2001e7ff783cSmatthias.ringwald         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2002f62db1e3Smatthias.ringwald     }
20032cd0be45Smatthias.ringwald     // process
20042cd0be45Smatthias.ringwald     l2cap_run();
200543625864Smatthias.ringwald }
20061e6aba47Smatthias.ringwald 
2007afde0c52Smatthias.ringwald static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
2008ceec418aSMatthias Ringwald     // mark all channels before emitting open events as these could trigger new connetion requests to the same device
2009665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
2010665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2011665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2012665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2013fad84cafSMatthias Ringwald         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2014058e3d6bSMatthias Ringwald         if (bd_addr_cmp( channel->address, address) != 0) continue;
2015c22aecc9S[email protected]         // channel for this address found
2016c22aecc9S[email protected]         switch (channel->state){
2017c22aecc9S[email protected]             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2018c22aecc9S[email protected]             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2019ceec418aSMatthias Ringwald                 channel->state = L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD;
2020c22aecc9S[email protected]                 break;
2021c22aecc9S[email protected]             default:
2022c22aecc9S[email protected]                 break;
2023afde0c52Smatthias.ringwald         }
2024afde0c52Smatthias.ringwald     }
2025ceec418aSMatthias Ringwald     // emit and free marked entries. restart loop to deal with list changes
2026ceec418aSMatthias Ringwald     int done = 0;
2027ceec418aSMatthias Ringwald     while (!done) {
2028ceec418aSMatthias Ringwald         done = 1;
2029ceec418aSMatthias Ringwald         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2030ceec418aSMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
2031ceec418aSMatthias Ringwald             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2032fad84cafSMatthias Ringwald             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2033ceec418aSMatthias Ringwald             if (channel->state == L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD){
2034ceec418aSMatthias Ringwald                 done = 0;
2035ceec418aSMatthias Ringwald                 // failure, forward error code
203666a72640SMatthias Ringwald                 l2cap_handle_channel_open_failed(channel, status);
2037ceec418aSMatthias Ringwald                 // discard channel
2038ceec418aSMatthias Ringwald                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2039c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
2040ceec418aSMatthias Ringwald                 break;
2041ceec418aSMatthias Ringwald             }
2042ceec418aSMatthias Ringwald         }
2043ceec418aSMatthias Ringwald     }
2044ceec418aSMatthias Ringwald 
2045afde0c52Smatthias.ringwald }
2046afde0c52Smatthias.ringwald 
2047afde0c52Smatthias.ringwald static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
2048665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
2049665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2050665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2051665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2052fad84cafSMatthias Ringwald         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2053058e3d6bSMatthias Ringwald         if ( ! bd_addr_cmp( channel->address, address) ){
20542df5dadcS[email protected]             l2cap_handle_connection_complete(handle, channel);
2055afde0c52Smatthias.ringwald         }
2056afde0c52Smatthias.ringwald     }
20576fdcc387Smatthias.ringwald     // process
20586fdcc387Smatthias.ringwald     l2cap_run();
2059afde0c52Smatthias.ringwald }
206009e9d05bSMatthias Ringwald #endif
2061b448a0e7Smatthias.ringwald 
20626774d5c9SMatthias Ringwald static bool l2cap_channel_ready_to_send(l2cap_channel_t * channel){
20636774d5c9SMatthias Ringwald     switch (channel->channel_type){
20646774d5c9SMatthias Ringwald #ifdef ENABLE_CLASSIC
20656774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CLASSIC:
20666774d5c9SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2067d89ab698SMatthias Ringwald             // send if we have more data and remote windows isn't full yet
2068d89ab698SMatthias Ringwald             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2069d89ab698SMatthias Ringwald                 if (channel->unacked_frames >= btstack_min(channel->num_stored_tx_frames, channel->remote_tx_window_size)) return false;
20706774d5c9SMatthias Ringwald                 return hci_can_send_acl_classic_packet_now() != 0;
2071d89ab698SMatthias Ringwald             }
2072d89ab698SMatthias Ringwald #endif
2073d89ab698SMatthias Ringwald             if (!channel->waiting_for_can_send_now) return false;
2074d89ab698SMatthias Ringwald             return (hci_can_send_acl_classic_packet_now() != 0);
20756774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
20766774d5c9SMatthias Ringwald             if (!channel->waiting_for_can_send_now) return false;
20776774d5c9SMatthias Ringwald             return hci_can_send_acl_classic_packet_now() != 0;
20786774d5c9SMatthias Ringwald #endif
20796774d5c9SMatthias Ringwald #ifdef ENABLE_BLE
20806774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_FIXED:
20816774d5c9SMatthias Ringwald             if (!channel->waiting_for_can_send_now) return false;
20826774d5c9SMatthias Ringwald             return hci_can_send_acl_le_packet_now() != 0;
20836774d5c9SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
20846774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
20856774d5c9SMatthias Ringwald             if (channel->send_sdu_buffer == NULL) return false;
20866774d5c9SMatthias Ringwald             if (channel->credits_outgoing == 0) return false;
20876774d5c9SMatthias Ringwald             return hci_can_send_acl_le_packet_now() != 0;
20886774d5c9SMatthias Ringwald #endif
20896774d5c9SMatthias Ringwald #endif
20906774d5c9SMatthias Ringwald         default:
20916774d5c9SMatthias Ringwald             return false;
20926774d5c9SMatthias Ringwald     }
20936774d5c9SMatthias Ringwald }
20946774d5c9SMatthias Ringwald 
20956774d5c9SMatthias Ringwald static void l2cap_channel_trigger_send(l2cap_channel_t * channel){
20966774d5c9SMatthias Ringwald     switch (channel->channel_type){
2097d89ab698SMatthias Ringwald #ifdef ENABLE_CLASSIC
2098d89ab698SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CLASSIC:
2099d89ab698SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2100d89ab698SMatthias Ringwald             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2101d89ab698SMatthias Ringwald                 l2cap_ertm_channel_send_information_frame(channel);
2102d89ab698SMatthias Ringwald                 return;
2103d89ab698SMatthias Ringwald             }
2104d89ab698SMatthias Ringwald #endif
2105d89ab698SMatthias Ringwald             channel->waiting_for_can_send_now = 0;
2106d89ab698SMatthias Ringwald             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2107d89ab698SMatthias Ringwald             break;
2108d89ab698SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2109d89ab698SMatthias Ringwald             channel->waiting_for_can_send_now = 0;
2110d89ab698SMatthias Ringwald             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2111d89ab698SMatthias Ringwald             break;
2112d89ab698SMatthias Ringwald #endif
21136774d5c9SMatthias Ringwald #ifdef ENABLE_BLE
2114d89ab698SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_FIXED:
2115d89ab698SMatthias Ringwald             channel->waiting_for_can_send_now = 0;
2116d89ab698SMatthias Ringwald             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2117d89ab698SMatthias Ringwald             break;
21186774d5c9SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
21196774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
21206774d5c9SMatthias Ringwald             l2cap_le_send_pdu(channel);
21216774d5c9SMatthias Ringwald             break;
21226774d5c9SMatthias Ringwald #endif
21236774d5c9SMatthias Ringwald #endif
21246774d5c9SMatthias Ringwald         default:
21256774d5c9SMatthias Ringwald             break;
21266774d5c9SMatthias Ringwald     }
21276774d5c9SMatthias Ringwald }
21286774d5c9SMatthias Ringwald 
212933c40538SMatthias Ringwald static void l2cap_notify_channel_can_send(void){
21306774d5c9SMatthias Ringwald     bool done = false;
21317740e150SMatthias Ringwald     while (!done){
21326774d5c9SMatthias Ringwald         done = true;
213333c40538SMatthias Ringwald         btstack_linked_list_iterator_t it;
213433c40538SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &l2cap_channels);
213533c40538SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
213633c40538SMatthias Ringwald             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
21376774d5c9SMatthias Ringwald             bool ready = l2cap_channel_ready_to_send(channel);
21386774d5c9SMatthias Ringwald             if (!ready) continue;
21396774d5c9SMatthias Ringwald 
21406774d5c9SMatthias Ringwald             // requeue channel for fairness
21417740e150SMatthias Ringwald             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
21427740e150SMatthias Ringwald             btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
21436774d5c9SMatthias Ringwald 
21446774d5c9SMatthias Ringwald             // trigger sending
21456774d5c9SMatthias Ringwald             l2cap_channel_trigger_send(channel);
21466774d5c9SMatthias Ringwald 
21477740e150SMatthias Ringwald             // exit inner loop as we just broke the iterator, but try again
21486774d5c9SMatthias Ringwald             done = false;
21497740e150SMatthias Ringwald             break;
21507740e150SMatthias Ringwald         }
215133c40538SMatthias Ringwald     }
215233c40538SMatthias Ringwald }
215333c40538SMatthias Ringwald 
21542053036dSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
21552053036dSMatthias Ringwald 
21562053036dSMatthias Ringwald static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){
21572053036dSMatthias Ringwald     // open cannot fail for for incoming connections
21582053036dSMatthias Ringwald     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0;
21592053036dSMatthias Ringwald 
21602053036dSMatthias Ringwald     // check state
21612053036dSMatthias Ringwald     switch (channel->state){
21622053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
21632053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
21642053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES:
21652053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
21662053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
21672053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES:
21682053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
21692053036dSMatthias Ringwald         case L2CAP_STATE_CONFIG:
21702053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
21712053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
21722053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE:
2173ceec418aSMatthias Ringwald         case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD:
21742053036dSMatthias Ringwald             return 1;
21752053036dSMatthias Ringwald 
21762053036dSMatthias Ringwald         case L2CAP_STATE_OPEN:
21772053036dSMatthias Ringwald         case L2CAP_STATE_CLOSED:
21782053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES:
21792053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
21802053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY:
21812053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
21822053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
21832053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
21842053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
21852053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
21862053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
21872053036dSMatthias Ringwald         case L2CAP_STATE_INVALID:
21882053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
21892053036dSMatthias Ringwald             return 0;
21906aa7d794SMatthias Ringwald         // no default here, to get a warning about new states
21912053036dSMatthias Ringwald     }
21926aa7d794SMatthias Ringwald     // still, the compiler insists on a return value
21936aa7d794SMatthias Ringwald     return 0;
21942053036dSMatthias Ringwald }
219513aa3e4bSMatthias Ringwald #endif
21962053036dSMatthias Ringwald 
219713aa3e4bSMatthias Ringwald #ifdef ENABLE_CLASSIC
21982053036dSMatthias Ringwald static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){
21992053036dSMatthias Ringwald     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
220066a72640SMatthias Ringwald         l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
22012053036dSMatthias Ringwald     } else {
220266a72640SMatthias Ringwald         l2cap_handle_channel_closed(channel);
22032053036dSMatthias Ringwald     }
2204c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
22052053036dSMatthias Ringwald }
22062053036dSMatthias Ringwald #endif
22072053036dSMatthias Ringwald 
22082cf36df7SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
22092cf36df7SMatthias Ringwald static void l2cap_handle_hci_le_disconnect_event(l2cap_channel_t * channel){
22102cf36df7SMatthias Ringwald     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
22112cf36df7SMatthias Ringwald         l2cap_emit_le_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
22122cf36df7SMatthias Ringwald     } else {
22132cf36df7SMatthias Ringwald         l2cap_emit_le_channel_closed(channel);
22142cf36df7SMatthias Ringwald     }
2215c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
22162cf36df7SMatthias Ringwald }
22172cf36df7SMatthias Ringwald #endif
22182053036dSMatthias Ringwald 
2219d9a7306aSMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
2220afde0c52Smatthias.ringwald 
22215774a392SMatthias Ringwald     UNUSED(packet_type); // ok: registered with hci_event_callback_registration
22225774a392SMatthias Ringwald     UNUSED(cid);         // ok: there is no channel
22235774a392SMatthias Ringwald     UNUSED(size);        // ok: fixed format events read from HCI buffer
22249ec2630cSMatthias Ringwald 
22255774a392SMatthias Ringwald #ifdef ENABLE_CLASSIC
2226afde0c52Smatthias.ringwald     bd_addr_t address;
22272d00edd4Smatthias.ringwald     int hci_con_used;
22285774a392SMatthias Ringwald #endif
22295774a392SMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
22305774a392SMatthias Ringwald     hci_con_handle_t handle;
223109e9d05bSMatthias Ringwald     btstack_linked_list_iterator_t it;
22325774a392SMatthias Ringwald #endif
2233afde0c52Smatthias.ringwald 
22340e2df43fSMatthias Ringwald     switch(hci_event_packet_get_type(packet)){
2235afde0c52Smatthias.ringwald 
223609e9d05bSMatthias Ringwald         // Notify channel packet handler if they can send now
223709e9d05bSMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
223809e9d05bSMatthias Ringwald         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
2239eea99214SMatthias Ringwald         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
224009e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
224109e9d05bSMatthias Ringwald             l2cap_notify_channel_can_send();
224209e9d05bSMatthias Ringwald             break;
224309e9d05bSMatthias Ringwald 
224409e9d05bSMatthias Ringwald         case HCI_EVENT_COMMAND_STATUS:
2245ece97caeSMatthias Ringwald #ifdef ENABLE_CLASSIC
2246ece97caeSMatthias Ringwald             // check command status for create connection for errors
2247ece97caeSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
2248ece97caeSMatthias Ringwald                 // cache outgoing address and reset
22496535961aSMatthias Ringwald                 (void)memcpy(address, l2cap_outgoing_classic_addr, 6);
2250ece97caeSMatthias Ringwald                 memset(l2cap_outgoing_classic_addr, 0, 6);
2251ece97caeSMatthias Ringwald                 // error => outgoing connection failed
2252ece97caeSMatthias Ringwald                 uint8_t status = hci_event_command_status_get_status(packet);
2253ece97caeSMatthias Ringwald                 if (status){
2254ece97caeSMatthias Ringwald                     l2cap_handle_connection_failed_for_addr(address, status);
2255ece97caeSMatthias Ringwald                 }
2256ece97caeSMatthias Ringwald             }
2257ece97caeSMatthias Ringwald #endif
225809e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
225909e9d05bSMatthias Ringwald             break;
226009e9d05bSMatthias Ringwald 
226109e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2262afde0c52Smatthias.ringwald         // handle connection complete events
2263afde0c52Smatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
2264724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], address);
2265afde0c52Smatthias.ringwald             if (packet[2] == 0){
2266f8fbdce0SMatthias Ringwald                 handle = little_endian_read_16(packet, 3);
2267afde0c52Smatthias.ringwald                 l2cap_handle_connection_success_for_addr(address, handle);
2268afde0c52Smatthias.ringwald             } else {
2269afde0c52Smatthias.ringwald                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
2270afde0c52Smatthias.ringwald             }
2271afde0c52Smatthias.ringwald             break;
2272afde0c52Smatthias.ringwald 
2273afde0c52Smatthias.ringwald         // handle successful create connection cancel command
2274afde0c52Smatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
2275073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
2276afde0c52Smatthias.ringwald                 if (packet[5] == 0){
2277724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[6], address);
2278afde0c52Smatthias.ringwald                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
2279afde0c52Smatthias.ringwald                     l2cap_handle_connection_failed_for_addr(address, 0x16);
228003cfbabcSmatthias.ringwald                 }
22811e6aba47Smatthias.ringwald             }
228239d59809Smatthias.ringwald             l2cap_run();    // try sending signaling packets first
228339d59809Smatthias.ringwald             break;
228409e9d05bSMatthias Ringwald #endif
228527a923d0Smatthias.ringwald 
22862053036dSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
22871e6aba47Smatthias.ringwald         // handle disconnection complete events
2288afde0c52Smatthias.ringwald         case HCI_EVENT_DISCONNECTION_COMPLETE:
2289d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
22902053036dSMatthias Ringwald             // send l2cap open failed or closed events for all channels on this handle and free them
2291665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2292665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2293665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2294fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2295fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
2296665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
2297421cb104SMatthias Ringwald                 switch(channel->channel_type){
2298421cb104SMatthias Ringwald #ifdef ENABLE_CLASSIC
2299421cb104SMatthias Ringwald                     case L2CAP_CHANNEL_TYPE_CLASSIC:
23002053036dSMatthias Ringwald                         l2cap_handle_hci_disconnect_event(channel);
2301421cb104SMatthias Ringwald                         break;
230209e9d05bSMatthias Ringwald #endif
2303a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2304421cb104SMatthias Ringwald                     case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
23052cf36df7SMatthias Ringwald                         l2cap_handle_hci_le_disconnect_event(channel);
2306afde0c52Smatthias.ringwald                         break;
23072053036dSMatthias Ringwald #endif
2308421cb104SMatthias Ringwald                     default:
2309421cb104SMatthias Ringwald                         break;
2310421cb104SMatthias Ringwald                 }
2311421cb104SMatthias Ringwald             }
23129909e5e4SMatthias Ringwald             break;
2313421cb104SMatthias Ringwald #endif
2314fcadd0caSmatthias.ringwald 
23159909e5e4SMatthias Ringwald 
2316ee091cf1Smatthias.ringwald         // HCI Connection Timeouts
231709e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2318afde0c52Smatthias.ringwald         case L2CAP_EVENT_TIMEOUT_CHECK:
2319f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
2320bd04d84aSMatthias Ringwald             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
232180ca58a0Smatthias.ringwald             if (hci_authentication_active_for_handle(handle)) break;
23222d00edd4Smatthias.ringwald             hci_con_used = 0;
2323665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2324665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2325665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2326fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2327fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
23282d00edd4Smatthias.ringwald                 hci_con_used = 1;
2329c22aecc9S[email protected]                 break;
2330ee091cf1Smatthias.ringwald             }
23312d00edd4Smatthias.ringwald             if (hci_con_used) break;
2332d94d3cafS[email protected]             if (!hci_can_send_command_packet_now()) break;
23339edc8742Smatthias.ringwald             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
2334afde0c52Smatthias.ringwald             break;
2335ee091cf1Smatthias.ringwald 
2336df3354fcS[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2337f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
2338665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2339665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2340665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2341fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2342fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
2343e5ac0afcSMatthias Ringwald                 log_info("remote supported features, channel %p, cid %04x - state %u", channel, channel->local_cid, channel->state);
23442df5dadcS[email protected]                 l2cap_handle_remote_supported_features_received(channel);
2345df3354fcS[email protected]             }
2346c22aecc9S[email protected]             break;
2347df3354fcS[email protected] 
23485611a760SMatthias Ringwald         case GAP_EVENT_SECURITY_LEVEL:
2349f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
2350e5ac0afcSMatthias Ringwald             log_info("l2cap - security level update for handle 0x%04x", handle);
2351665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2352665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2353665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2354fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2355fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
23565533f01eS[email protected] 
2357e569dfd9SMatthias Ringwald                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
23585533f01eS[email protected]                 gap_security_level_t required_level = channel->required_security_level;
23595533f01eS[email protected] 
2360e5ac0afcSMatthias Ringwald                 log_info("channel %p, cid %04x - state %u: actual %u >= required %u?", channel, channel->local_cid, channel->state, actual_level, required_level);
2361dfce2622SMilanka Ringwald 
2362df3354fcS[email protected]                 switch (channel->state){
2363df3354fcS[email protected]                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
23645533f01eS[email protected]                         if (actual_level >= required_level){
236552606043SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
236652606043SMatthias Ringwald                             // we need to know if ERTM is supported before sending a config response
236752606043SMatthias Ringwald                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
236852606043SMatthias Ringwald                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
236952606043SMatthias Ringwald                             channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
237052606043SMatthias Ringwald #else
2371f85a9399S[email protected]                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
237244276248SMatthias Ringwald                             l2cap_emit_incoming_connection(channel);
237352606043SMatthias Ringwald #endif
23741eb2563eS[email protected]                         } else {
2375775ecc36SMatthias Ringwald                             channel->reason = 0x0003; // security block
23761eb2563eS[email protected]                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
23771eb2563eS[email protected]                         }
2378df3354fcS[email protected]                         break;
2379df3354fcS[email protected] 
2380df3354fcS[email protected]                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
23815533f01eS[email protected]                         if (actual_level >= required_level){
23821b9cb13dSMatthias Ringwald                             l2cap_ready_to_connect(channel);
2383df3354fcS[email protected]                         } else {
2384df3354fcS[email protected]                             // disconnnect, authentication not good enough
2385df3354fcS[email protected]                             hci_disconnect_security_block(handle);
2386df3354fcS[email protected]                         }
2387df3354fcS[email protected]                         break;
2388df3354fcS[email protected] 
2389df3354fcS[email protected]                     default:
2390df3354fcS[email protected]                         break;
2391df3354fcS[email protected]                 }
2392f85a9399S[email protected]             }
2393f85a9399S[email protected]             break;
239409e9d05bSMatthias Ringwald #endif
2395f85a9399S[email protected] 
2396afde0c52Smatthias.ringwald         default:
2397afde0c52Smatthias.ringwald             break;
2398afde0c52Smatthias.ringwald     }
2399afde0c52Smatthias.ringwald 
2400bd63148eS[email protected]     l2cap_run();
24011e6aba47Smatthias.ringwald }
24021e6aba47Smatthias.ringwald 
2403e74c5f58SMatthias 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){
24044cf56b4aSmatthias.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."
24052b360848Smatthias.ringwald     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
24062b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].handle = handle;
24072b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].code = code;
24082b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].sig_id = sig_id;
2409e74c5f58SMatthias Ringwald         signaling_responses[signaling_responses_pending].cid = cid;
24102b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].data = data;
24112b360848Smatthias.ringwald         signaling_responses_pending++;
24122b360848Smatthias.ringwald         l2cap_run();
24132b360848Smatthias.ringwald     }
24142b360848Smatthias.ringwald }
24152b360848Smatthias.ringwald 
241609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
241709e9d05bSMatthias Ringwald static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
241809e9d05bSMatthias Ringwald     channel->remote_sig_id = identifier;
241909e9d05bSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
242009e9d05bSMatthias Ringwald     l2cap_run();
242109e9d05bSMatthias Ringwald }
242209e9d05bSMatthias Ringwald 
2423b35f641cSmatthias.ringwald static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
2424645658c9Smatthias.ringwald 
24259da54300S[email protected]     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
2426645658c9Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
2427645658c9Smatthias.ringwald     if (!service) {
2428645658c9Smatthias.ringwald         // 0x0002 PSM not supported
2429e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2430645658c9Smatthias.ringwald         return;
2431645658c9Smatthias.ringwald     }
2432645658c9Smatthias.ringwald 
24335061f3afS[email protected]     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
2434645658c9Smatthias.ringwald     if (!hci_connection) {
24352b360848Smatthias.ringwald         //
24369da54300S[email protected]         log_error("no hci_connection for handle %u", handle);
2437645658c9Smatthias.ringwald         return;
2438645658c9Smatthias.ringwald     }
24392bd8b7e7S[email protected] 
2440645658c9Smatthias.ringwald     // alloc structure
24419da54300S[email protected]     // log_info("l2cap_handle_connection_request register channel");
2442f16129ceSMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, hci_connection->address, BD_ADDR_TYPE_ACL,
2443da144af5SMatthias Ringwald     psm, service->mtu, service->required_security_level);
24442b360848Smatthias.ringwald     if (!channel){
24452b360848Smatthias.ringwald         // 0x0004 No resources available
2446e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
24472b360848Smatthias.ringwald         return;
24482b360848Smatthias.ringwald     }
2449da144af5SMatthias Ringwald 
2450fc64f94aSMatthias Ringwald     channel->con_handle = handle;
2451b35f641cSmatthias.ringwald     channel->remote_cid = source_cid;
2452b1988dceSmatthias.ringwald     channel->remote_sig_id = sig_id;
2453645658c9Smatthias.ringwald 
2454f53da564S[email protected]     // limit local mtu to max acl packet length - l2cap header
24552985cb84Smatthias.ringwald     if (channel->local_mtu > l2cap_max_mtu()) {
24562985cb84Smatthias.ringwald         channel->local_mtu = l2cap_max_mtu();
24579775e25bSmatthias.ringwald     }
24589775e25bSmatthias.ringwald 
2459645658c9Smatthias.ringwald     // set initial state
2460df3354fcS[email protected]     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
2461a24785d0SMatthias Ringwald     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
2462e405ae81Smatthias.ringwald 
2463645658c9Smatthias.ringwald     // add to connections list
2464665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
2465645658c9Smatthias.ringwald 
2466f85a9399S[email protected]     // assert security requirements
24671eb2563eS[email protected]     gap_request_security_level(handle, channel->required_security_level);
2468e405ae81Smatthias.ringwald }
2469645658c9Smatthias.ringwald 
2470ce8f182eSMatthias Ringwald void l2cap_accept_connection(uint16_t local_cid){
2471e0abb8e7S[email protected]     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
2472b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2473e405ae81Smatthias.ringwald     if (!channel) {
2474ce8f182eSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
2475e405ae81Smatthias.ringwald         return;
2476e405ae81Smatthias.ringwald     }
2477e405ae81Smatthias.ringwald 
247843ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
247943ec931dSMatthias Ringwald     // configure L2CAP Basic mode
248043ec931dSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
248143ec931dSMatthias Ringwald #endif
248243ec931dSMatthias Ringwald 
2483552d92a1Smatthias.ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
2484e405ae81Smatthias.ringwald 
2485552d92a1Smatthias.ringwald     // process
2486552d92a1Smatthias.ringwald     l2cap_run();
2487e405ae81Smatthias.ringwald }
2488645658c9Smatthias.ringwald 
24897ef6a7bbSMatthias Ringwald void l2cap_decline_connection(uint16_t local_cid){
24907ef6a7bbSMatthias Ringwald     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
2491b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
2492e405ae81Smatthias.ringwald     if (!channel) {
2493ce8f182eSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
2494e405ae81Smatthias.ringwald         return;
2495e405ae81Smatthias.ringwald     }
2496e7ff783cSmatthias.ringwald     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
24977ef6a7bbSMatthias Ringwald     channel->reason = 0x04; // no resources available
2498e7ff783cSmatthias.ringwald     l2cap_run();
2499645658c9Smatthias.ringwald }
2500645658c9Smatthias.ringwald 
2501e9cfb251SMatthias Ringwald // @pre command len is valid, see check in l2cap_signaling_handler_channel
25027f02f414SMatthias Ringwald static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
2503b1988dceSmatthias.ringwald 
2504fcb125edSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2505fcb125edSMatthias Ringwald     uint8_t use_fcs = 1;
2506fcb125edSMatthias Ringwald #endif
2507fcb125edSMatthias Ringwald 
2508b1988dceSmatthias.ringwald     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2509b1988dceSmatthias.ringwald 
2510f8fbdce0SMatthias Ringwald     uint16_t flags = little_endian_read_16(command, 6);
251163a7246aSmatthias.ringwald     if (flags & 1) {
251263a7246aSmatthias.ringwald         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
251363a7246aSmatthias.ringwald     }
251463a7246aSmatthias.ringwald 
25152784b77dSmatthias.ringwald     // accept the other's configuration options
2516f8fbdce0SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
25173de7c0caSmatthias.ringwald     uint16_t pos     = 8;
25183de7c0caSmatthias.ringwald     while (pos < end_pos){
251963a7246aSmatthias.ringwald         uint8_t option_hint = command[pos] >> 7;
252063a7246aSmatthias.ringwald         uint8_t option_type = command[pos] & 0x7f;
25213844aeadSMatthias Ringwald         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
252263a7246aSmatthias.ringwald         pos++;
25231dc511deSmatthias.ringwald         uint8_t length = command[pos++];
25241dc511deSmatthias.ringwald         // MTU { type(8): 1, len(8):2, MTU(16) }
2525c1ab6cc1SMatthias Ringwald         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) && (length == 2)){
2526f8fbdce0SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, pos);
25273844aeadSMatthias Ringwald             log_info("Remote MTU %u", channel->remote_mtu);
25289d139fbaSMatthias Ringwald             if (channel->remote_mtu > l2cap_max_mtu()){
25299d139fbaSMatthias Ringwald                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
25309d139fbaSMatthias Ringwald                 channel->remote_mtu = l2cap_max_mtu();
25319d139fbaSMatthias Ringwald             }
253263a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
253363a7246aSmatthias.ringwald         }
25340fe7a9d0S[email protected]         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
2535e53a3388SMatthias Ringwald         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT) && (length == 2)){
2536f8fbdce0SMatthias Ringwald             channel->flush_timeout = little_endian_read_16(command, pos);
25373844aeadSMatthias Ringwald             log_info("Flush timeout: %u ms", channel->flush_timeout);
25380fe7a9d0S[email protected]         }
2539f2fa388dSMatthias Ringwald 
25406dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
25416dca2a0cSMatthias Ringwald         // Retransmission and Flow Control Option
2542671fb338SMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
25433232a1c6SMatthias Ringwald             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
2544ac8f1300SMatthias Ringwald             switch(channel->mode){
2545ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
254625cd60d3SMatthias Ringwald                     // Store remote config
2547bbc0a9e7SMatthias Ringwald                     channel->remote_tx_window_size = command[pos+1];
2548bbc0a9e7SMatthias Ringwald                     channel->remote_max_transmit   = command[pos+2];
2549bbc0a9e7SMatthias Ringwald                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
2550bbc0a9e7SMatthias Ringwald                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
25513844aeadSMatthias Ringwald                     channel->remote_mps = little_endian_read_16(command, pos + 7);
25523844aeadSMatthias Ringwald                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
2553bbc0a9e7SMatthias Ringwald                         channel->remote_tx_window_size,
2554bbc0a9e7SMatthias Ringwald                         channel->remote_max_transmit,
2555bbc0a9e7SMatthias Ringwald                         channel->remote_retransmission_timeout_ms,
25563844aeadSMatthias Ringwald                         channel->remote_monitor_timeout_ms,
25573844aeadSMatthias Ringwald                         channel->remote_mps);
255825cd60d3SMatthias Ringwald                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
255925cd60d3SMatthias Ringwald                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
256025cd60d3SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2561ac8f1300SMatthias Ringwald                     } else {
2562b8134563SMatthias Ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2563ac8f1300SMatthias Ringwald                     }
2564ac8f1300SMatthias Ringwald                     break;
2565ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
2566ac8f1300SMatthias Ringwald                     switch (mode){
2567ac8f1300SMatthias Ringwald                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2568ac8f1300SMatthias Ringwald                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
2569ac8f1300SMatthias Ringwald                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
2570ac8f1300SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2571ac8f1300SMatthias Ringwald                             }
2572ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
2573ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
2574ac8f1300SMatthias Ringwald                             break;
2575ac8f1300SMatthias Ringwald                         default: // case L2CAP_CHANNEL_MODE_BASIC:
2576ac8f1300SMatthias Ringwald                             // TODO store and evaluate configuration
2577b8134563SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2578ac8f1300SMatthias Ringwald                             break;
2579ac8f1300SMatthias Ringwald                     }
2580ac8f1300SMatthias Ringwald                     break;
2581ac8f1300SMatthias Ringwald                 default:
2582ac8f1300SMatthias Ringwald                     break;
2583ac8f1300SMatthias Ringwald             }
25843232a1c6SMatthias Ringwald         }
25856574158aSMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
2586fcb125edSMatthias Ringwald             use_fcs = command[pos];
25876574158aSMatthias Ringwald         }
25886dca2a0cSMatthias Ringwald #endif
258963a7246aSmatthias.ringwald         // check for unknown options
2590505f1c30SMatthias Ringwald         if ((option_hint == 0) && ((option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) || (option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE))){
2591c177a91cS[email protected]             log_info("l2cap cid %u, unknown options", channel->local_cid);
259263a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
25931dc511deSmatthias.ringwald         }
25941dc511deSmatthias.ringwald         pos += length;
25951dc511deSmatthias.ringwald     }
2596fcb125edSMatthias Ringwald 
2597fcb125edSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2598fcb125edSMatthias Ringwald         // "FCS" has precedence over "No FCS"
2599fcb125edSMatthias Ringwald         uint8_t update = channel->fcs_option || use_fcs;
2600fcb125edSMatthias Ringwald         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
2601fcb125edSMatthias Ringwald         channel->fcs_option = update;
260267f8f607SMatthias Ringwald         // If ERTM mandatory, but remote didn't send Retransmission and Flowcontrol options -> disconnect
260367f8f607SMatthias Ringwald         if (((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM) == 0) & (channel->ertm_mandatory)){
260467f8f607SMatthias Ringwald             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
260567f8f607SMatthias Ringwald         }
2606fcb125edSMatthias Ringwald #endif
26072784b77dSmatthias.ringwald }
26082784b77dSmatthias.ringwald 
2609e9cfb251SMatthias Ringwald // @pre command len is valid, see check in l2cap_signaling_handler_channel
2610f2fa388dSMatthias Ringwald static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
2611f2fa388dSMatthias Ringwald     log_info("l2cap_signaling_handle_configure_response");
26123232a1c6SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
26133232a1c6SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2614f2fa388dSMatthias Ringwald     uint16_t pos     = 10;
26153232a1c6SMatthias Ringwald     while (pos < end_pos){
26163232a1c6SMatthias Ringwald         uint8_t option_hint = command[pos] >> 7;
26173232a1c6SMatthias Ringwald         uint8_t option_type = command[pos] & 0x7f;
2618fcb125edSMatthias Ringwald         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
26193232a1c6SMatthias Ringwald         pos++;
26203232a1c6SMatthias Ringwald         uint8_t length = command[pos++];
26213232a1c6SMatthias Ringwald 
26223232a1c6SMatthias Ringwald         // Retransmission and Flow Control Option
2623671fb338SMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2624ac8f1300SMatthias Ringwald             switch (channel->mode){
2625ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2626f2fa388dSMatthias Ringwald                     if (channel->ertm_mandatory){
2627ac8f1300SMatthias Ringwald                         // ??
2628f2fa388dSMatthias Ringwald                     } else {
2629ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
2630ac8f1300SMatthias Ringwald                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
263166a72640SMatthias Ringwald                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
2632f2fa388dSMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
26333232a1c6SMatthias Ringwald                         }
26343232a1c6SMatthias Ringwald                     }
2635ac8f1300SMatthias Ringwald                     break;
2636ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
2637ac8f1300SMatthias Ringwald                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2638ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
2639ac8f1300SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2640ac8f1300SMatthias Ringwald                     }
2641ac8f1300SMatthias Ringwald                     break;
2642ac8f1300SMatthias Ringwald                 default:
2643ac8f1300SMatthias Ringwald                     break;
26443232a1c6SMatthias Ringwald             }
2645f2fa388dSMatthias Ringwald         }
26463232a1c6SMatthias Ringwald 
26473232a1c6SMatthias Ringwald         // check for unknown options
2648671fb338SMatthias Ringwald         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
26493232a1c6SMatthias Ringwald             log_info("l2cap cid %u, unknown options", channel->local_cid);
26503232a1c6SMatthias Ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
26513232a1c6SMatthias Ringwald         }
26523232a1c6SMatthias Ringwald 
26533232a1c6SMatthias Ringwald         pos += length;
26543232a1c6SMatthias Ringwald     }
2655688f9764SMatthias Ringwald #else
26565774a392SMatthias Ringwald     UNUSED(channel);  // ok: no code
26575774a392SMatthias Ringwald     UNUSED(result);   // ok: no code
26585774a392SMatthias Ringwald     UNUSED(command);  // ok: no code
26593232a1c6SMatthias Ringwald #endif
26603232a1c6SMatthias Ringwald }
26613232a1c6SMatthias Ringwald 
2662fa8473a4Smatthias.ringwald static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
26639da54300S[email protected]     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
266473cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
266573cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
2666019f9b43SMatthias Ringwald     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
2667019f9b43SMatthias Ringwald     if (channel->state == L2CAP_STATE_OPEN) return 0;
2668fa8473a4Smatthias.ringwald     return 1;
2669fa8473a4Smatthias.ringwald }
2670fa8473a4Smatthias.ringwald 
2671fa8473a4Smatthias.ringwald 
2672e9cfb251SMatthias Ringwald // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
26737f02f414SMatthias Ringwald static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
26741e6aba47Smatthias.ringwald 
267500d93d79Smatthias.ringwald     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
267600d93d79Smatthias.ringwald     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2677e9cfb251SMatthias Ringwald     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
267838e5900eSmatthias.ringwald     uint16_t result = 0;
26791e6aba47Smatthias.ringwald 
26809da54300S[email protected]     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
2681b35f641cSmatthias.ringwald 
26829a011532Smatthias.ringwald     // handle DISCONNECT REQUESTS seperately
26839a011532Smatthias.ringwald     if (code == DISCONNECTION_REQUEST){
26849a011532Smatthias.ringwald         switch (channel->state){
2685fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
26869a011532Smatthias.ringwald             case L2CAP_STATE_OPEN:
26872b83fb7dSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
26889a011532Smatthias.ringwald             case L2CAP_STATE_WAIT_DISCONNECT:
26899a011532Smatthias.ringwald                 l2cap_handle_disconnect_request(channel, identifier);
26909a011532Smatthias.ringwald                 break;
26919a011532Smatthias.ringwald 
26929a011532Smatthias.ringwald             default:
26939a011532Smatthias.ringwald                 // ignore in other states
26949a011532Smatthias.ringwald                 break;
26959a011532Smatthias.ringwald         }
26969a011532Smatthias.ringwald         return;
26979a011532Smatthias.ringwald     }
26989a011532Smatthias.ringwald 
269956081214Smatthias.ringwald     // @STATEMACHINE(l2cap)
27001e6aba47Smatthias.ringwald     switch (channel->state) {
27011e6aba47Smatthias.ringwald 
27021e6aba47Smatthias.ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
27031e6aba47Smatthias.ringwald             switch (code){
27041e6aba47Smatthias.ringwald                 case CONNECTION_RESPONSE:
2705e9cfb251SMatthias Ringwald                     if (cmd_len < 8){
2706e9cfb251SMatthias Ringwald                         // command imcomplete
2707e9cfb251SMatthias Ringwald                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2708e9cfb251SMatthias Ringwald                         break;
2709e9cfb251SMatthias Ringwald                     }
27105932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2711f8fbdce0SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
271238e5900eSmatthias.ringwald                     switch (result) {
271338e5900eSmatthias.ringwald                         case 0:
2714169f8b28Smatthias.ringwald                             // successful connection
2715f8fbdce0SMatthias Ringwald                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2716fa8473a4Smatthias.ringwald                             channel->state = L2CAP_STATE_CONFIG;
271728ca2b46S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
271838e5900eSmatthias.ringwald                             break;
271938e5900eSmatthias.ringwald                         case 1:
27205932bd7cS[email protected]                             // connection pending. get some coffee, but start the ERTX
27215932bd7cS[email protected]                             l2cap_start_ertx(channel);
272238e5900eSmatthias.ringwald                             break;
272338e5900eSmatthias.ringwald                         default:
2724eb920dbeSmatthias.ringwald                             // channel closed
2725eb920dbeSmatthias.ringwald                             channel->state = L2CAP_STATE_CLOSED;
2726f32b992eSmatthias.ringwald                             // map l2cap connection response result to BTstack status enumeration
272766a72640SMatthias Ringwald                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
2728eb920dbeSmatthias.ringwald 
2729eb920dbeSmatthias.ringwald                             // drop link key if security block
2730c1ab6cc1SMatthias Ringwald                             if ((L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result) == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
273115a95bd5SMatthias Ringwald                                 gap_drop_link_key_for_bd_addr(channel->address);
2732eb920dbeSmatthias.ringwald                             }
2733eb920dbeSmatthias.ringwald 
2734eb920dbeSmatthias.ringwald                             // discard channel
2735665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2736c45d6b2cSMatthias Ringwald                             l2cap_free_channel_entry(channel);
273738e5900eSmatthias.ringwald                             break;
27381e6aba47Smatthias.ringwald                     }
27391e6aba47Smatthias.ringwald                     break;
274038e5900eSmatthias.ringwald 
274138e5900eSmatthias.ringwald                 default:
27421e6aba47Smatthias.ringwald                     //@TODO: implement other signaling packets
274338e5900eSmatthias.ringwald                     break;
27441e6aba47Smatthias.ringwald             }
27451e6aba47Smatthias.ringwald             break;
27461e6aba47Smatthias.ringwald 
2747fa8473a4Smatthias.ringwald         case L2CAP_STATE_CONFIG:
2748ae280e73Smatthias.ringwald             switch (code) {
2749ae280e73Smatthias.ringwald                 case CONFIGURE_REQUEST:
2750e9cfb251SMatthias Ringwald                     if (cmd_len < 4){
2751e9cfb251SMatthias Ringwald                         // command incomplete
2752e9cfb251SMatthias Ringwald                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2753e9cfb251SMatthias Ringwald                         break;
2754e9cfb251SMatthias Ringwald                     }
275528ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
2756ae280e73Smatthias.ringwald                     l2cap_signaling_handle_configure_request(channel, command);
275763a7246aSmatthias.ringwald                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
275863a7246aSmatthias.ringwald                         // only done if continuation not set
275963a7246aSmatthias.ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
276063a7246aSmatthias.ringwald                     }
2761ae280e73Smatthias.ringwald                     break;
27621e6aba47Smatthias.ringwald                 case CONFIGURE_RESPONSE:
2763e9cfb251SMatthias Ringwald                     if (cmd_len < 6){
2764e9cfb251SMatthias Ringwald                         // command incomplete
2765e9cfb251SMatthias Ringwald                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2766e9cfb251SMatthias Ringwald                         break;
2767e9cfb251SMatthias Ringwald                     }
2768e9cfb251SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
27695932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2770f2fa388dSMatthias Ringwald                     l2cap_signaling_handle_configure_response(channel, result, command);
27715932bd7cS[email protected]                     switch (result){
27725932bd7cS[email protected]                         case 0: // success
27735932bd7cS[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
27745932bd7cS[email protected]                             break;
27755932bd7cS[email protected]                         case 4: // pending
27765932bd7cS[email protected]                             l2cap_start_ertx(channel);
27775932bd7cS[email protected]                             break;
27785932bd7cS[email protected]                         default:
2779a32d6a03SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2780a32d6a03SMatthias Ringwald                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
2781a32d6a03SMatthias Ringwald                                 // remote does not offer ertm but it's required
2782a32d6a03SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2783a32d6a03SMatthias Ringwald                                 break;
2784a32d6a03SMatthias Ringwald                             }
2785a32d6a03SMatthias Ringwald #endif
2786fe9d8984S[email protected]                             // retry on negative result
2787fe9d8984S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2788fe9d8984S[email protected]                             break;
2789fe9d8984S[email protected]                     }
27905a67bd4aSmatthias.ringwald                     break;
27915a67bd4aSmatthias.ringwald                 default:
27925a67bd4aSmatthias.ringwald                     break;
27931e6aba47Smatthias.ringwald             }
2794fa8473a4Smatthias.ringwald             if (l2cap_channel_ready_for_open(channel)){
27952e4c1850SMatthias Ringwald 
27962e4c1850SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
27972e4c1850SMatthias Ringwald                 // assert that packet can be stored in fragment buffers in ertm
27982e4c1850SMatthias Ringwald                 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
27992e4c1850SMatthias Ringwald                     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
28002e4c1850SMatthias Ringwald                     uint16_t usable_mtu = channel->num_tx_buffers == 1 ? effective_mps : channel->num_tx_buffers * effective_mps - 2;
28012e4c1850SMatthias Ringwald                     if (usable_mtu < channel->remote_mtu){
28022e4c1850SMatthias Ringwald                         log_info("Remote MTU %u > max storable ERTM packet, only using MTU = %u", channel->remote_mtu, usable_mtu);
28032e4c1850SMatthias Ringwald                         channel->remote_mtu = usable_mtu;
28042e4c1850SMatthias Ringwald                     }
28052e4c1850SMatthias Ringwald                 }
28062e4c1850SMatthias Ringwald #endif
2807fa8473a4Smatthias.ringwald                 // for open:
28085a67bd4aSmatthias.ringwald                 channel->state = L2CAP_STATE_OPEN;
2809fa8473a4Smatthias.ringwald                 l2cap_emit_channel_opened(channel, 0);
2810c8e4258aSmatthias.ringwald             }
2811c8e4258aSmatthias.ringwald             break;
2812f62db1e3Smatthias.ringwald 
2813f62db1e3Smatthias.ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
2814f62db1e3Smatthias.ringwald             switch (code) {
2815f62db1e3Smatthias.ringwald                 case DISCONNECTION_RESPONSE:
281627a923d0Smatthias.ringwald                     l2cap_finialize_channel_close(channel);
281727a923d0Smatthias.ringwald                     break;
28185a67bd4aSmatthias.ringwald                 default:
28195a67bd4aSmatthias.ringwald                     //@TODO: implement other signaling packets
28205a67bd4aSmatthias.ringwald                     break;
282127a923d0Smatthias.ringwald             }
282227a923d0Smatthias.ringwald             break;
282384836b65Smatthias.ringwald 
282484836b65Smatthias.ringwald         case L2CAP_STATE_CLOSED:
282584836b65Smatthias.ringwald             // @TODO handle incoming requests
282684836b65Smatthias.ringwald             break;
282784836b65Smatthias.ringwald 
282884836b65Smatthias.ringwald         case L2CAP_STATE_OPEN:
282984836b65Smatthias.ringwald             //@TODO: implement other signaling packets, e.g. re-configure
283084836b65Smatthias.ringwald             break;
283110642e45Smatthias.ringwald         default:
283210642e45Smatthias.ringwald             break;
283327a923d0Smatthias.ringwald     }
28349da54300S[email protected]     // log_info("new state %u", channel->state);
283527a923d0Smatthias.ringwald }
283627a923d0Smatthias.ringwald 
283700d93d79Smatthias.ringwald 
2838ed2ed8e1SMatthias Ringwald // @pre command len is valid, see check in l2cap_acl_classic_handler
28397f02f414SMatthias Ringwald static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
284000d93d79Smatthias.ringwald 
28411b9cb13dSMatthias Ringwald     btstack_linked_list_iterator_t it;
28421b9cb13dSMatthias Ringwald 
284300d93d79Smatthias.ringwald     // get code, signalind identifier and command len
284400d93d79Smatthias.ringwald     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
284500d93d79Smatthias.ringwald     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
28460493bf3aSMatthias Ringwald     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
284700d93d79Smatthias.ringwald 
28481b9cb13dSMatthias Ringwald     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
2849505f1c30SMatthias Ringwald     if ((code < 1) || (code == ECHO_RESPONSE) || (code > INFORMATION_RESPONSE)){
2850e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
285100d93d79Smatthias.ringwald         return;
285200d93d79Smatthias.ringwald     }
285300d93d79Smatthias.ringwald 
285400d93d79Smatthias.ringwald     // general commands without an assigned channel
285500d93d79Smatthias.ringwald     switch(code) {
285600d93d79Smatthias.ringwald 
28570493bf3aSMatthias Ringwald         case CONNECTION_REQUEST:
28580493bf3aSMatthias Ringwald             if (cmd_len == 4){
2859f8fbdce0SMatthias Ringwald                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2860f8fbdce0SMatthias Ringwald                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
286100d93d79Smatthias.ringwald                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
28620493bf3aSMatthias Ringwald             } else {
28630493bf3aSMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
286400d93d79Smatthias.ringwald             }
28650493bf3aSMatthias Ringwald             return;
286600d93d79Smatthias.ringwald 
28672b360848Smatthias.ringwald         case ECHO_REQUEST:
2868e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
28692b83fb7dSmatthias.ringwald             return;
287000d93d79Smatthias.ringwald 
28710493bf3aSMatthias Ringwald         case INFORMATION_REQUEST:
28720493bf3aSMatthias Ringwald             if (cmd_len == 2) {
28733e64cb44SMatthias Ringwald                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
28743e64cb44SMatthias Ringwald                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
28750493bf3aSMatthias Ringwald             } else {
28760493bf3aSMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
287700d93d79Smatthias.ringwald             }
28780493bf3aSMatthias Ringwald             return;
287900d93d79Smatthias.ringwald 
28801b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
28811b9cb13dSMatthias Ringwald         case INFORMATION_RESPONSE: {
28821b9cb13dSMatthias Ringwald             hci_connection_t * connection = hci_connection_for_handle(handle);
28831b9cb13dSMatthias Ringwald             if (!connection) return;
28840defadfbSMatthias Ringwald             if (connection->l2cap_state.information_state != L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE) return;
28850defadfbSMatthias Ringwald 
28860defadfbSMatthias Ringwald             // get extended features from response if valid
28870defadfbSMatthias Ringwald             connection->l2cap_state.extended_feature_mask = 0;
28880defadfbSMatthias Ringwald             if (cmd_len >= 6) {
28891b9cb13dSMatthias Ringwald                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
28901b9cb13dSMatthias Ringwald                 uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
28910defadfbSMatthias Ringwald                 if (result == 0 && info_type == L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) {
28921b9cb13dSMatthias Ringwald                     connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
28930defadfbSMatthias Ringwald                 }
28940defadfbSMatthias Ringwald             }
28950defadfbSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
2896543b84e4SMatthias Ringwald             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
28970defadfbSMatthias Ringwald 
28981b9cb13dSMatthias Ringwald             // trigger connection request
28991b9cb13dSMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
29001b9cb13dSMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
29011b9cb13dSMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2902fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2903543b84e4SMatthias Ringwald                 if (channel->con_handle != handle) continue;
2904f8ecb114SMatthias Ringwald 
2905f8ecb114SMatthias Ringwald                 // incoming connection: ask user for channel configuration, esp. if ertm will be mandatory
2906f8ecb114SMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
2907f8ecb114SMatthias Ringwald                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2908f8ecb114SMatthias Ringwald                     l2cap_emit_incoming_connection(channel);
2909f8ecb114SMatthias Ringwald                     continue;
2910f8ecb114SMatthias Ringwald                 }
2911f8ecb114SMatthias Ringwald 
2912f8ecb114SMatthias Ringwald                 // outgoing connection
2913f8ecb114SMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
2914f8ecb114SMatthias Ringwald 
2915dae3b2abSMatthias Ringwald                     // if ERTM was requested, but is not listed in extended feature mask:
2916543b84e4SMatthias Ringwald                     if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2917dae3b2abSMatthias Ringwald 
2918f073f086SMatthias Ringwald                         if (channel->ertm_mandatory){
2919dae3b2abSMatthias Ringwald                             // bail if ERTM is mandatory
2920543b84e4SMatthias Ringwald                             channel->state = L2CAP_STATE_CLOSED;
2921543b84e4SMatthias Ringwald                             // map l2cap connection response result to BTstack status enumeration
292266a72640SMatthias Ringwald                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
2923543b84e4SMatthias Ringwald                             // discard channel
2924543b84e4SMatthias Ringwald                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2925c45d6b2cSMatthias Ringwald                             l2cap_free_channel_entry(channel);
2926543b84e4SMatthias Ringwald                             continue;
2927dae3b2abSMatthias Ringwald 
2928f073f086SMatthias Ringwald                         } else {
2929f073f086SMatthias Ringwald                             // fallback to Basic mode
293066a72640SMatthias Ringwald                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
2931f073f086SMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2932f073f086SMatthias Ringwald                         }
2933dae3b2abSMatthias Ringwald                     }
2934f8ecb114SMatthias Ringwald 
293552606043SMatthias Ringwald                     // respond to connection request
2936f8ecb114SMatthias Ringwald                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
2937f8ecb114SMatthias Ringwald                     continue;
293852606043SMatthias Ringwald                 }
29391b9cb13dSMatthias Ringwald             }
29401b9cb13dSMatthias Ringwald             return;
29411b9cb13dSMatthias Ringwald         }
29421b9cb13dSMatthias Ringwald #endif
29431b9cb13dSMatthias Ringwald 
294400d93d79Smatthias.ringwald         default:
294500d93d79Smatthias.ringwald             break;
294600d93d79Smatthias.ringwald     }
294700d93d79Smatthias.ringwald 
294800d93d79Smatthias.ringwald     // Get potential destination CID
2949f8fbdce0SMatthias Ringwald     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
295000d93d79Smatthias.ringwald 
295100d93d79Smatthias.ringwald     // Find channel for this sig_id and connection handle
2952665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2953665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2954665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2955fad84cafSMatthias Ringwald         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2956fc64f94aSMatthias Ringwald         if (channel->con_handle != handle) continue;
295700d93d79Smatthias.ringwald         if (code & 1) {
2958b1988dceSmatthias.ringwald             // match odd commands (responses) by previous signaling identifier
2959b1988dceSmatthias.ringwald             if (channel->local_sig_id == sig_id) {
296000d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
29614e32727eSmatthias.ringwald                 break;
296200d93d79Smatthias.ringwald             }
296300d93d79Smatthias.ringwald         } else {
2964b1988dceSmatthias.ringwald             // match even commands (requests) by local channel id
296500d93d79Smatthias.ringwald             if (channel->local_cid == dest_cid) {
296600d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
29674e32727eSmatthias.ringwald                 break;
296800d93d79Smatthias.ringwald             }
296900d93d79Smatthias.ringwald         }
297000d93d79Smatthias.ringwald     }
297100d93d79Smatthias.ringwald }
297209e9d05bSMatthias Ringwald #endif
297300d93d79Smatthias.ringwald 
2974e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
297509e9d05bSMatthias Ringwald 
297609e9d05bSMatthias Ringwald static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
297709e9d05bSMatthias Ringwald     uint8_t event[6];
297809e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
297909e9d05bSMatthias Ringwald     event[1] = 4;
298009e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
298109e9d05bSMatthias Ringwald     little_endian_store_16(event, 4, result);
298209e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
298309e9d05bSMatthias Ringwald     if (!l2cap_event_packet_handler) return;
298409e9d05bSMatthias Ringwald     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
298509e9d05bSMatthias Ringwald }
298609e9d05bSMatthias Ringwald 
2987c48b2a2cSMatthias Ringwald // @returns valid
2988c48b2a2cSMatthias Ringwald static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
2989e7d0c9aaSMatthias Ringwald     hci_connection_t * connection;
2990c48b2a2cSMatthias Ringwald     uint16_t result;
2991f299206dSMatthias Ringwald     uint8_t  event[12];
299283fd9c76SMatthias Ringwald 
2993cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2994a3dc965aSMatthias Ringwald     btstack_linked_list_iterator_t it;
2995a3dc965aSMatthias Ringwald     l2cap_channel_t * channel;
2996a3dc965aSMatthias Ringwald     uint16_t local_cid;
299783fd9c76SMatthias Ringwald     uint16_t le_psm;
299863f0ac45SMatthias Ringwald     uint16_t new_credits;
299963f0ac45SMatthias Ringwald     uint16_t credits_before;
3000e7d0c9aaSMatthias Ringwald     l2cap_service_t * service;
300111cae19eSMilanka Ringwald     uint16_t source_cid;
300283fd9c76SMatthias Ringwald #endif
300300d93d79Smatthias.ringwald 
30041b8b8d05SMatthias Ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3005adcfabadSMatthias Ringwald     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
30061fcd10b7SMatthias Ringwald     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
30071b8b8d05SMatthias Ringwald 
30081b8b8d05SMatthias Ringwald     switch (code){
300900d93d79Smatthias.ringwald 
3010c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_REQUEST:
3011adcfabadSMatthias Ringwald             // check size
30121fcd10b7SMatthias Ringwald             if (len < 8) return 0;
3013e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
3014da886c03S[email protected]             if (connection){
30156d91fb6cSMatthias Ringwald                 if (connection->role != HCI_ROLE_MASTER){
30166d91fb6cSMatthias Ringwald                     // reject command without notifying upper layer when not in master role
3017c48b2a2cSMatthias Ringwald                     return 0;
30186d91fb6cSMatthias Ringwald                 }
3019a4c06b28SMatthias Ringwald                 le_connection_parameter_range_t existing_range;
30204ced4e8cSMatthias Ringwald                 gap_get_connection_parameter_range(&existing_range);
3021d5e694a3SMatthias Ringwald                 uint16_t le_conn_interval_min   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3022d5e694a3SMatthias Ringwald                 uint16_t le_conn_interval_max   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3023d5e694a3SMatthias Ringwald                 uint16_t le_conn_latency        = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3024d5e694a3SMatthias Ringwald                 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
3025da886c03S[email protected] 
302673cd8a2aSMatthias Ringwald                 int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
3027da886c03S[email protected]                 if (update_parameter){
3028da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
3029da886c03S[email protected]                     connection->le_conn_interval_min = le_conn_interval_min;
3030da886c03S[email protected]                     connection->le_conn_interval_max = le_conn_interval_max;
3031da886c03S[email protected]                     connection->le_conn_latency = le_conn_latency;
3032da886c03S[email protected]                     connection->le_supervision_timeout = le_supervision_timeout;
3033da886c03S[email protected]                 } else {
3034da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
3035da886c03S[email protected]                 }
3036c48b2a2cSMatthias Ringwald                 connection->le_con_param_update_identifier = sig_id;
3037da886c03S[email protected]             }
3038da886c03S[email protected] 
303933c40538SMatthias Ringwald             if (!l2cap_event_packet_handler) break;
3040c48b2a2cSMatthias Ringwald 
3041c48b2a2cSMatthias Ringwald             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
3042c48b2a2cSMatthias Ringwald             event[1] = 8;
3043f299206dSMatthias Ringwald             little_endian_store_16(event, 2, handle);
30446535961aSMatthias Ringwald             (void)memcpy(&event[4], &command[4], 8);
3045c48b2a2cSMatthias Ringwald             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
304633c40538SMatthias Ringwald             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
3047ccf076adS[email protected]             break;
3048c48b2a2cSMatthias Ringwald 
30491fcd10b7SMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
30501fcd10b7SMatthias Ringwald             // check size
30511fcd10b7SMatthias Ringwald             if (len < 2) return 0;
30521fcd10b7SMatthias Ringwald             result = little_endian_read_16(command, 4);
30531fcd10b7SMatthias Ringwald             l2cap_emit_connection_parameter_update_response(handle, result);
30541fcd10b7SMatthias Ringwald             break;
30551fcd10b7SMatthias Ringwald 
3056a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
3057a3dc965aSMatthias Ringwald 
305863f0ac45SMatthias Ringwald         case COMMAND_REJECT:
305963f0ac45SMatthias Ringwald             // Find channel for this sig_id and connection handle
306063f0ac45SMatthias Ringwald             channel = NULL;
3061421cb104SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
306263f0ac45SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
306363f0ac45SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3064fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
306563f0ac45SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
306663f0ac45SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
306763f0ac45SMatthias Ringwald                 channel = a_channel;
306863f0ac45SMatthias Ringwald                 break;
306963f0ac45SMatthias Ringwald             }
307063f0ac45SMatthias Ringwald             if (!channel) break;
307163f0ac45SMatthias Ringwald 
307263f0ac45SMatthias Ringwald             // if received while waiting for le connection response, assume legacy device
307363f0ac45SMatthias Ringwald             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
307463f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
307563f0ac45SMatthias Ringwald                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
307644276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0x0002);
307763f0ac45SMatthias Ringwald 
307863f0ac45SMatthias Ringwald                 // discard channel
3079421cb104SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3080c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
308163f0ac45SMatthias Ringwald                 break;
308263f0ac45SMatthias Ringwald             }
308363f0ac45SMatthias Ringwald             break;
308463f0ac45SMatthias Ringwald 
3085e7d0c9aaSMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_REQUEST:
3086adcfabadSMatthias Ringwald             // check size
3087adcfabadSMatthias Ringwald             if (len < 10) return 0;
3088e7d0c9aaSMatthias Ringwald 
3089e7d0c9aaSMatthias Ringwald             // get hci connection, bail if not found (must not happen)
3090e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
3091e7d0c9aaSMatthias Ringwald             if (!connection) return 0;
3092e7d0c9aaSMatthias Ringwald 
3093e7d0c9aaSMatthias Ringwald             // check if service registered
3094e7d0c9aaSMatthias Ringwald             le_psm  = little_endian_read_16(command, 4);
3095e7d0c9aaSMatthias Ringwald             service = l2cap_le_get_service(le_psm);
309611cae19eSMilanka Ringwald             source_cid = little_endian_read_16(command, 6);
3097e7d0c9aaSMatthias Ringwald 
3098e7d0c9aaSMatthias Ringwald             if (service){
3099e7d0c9aaSMatthias Ringwald                 if (source_cid < 0x40){
3100e7d0c9aaSMatthias Ringwald                     // 0x0009 Connection refused - Invalid Source CID
3101e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
3102e7d0c9aaSMatthias Ringwald                     return 1;
3103e7d0c9aaSMatthias Ringwald                 }
3104e7d0c9aaSMatthias Ringwald 
3105e7d0c9aaSMatthias Ringwald                 // go through list of channels for this ACL connection and check if we get a match
3106421cb104SMatthias Ringwald                 btstack_linked_list_iterator_init(&it, &l2cap_channels);
3107e7d0c9aaSMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&it)){
31081b8b8d05SMatthias Ringwald                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3109fad84cafSMatthias Ringwald                     if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
31101b8b8d05SMatthias Ringwald                     if (a_channel->con_handle != handle) continue;
31111b8b8d05SMatthias Ringwald                     if (a_channel->remote_cid != source_cid) continue;
3112e7d0c9aaSMatthias Ringwald                     // 0x000a Connection refused - Source CID already allocated
3113e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
3114e7d0c9aaSMatthias Ringwald                     return 1;
3115e7d0c9aaSMatthias Ringwald                 }
3116e7d0c9aaSMatthias Ringwald 
311783fd9c76SMatthias Ringwald                 // security: check encryption
311883fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_2){
31199c6e867eSMatthias Ringwald                     if (gap_encryption_key_size(handle) == 0){
312083fd9c76SMatthias Ringwald                         // 0x0008 Connection refused - insufficient encryption
3121e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
312283fd9c76SMatthias Ringwald                         return 1;
312383fd9c76SMatthias Ringwald                     }
312483fd9c76SMatthias Ringwald                     // anything less than 16 byte key size is insufficient
31259c6e867eSMatthias Ringwald                     if (gap_encryption_key_size(handle) < 16){
312683fd9c76SMatthias Ringwald                         // 0x0007 Connection refused – insufficient encryption key size
3127e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
312883fd9c76SMatthias Ringwald                         return 1;
312983fd9c76SMatthias Ringwald                     }
313083fd9c76SMatthias Ringwald                 }
313183fd9c76SMatthias Ringwald 
313283fd9c76SMatthias Ringwald                 // security: check authencation
313383fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_3){
31349c6e867eSMatthias Ringwald                     if (!gap_authenticated(handle)){
313583fd9c76SMatthias Ringwald                         // 0x0005 Connection refused – insufficient authentication
3136e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
313783fd9c76SMatthias Ringwald                         return 1;
313883fd9c76SMatthias Ringwald                     }
313983fd9c76SMatthias Ringwald                 }
314083fd9c76SMatthias Ringwald 
314183fd9c76SMatthias Ringwald                 // security: check authorization
314283fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_4){
31439c6e867eSMatthias Ringwald                     if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
314483fd9c76SMatthias Ringwald                         // 0x0006 Connection refused – insufficient authorization
3145e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
314683fd9c76SMatthias Ringwald                         return 1;
314783fd9c76SMatthias Ringwald                     }
314883fd9c76SMatthias Ringwald                 }
3149e7d0c9aaSMatthias Ringwald 
3150e7d0c9aaSMatthias Ringwald                 // allocate channel
31515d18f623SMatthias Ringwald                 channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL, connection->address,
3152e7d0c9aaSMatthias Ringwald                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
3153e7d0c9aaSMatthias Ringwald                 if (!channel){
3154e7d0c9aaSMatthias Ringwald                     // 0x0004 Connection refused – no resources available
3155e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
3156e7d0c9aaSMatthias Ringwald                     return 1;
3157e7d0c9aaSMatthias Ringwald                 }
3158e7d0c9aaSMatthias Ringwald 
3159e7d0c9aaSMatthias Ringwald                 channel->con_handle = handle;
3160e7d0c9aaSMatthias Ringwald                 channel->remote_cid = source_cid;
3161e7d0c9aaSMatthias Ringwald                 channel->remote_sig_id = sig_id;
31627f107edaSMatthias Ringwald                 channel->remote_mtu = little_endian_read_16(command, 8);
31637f107edaSMatthias Ringwald                 channel->remote_mps = little_endian_read_16(command, 10);
31647f107edaSMatthias Ringwald                 channel->credits_outgoing = little_endian_read_16(command, 12);
3165e7d0c9aaSMatthias Ringwald 
3166e7d0c9aaSMatthias Ringwald                 // set initial state
3167e7d0c9aaSMatthias Ringwald                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
3168c99bb618SMatthias Ringwald                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
3169e7d0c9aaSMatthias Ringwald 
3170e7d0c9aaSMatthias Ringwald                 // add to connections list
3171421cb104SMatthias Ringwald                 btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
3172e7d0c9aaSMatthias Ringwald 
3173e7d0c9aaSMatthias Ringwald                 // post connection request event
317444276248SMatthias Ringwald                 l2cap_emit_le_incoming_connection(channel);
3175e7d0c9aaSMatthias Ringwald 
3176e7d0c9aaSMatthias Ringwald             } else {
3177e7d0c9aaSMatthias Ringwald                 // Connection refused – LE_PSM not supported
3178e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
3179e7d0c9aaSMatthias Ringwald             }
3180e7d0c9aaSMatthias Ringwald             break;
31811b8b8d05SMatthias Ringwald 
31821b8b8d05SMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
3183adcfabadSMatthias Ringwald             // check size
3184adcfabadSMatthias Ringwald             if (len < 10) return 0;
3185adcfabadSMatthias Ringwald 
31861b8b8d05SMatthias Ringwald             // Find channel for this sig_id and connection handle
31871b8b8d05SMatthias Ringwald             channel = NULL;
3188421cb104SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
31891b8b8d05SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
31901b8b8d05SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3191fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
31921b8b8d05SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
31931b8b8d05SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
31941b8b8d05SMatthias Ringwald                 channel = a_channel;
31951b8b8d05SMatthias Ringwald                 break;
31961b8b8d05SMatthias Ringwald             }
31971b8b8d05SMatthias Ringwald             if (!channel) break;
31981b8b8d05SMatthias Ringwald 
31991b8b8d05SMatthias Ringwald             // cid + 0
32001b8b8d05SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
32011b8b8d05SMatthias Ringwald             if (result){
32021b8b8d05SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
32031b8b8d05SMatthias Ringwald                 // map l2cap connection response result to BTstack status enumeration
320444276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, result);
32051b8b8d05SMatthias Ringwald 
32061b8b8d05SMatthias Ringwald                 // discard channel
3207421cb104SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3208c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
32091b8b8d05SMatthias Ringwald                 break;
32101b8b8d05SMatthias Ringwald             }
32111b8b8d05SMatthias Ringwald 
32121b8b8d05SMatthias Ringwald             // success
32131b8b8d05SMatthias Ringwald             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
32141b8b8d05SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
32151b8b8d05SMatthias Ringwald             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
32161b8b8d05SMatthias Ringwald             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
32171b8b8d05SMatthias Ringwald             channel->state = L2CAP_STATE_OPEN;
321844276248SMatthias Ringwald             l2cap_emit_le_channel_opened(channel, result);
32191b8b8d05SMatthias Ringwald             break;
32201b8b8d05SMatthias Ringwald 
322185aeef60SMatthias Ringwald         case LE_FLOW_CONTROL_CREDIT:
3222adcfabadSMatthias Ringwald             // check size
3223adcfabadSMatthias Ringwald             if (len < 4) return 0;
3224adcfabadSMatthias Ringwald 
322585aeef60SMatthias Ringwald             // find channel
322685aeef60SMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3227421cb104SMatthias Ringwald             channel = l2cap_get_channel_for_local_cid(local_cid);
322863f0ac45SMatthias Ringwald             if (!channel) {
322963f0ac45SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
323063f0ac45SMatthias Ringwald                 break;
323163f0ac45SMatthias Ringwald             }
323263f0ac45SMatthias Ringwald             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
323363f0ac45SMatthias Ringwald             credits_before = channel->credits_outgoing;
323463f0ac45SMatthias Ringwald             channel->credits_outgoing += new_credits;
323563f0ac45SMatthias Ringwald             // check for credit overrun
323663f0ac45SMatthias Ringwald             if (credits_before > channel->credits_outgoing){
323763f0ac45SMatthias Ringwald                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
323863f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
323963f0ac45SMatthias Ringwald                 break;
324063f0ac45SMatthias Ringwald             }
324163f0ac45SMatthias Ringwald             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
324285aeef60SMatthias Ringwald             break;
324385aeef60SMatthias Ringwald 
3244828a7f7aSMatthias Ringwald         case DISCONNECTION_REQUEST:
3245adcfabadSMatthias Ringwald 
3246adcfabadSMatthias Ringwald             // check size
3247adcfabadSMatthias Ringwald             if (len < 4) return 0;
3248adcfabadSMatthias Ringwald 
3249828a7f7aSMatthias Ringwald             // find channel
3250828a7f7aSMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3251421cb104SMatthias Ringwald             channel = l2cap_get_channel_for_local_cid(local_cid);
325263f34e00SMatthias Ringwald             if (!channel) {
325363f34e00SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
325463f34e00SMatthias Ringwald                 break;
325563f34e00SMatthias Ringwald             }
3256828a7f7aSMatthias Ringwald             channel->remote_sig_id = sig_id;
3257828a7f7aSMatthias Ringwald             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
3258828a7f7aSMatthias Ringwald             break;
3259828a7f7aSMatthias Ringwald 
3260a3dc965aSMatthias Ringwald #endif
3261a3dc965aSMatthias Ringwald 
326263f0ac45SMatthias Ringwald         case DISCONNECTION_RESPONSE:
326363f0ac45SMatthias Ringwald             break;
326463f0ac45SMatthias Ringwald 
3265c48b2a2cSMatthias Ringwald         default:
3266c48b2a2cSMatthias Ringwald             // command unknown -> reject command
3267c48b2a2cSMatthias Ringwald             return 0;
3268ccf076adS[email protected]     }
3269c48b2a2cSMatthias Ringwald     return 1;
3270c48b2a2cSMatthias Ringwald }
3271e7d0c9aaSMatthias Ringwald #endif
3272c48b2a2cSMatthias Ringwald 
3273bb0a72a6SMatthias Ringwald static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3274bb0a72a6SMatthias Ringwald #ifdef ENABLE_CLASSIC
327509e9d05bSMatthias Ringwald     l2cap_channel_t * l2cap_channel;
3276fad84cafSMatthias Ringwald     l2cap_fixed_channel_t * l2cap_fixed_channel;
327709e9d05bSMatthias Ringwald 
3278c48b2a2cSMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3279c48b2a2cSMatthias Ringwald     switch (channel_id) {
3280c48b2a2cSMatthias Ringwald 
3281c48b2a2cSMatthias Ringwald         case L2CAP_CID_SIGNALING: {
3282eaeabfdaSMatthias Ringwald             uint32_t command_offset = 8;
3283eaeabfdaSMatthias Ringwald             while ((command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET) < size) {
3284ed2ed8e1SMatthias Ringwald                 // assert signaling command is fully inside packet
3285ed2ed8e1SMatthias Ringwald                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3286eaeabfdaSMatthias Ringwald                 uint32_t next_command_offset = command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
3287ed2ed8e1SMatthias Ringwald                 if (next_command_offset > size){
3288ed2ed8e1SMatthias Ringwald                     log_error("l2cap signaling command len invalid -> drop");
3289ed2ed8e1SMatthias Ringwald                     break;
3290ed2ed8e1SMatthias Ringwald                 }
3291ed2ed8e1SMatthias Ringwald                 // handle signaling command
3292c48b2a2cSMatthias Ringwald                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
3293ed2ed8e1SMatthias Ringwald                 // go to next command
3294eaeabfdaSMatthias Ringwald                 command_offset = next_command_offset;
3295c48b2a2cSMatthias Ringwald             }
3296c48b2a2cSMatthias Ringwald             break;
3297c48b2a2cSMatthias Ringwald         }
3298c48b2a2cSMatthias Ringwald         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
3299fad84cafSMatthias Ringwald             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL);
3300fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel) break;
3301fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel->packet_handler) break;
3302fad84cafSMatthias Ringwald             (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3303c48b2a2cSMatthias Ringwald             break;
33041bbc0b23S[email protected] 
330509e9d05bSMatthias Ringwald         default:
330600d93d79Smatthias.ringwald             // Find channel for this channel_id and connection handle
330764e11ca9SMatthias Ringwald             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
3308d1fd2a88SMatthias Ringwald             if (l2cap_channel) {
330927e0774aSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
331027e0774aSMatthias Ringwald                 if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
331127e0774aSMatthias Ringwald 
33126574158aSMatthias Ringwald                     int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
331307c7de86SMatthias Ringwald 
33146574158aSMatthias Ringwald                     // assert control + FCS fields are inside
33156574158aSMatthias Ringwald                     if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) break;
33166574158aSMatthias Ringwald 
33176574158aSMatthias Ringwald                     if (l2cap_channel->fcs_option){
3318fcb125edSMatthias Ringwald                         // verify FCS (required if one side requested it)
331927e0774aSMatthias Ringwald                         uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
332027e0774aSMatthias Ringwald                         uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
3321e288be62SMatthias Ringwald 
3322e288be62SMatthias Ringwald #ifdef L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL
3323e288be62SMatthias Ringwald                         // simulate fcs error
3324e288be62SMatthias Ringwald                         static int counter = 0;
3325e288be62SMatthias Ringwald                         if (++counter == L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL) {
3326e288be62SMatthias Ringwald                             log_info("Simulate fcs error");
3327e288be62SMatthias Ringwald                             fcs_calculated++;
3328e288be62SMatthias Ringwald                             counter = 0;
3329e288be62SMatthias Ringwald                         }
3330e288be62SMatthias Ringwald #endif
3331e288be62SMatthias Ringwald 
33326574158aSMatthias Ringwald                         if (fcs_calculated == fcs_packet){
33336574158aSMatthias Ringwald                             log_info("Packet FCS 0x%04x verified", fcs_packet);
33346574158aSMatthias Ringwald                         } else {
333527e0774aSMatthias Ringwald                             log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
3336ef2faf56SMatthias Ringwald                             // ERTM State Machine in Bluetooth Spec does not handle 'I-Frame with invalid FCS'
333727e0774aSMatthias Ringwald                             break;
333827e0774aSMatthias Ringwald                         }
33396574158aSMatthias Ringwald                     }
334027e0774aSMatthias Ringwald 
334127e0774aSMatthias Ringwald                     // switch on packet type
334227e0774aSMatthias Ringwald                     uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
334338f62777SMatthias Ringwald                     uint8_t  req_seq = (control >> 8) & 0x3f;
33442bea1b8dSMatthias Ringwald                     int final = (control >> 7) & 0x01;
334527e0774aSMatthias Ringwald                     if (control & 1){
334627e0774aSMatthias Ringwald                         // S-Frame
334778cd8a22SMatthias Ringwald                         int poll  = (control >> 4) & 0x01;
3348bdbe2e49SMatthias Ringwald                         l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
33499ffcbce4SMatthias Ringwald                         log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
33507b7901d8SMatthias Ringwald                         l2cap_ertm_tx_packet_state_t * tx_state;
3351bdbe2e49SMatthias Ringwald                         switch (s){
3352bdbe2e49SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
33539ffcbce4SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
33541e1a46bbSMatthias Ringwald                                 l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
33553233d8abSMatthias Ringwald                                 if (poll && final){
33563233d8abSMatthias Ringwald                                     // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
33573233d8abSMatthias Ringwald                                     log_error("P=F=1 in S-Frame");
33583233d8abSMatthias Ringwald                                     break;
33593233d8abSMatthias Ringwald                                 }
336078cd8a22SMatthias Ringwald                                 if (poll){
3361f85ade6bSMatthias Ringwald                                     // check if we did request selective retransmission before <==> we have stored SDU segments
3362f85ade6bSMatthias Ringwald                                     int i;
3363f85ade6bSMatthias Ringwald                                     int num_stored_out_of_order_packets = 0;
3364f85ade6bSMatthias Ringwald                                     for (i=0;i<l2cap_channel->num_rx_buffers;i++){
3365f85ade6bSMatthias Ringwald                                         int index = l2cap_channel->rx_store_index + i;
3366f85ade6bSMatthias Ringwald                                         if (index >= l2cap_channel->num_rx_buffers){
3367f85ade6bSMatthias Ringwald                                             index -= l2cap_channel->num_rx_buffers;
3368f85ade6bSMatthias Ringwald                                         }
3369f85ade6bSMatthias Ringwald                                         l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3370f85ade6bSMatthias Ringwald                                         if (!rx_state->valid) continue;
3371f85ade6bSMatthias Ringwald                                         num_stored_out_of_order_packets++;
3372f85ade6bSMatthias Ringwald                                     }
3373f85ade6bSMatthias Ringwald                                     if (num_stored_out_of_order_packets){
3374f85ade6bSMatthias Ringwald                                         l2cap_channel->send_supervisor_frame_selective_reject = 1;
3375f85ade6bSMatthias Ringwald                                     } else {
3376d2afdd38SMatthias Ringwald                                         l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
337778cd8a22SMatthias Ringwald                                     }
3378f85ade6bSMatthias Ringwald                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
3379f85ade6bSMatthias Ringwald                                 }
33803233d8abSMatthias Ringwald                                 if (final){
3381550189ffSMatthias Ringwald                                     // Stop-MonitorTimer
3382550189ffSMatthias Ringwald                                     l2cap_ertm_stop_monitor_timer(l2cap_channel);
3383550189ffSMatthias Ringwald                                     // If UnackedFrames > 0 then Start-RetransTimer
338494301352SMatthias Ringwald                                     if (l2cap_channel->unacked_frames){
3385550189ffSMatthias Ringwald                                         l2cap_ertm_start_retransmission_timer(l2cap_channel);
3386550189ffSMatthias Ringwald                                     }
33873233d8abSMatthias Ringwald                                     // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3388ef2faf56SMatthias Ringwald                                     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
33893233d8abSMatthias Ringwald                                 }
3390bdbe2e49SMatthias Ringwald                                 break;
33919ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
33929ffcbce4SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
33931e1a46bbSMatthias Ringwald                                 l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3394600cf12dSMatthias Ringwald                                 // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
3395ef2faf56SMatthias Ringwald                                 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
33969ffcbce4SMatthias Ringwald                                 break;
33979ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
33989ffcbce4SMatthias Ringwald                                 log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
33999ffcbce4SMatthias Ringwald                                 break;
34009ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
34017b7901d8SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
34027b7901d8SMatthias Ringwald                                 if (poll){
34031e1a46bbSMatthias Ringwald                                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
34047b7901d8SMatthias Ringwald                                 }
34057b7901d8SMatthias Ringwald                                 // find requested i-frame
34067b7901d8SMatthias Ringwald                                 tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
34077b7901d8SMatthias Ringwald                                 if (tx_state){
34087b7901d8SMatthias Ringwald                                     log_info("Retransmission for tx_seq %u requested", req_seq);
3409d2afdd38SMatthias Ringwald                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
34107b7901d8SMatthias Ringwald                                     tx_state->retransmission_requested = 1;
34117b7901d8SMatthias Ringwald                                     l2cap_channel->srej_active = 1;
34127b7901d8SMatthias Ringwald                                 }
34139ffcbce4SMatthias Ringwald                                 break;
3414bdbe2e49SMatthias Ringwald                             default:
3415bdbe2e49SMatthias Ringwald                                 break;
3416bdbe2e49SMatthias Ringwald                         }
341727e0774aSMatthias Ringwald                         break;
341827e0774aSMatthias Ringwald                     } else {
341927e0774aSMatthias Ringwald                         // I-Frame
342027e0774aSMatthias Ringwald                         // get control
342127e0774aSMatthias Ringwald                         l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
342238f62777SMatthias Ringwald                         uint8_t tx_seq = (control >> 1) & 0x3f;
342338f62777SMatthias Ringwald                         log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
3424e8e9809fSMatthias Ringwald                         log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
342538f62777SMatthias Ringwald                         log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
34261e1a46bbSMatthias Ringwald                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
342711b576c5SMatthias Ringwald                         if (final){
342811b576c5SMatthias Ringwald                             // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3429ef2faf56SMatthias Ringwald                             l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
343011b576c5SMatthias Ringwald                         }
343107c7de86SMatthias Ringwald 
343207c7de86SMatthias Ringwald                         // get SDU
3433826c39d0SMatthias Ringwald                         const uint8_t * payload_data = &packet[COMPLETE_L2CAP_HEADER+2];
3434826c39d0SMatthias Ringwald                         uint16_t        payload_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
343507c7de86SMatthias Ringwald 
343607c7de86SMatthias Ringwald                         // assert SDU size is smaller or equal to our buffers
3437826c39d0SMatthias Ringwald                         uint16_t max_payload_size = 0;
3438826c39d0SMatthias Ringwald                         switch (sar){
3439826c39d0SMatthias Ringwald                             case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
3440826c39d0SMatthias Ringwald                             case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
3441826c39d0SMatthias Ringwald                                 // SDU Length + MPS
3442826c39d0SMatthias Ringwald                                 max_payload_size = l2cap_channel->local_mps + 2;
3443826c39d0SMatthias Ringwald                                 break;
3444826c39d0SMatthias Ringwald                             case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
3445826c39d0SMatthias Ringwald                             case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
3446826c39d0SMatthias Ringwald                                 max_payload_size = l2cap_channel->local_mps;
3447826c39d0SMatthias Ringwald                                 break;
3448826c39d0SMatthias Ringwald                         }
3449826c39d0SMatthias Ringwald                         if (payload_len > max_payload_size){
3450826c39d0SMatthias Ringwald                             log_info("payload len %u > max payload %u -> drop packet", payload_len, max_payload_size);
3451826c39d0SMatthias Ringwald                             break;
3452826c39d0SMatthias Ringwald                         }
345307c7de86SMatthias Ringwald 
345438f62777SMatthias Ringwald                         // check ordering
345538f62777SMatthias Ringwald                         if (l2cap_channel->expected_tx_seq == tx_seq){
345638f62777SMatthias Ringwald                             log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
345738f62777SMatthias Ringwald                             l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3458f85ade6bSMatthias Ringwald                             l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3459d48432d4SMatthias Ringwald 
3460e32be409SMatthias Ringwald                             // process SDU
3461826c39d0SMatthias Ringwald                             l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, payload_data, payload_len);
3462d48432d4SMatthias Ringwald 
346370734707SMatthias Ringwald                             // process stored segments
3464ff3cc4a5SMatthias Ringwald                             while (true){
346570734707SMatthias Ringwald                                 int index = l2cap_channel->rx_store_index;
346670734707SMatthias Ringwald                                 l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
346770734707SMatthias Ringwald                                 if (!rx_state->valid) break;
3468f85ade6bSMatthias Ringwald 
3469f85ade6bSMatthias Ringwald                                 log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
3470f85ade6bSMatthias Ringwald                                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3471f85ade6bSMatthias Ringwald                                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3472f85ade6bSMatthias Ringwald 
347370734707SMatthias Ringwald                                 rx_state->valid = 0;
347470734707SMatthias Ringwald                                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
3475f85ade6bSMatthias Ringwald 
3476f85ade6bSMatthias Ringwald                                 // update rx store index
347770734707SMatthias Ringwald                                 index++;
347870734707SMatthias Ringwald                                 if (index >= l2cap_channel->num_rx_buffers){
347970734707SMatthias Ringwald                                     index = 0;
348070734707SMatthias Ringwald                                 }
348170734707SMatthias Ringwald                                 l2cap_channel->rx_store_index = index;
348270734707SMatthias Ringwald                             }
348370734707SMatthias Ringwald 
3484f85ade6bSMatthias Ringwald                             //
3485f85ade6bSMatthias Ringwald                             l2cap_channel->send_supervisor_frame_receiver_ready = 1;
3486f85ade6bSMatthias Ringwald 
3487c7309e8dSMatthias Ringwald                         } else {
3488df2191a7SMatthias Ringwald                             int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
3489df2191a7SMatthias Ringwald                             if (delta < 2){
349070734707SMatthias Ringwald                                 // store segment
3491826c39d0SMatthias Ringwald                                 l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, payload_data, payload_len);
349270734707SMatthias Ringwald 
3493df2191a7SMatthias Ringwald                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
3494df2191a7SMatthias Ringwald                                 l2cap_channel->send_supervisor_frame_selective_reject = 1;
3495df2191a7SMatthias Ringwald                             } else {
3496df2191a7SMatthias Ringwald                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
3497c7309e8dSMatthias Ringwald                                 l2cap_channel->send_supervisor_frame_reject = 1;
349827e0774aSMatthias Ringwald                             }
349938f62777SMatthias Ringwald                         }
3500df2191a7SMatthias Ringwald                     }
350127e0774aSMatthias Ringwald                     break;
350227e0774aSMatthias Ringwald                 }
350327e0774aSMatthias Ringwald #endif
35043d50b4baSMatthias Ringwald                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
350500d93d79Smatthias.ringwald             }
3506bb0a72a6SMatthias Ringwald             break;
3507bb0a72a6SMatthias Ringwald     }
3508bb0a72a6SMatthias Ringwald #else
3509bb0a72a6SMatthias Ringwald     UNUSED(handle); // ok: no code
3510bb0a72a6SMatthias Ringwald     UNUSED(packet); // ok: no code
3511bb0a72a6SMatthias Ringwald     UNUSED(size);   // ok: no code
351209e9d05bSMatthias Ringwald #endif
3513bb0a72a6SMatthias Ringwald }
3514bb0a72a6SMatthias Ringwald 
3515bb0a72a6SMatthias Ringwald static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3516bb0a72a6SMatthias Ringwald #ifdef ENABLE_BLE
3517bb0a72a6SMatthias Ringwald 
3518fad84cafSMatthias Ringwald     l2cap_fixed_channel_t * l2cap_fixed_channel;
3519fad84cafSMatthias Ringwald 
3520bb0a72a6SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
3521bb0a72a6SMatthias Ringwald     l2cap_channel_t * l2cap_channel;
3522bb0a72a6SMatthias Ringwald #endif
3523bb0a72a6SMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3524bb0a72a6SMatthias Ringwald     switch (channel_id) {
3525bb0a72a6SMatthias Ringwald 
3526bb0a72a6SMatthias Ringwald         case L2CAP_CID_SIGNALING_LE: {
3527bb0a72a6SMatthias Ringwald             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
3528adcfabadSMatthias Ringwald             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
3529505f1c30SMatthias Ringwald             if ((COMPLETE_L2CAP_HEADER + 4 + len) > size) break;
3530bb0a72a6SMatthias Ringwald             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
3531bb0a72a6SMatthias Ringwald             if (!valid){
3532bb0a72a6SMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3533bb0a72a6SMatthias Ringwald             }
3534bb0a72a6SMatthias Ringwald             break;
3535bb0a72a6SMatthias Ringwald         }
3536bb0a72a6SMatthias Ringwald 
3537bb0a72a6SMatthias Ringwald         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
3538fad84cafSMatthias Ringwald             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL);
3539fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel) break;
3540fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel->packet_handler) break;
3541fad84cafSMatthias Ringwald             (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3542bb0a72a6SMatthias Ringwald             break;
3543bb0a72a6SMatthias Ringwald 
3544bb0a72a6SMatthias Ringwald         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
3545fad84cafSMatthias Ringwald             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
3546fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel) break;
3547fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel->packet_handler) break;
3548fad84cafSMatthias Ringwald             (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3549bb0a72a6SMatthias Ringwald             break;
3550bb0a72a6SMatthias Ringwald 
3551bb0a72a6SMatthias Ringwald         default:
3552bb0a72a6SMatthias Ringwald 
3553a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
3554421cb104SMatthias Ringwald             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
355564e11ca9SMatthias Ringwald             if (l2cap_channel) {
355685aeef60SMatthias Ringwald                 // credit counting
355785aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming == 0){
355885aeef60SMatthias Ringwald                     log_error("LE Data Channel packet received but no incoming credits");
355985aeef60SMatthias Ringwald                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
356085aeef60SMatthias Ringwald                     break;
356185aeef60SMatthias Ringwald                 }
356285aeef60SMatthias Ringwald                 l2cap_channel->credits_incoming--;
356385aeef60SMatthias Ringwald 
356485aeef60SMatthias Ringwald                 // automatic credits
3565c1ab6cc1SMatthias Ringwald                 if ((l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK) && l2cap_channel->automatic_credits){
356685aeef60SMatthias Ringwald                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
356785aeef60SMatthias Ringwald                 }
356885aeef60SMatthias Ringwald 
3569cd529728SMatthias Ringwald                 // first fragment
3570cd529728SMatthias Ringwald                 uint16_t pos = 0;
3571cd529728SMatthias Ringwald                 if (!l2cap_channel->receive_sdu_len){
3572bb98c113SMatthias Ringwald                     uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3573bb98c113SMatthias Ringwald                     if(sdu_len > l2cap_channel->local_mtu) break;   // SDU would be larger than our buffer
3574bb98c113SMatthias Ringwald                     l2cap_channel->receive_sdu_len = sdu_len;
3575cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_pos = 0;
3576cd529728SMatthias Ringwald                     pos  += 2;
3577cd529728SMatthias Ringwald                     size -= 2;
3578cd529728SMatthias Ringwald                 }
3579bb98c113SMatthias Ringwald                 uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
3580bb98c113SMatthias Ringwald                 uint16_t remaining_space = l2cap_channel->local_mtu - l2cap_channel->receive_sdu_pos;
3581bb98c113SMatthias Ringwald                 if (fragment_size > remaining_space) break;         // SDU would cause buffer overrun
35826535961aSMatthias Ringwald                 (void)memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos],
35836535961aSMatthias Ringwald                              &packet[COMPLETE_L2CAP_HEADER + pos],
35846535961aSMatthias Ringwald                              fragment_size);
3585cd529728SMatthias Ringwald                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
3586cd529728SMatthias Ringwald                 // done?
3587895ff4a5SMatthias Ringwald                 log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
3588cd529728SMatthias Ringwald                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
3589cd529728SMatthias Ringwald                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
3590cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = 0;
3591cd529728SMatthias Ringwald                 }
359263f0ac45SMatthias Ringwald             } else {
359363f0ac45SMatthias Ringwald                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
359464e11ca9SMatthias Ringwald             }
359564e11ca9SMatthias Ringwald #endif
35965652b5ffS[email protected]             break;
35975652b5ffS[email protected]     }
3598bb0a72a6SMatthias Ringwald #else
3599bb0a72a6SMatthias Ringwald     UNUSED(handle); // ok: no code
3600bb0a72a6SMatthias Ringwald     UNUSED(packet); // ok: no code
3601bb0a72a6SMatthias Ringwald     UNUSED(size);   // ok: no code
3602bb0a72a6SMatthias Ringwald #endif
3603bb0a72a6SMatthias Ringwald }
3604bb0a72a6SMatthias Ringwald 
3605bb0a72a6SMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
3606bb0a72a6SMatthias Ringwald     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
3607bb0a72a6SMatthias Ringwald     UNUSED(channel);        // ok: there is no channel
3608bb0a72a6SMatthias Ringwald 
3609adcfabadSMatthias Ringwald     // Assert full L2CAP header present
3610adcfabadSMatthias Ringwald     if (size < COMPLETE_L2CAP_HEADER) return;
3611adcfabadSMatthias Ringwald 
3612f16129ceSMatthias Ringwald     // Dispatch to Classic or LE handler (SCO packets are not dispatched to L2CAP)
3613bb0a72a6SMatthias Ringwald     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
3614bb0a72a6SMatthias Ringwald     hci_connection_t *conn = hci_connection_for_handle(handle);
3615bb0a72a6SMatthias Ringwald     if (!conn) return;
3616f16129ceSMatthias Ringwald     if (conn->address_type == BD_ADDR_TYPE_ACL){
3617bb0a72a6SMatthias Ringwald         l2cap_acl_classic_handler(handle, packet, size);
3618bb0a72a6SMatthias Ringwald     } else {
3619bb0a72a6SMatthias Ringwald         l2cap_acl_le_handler(handle, packet, size);
3620bb0a72a6SMatthias Ringwald     }
362100d93d79Smatthias.ringwald 
36221eb2563eS[email protected]     l2cap_run();
36232718e2e7Smatthias.ringwald }
362400d93d79Smatthias.ringwald 
362509e9d05bSMatthias Ringwald // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
362609e9d05bSMatthias Ringwald void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
3627fad84cafSMatthias Ringwald     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
3628fad84cafSMatthias Ringwald     if (!channel) return;
3629fad84cafSMatthias Ringwald     channel->packet_handler = the_packet_handler;
363009e9d05bSMatthias Ringwald }
363109e9d05bSMatthias Ringwald 
363209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
363315ec09bbSmatthias.ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
363427a923d0Smatthias.ringwald void l2cap_finialize_channel_close(l2cap_channel_t * channel){
3635f62db1e3Smatthias.ringwald     channel->state = L2CAP_STATE_CLOSED;
363666a72640SMatthias Ringwald     l2cap_handle_channel_closed(channel);
3637f62db1e3Smatthias.ringwald     // discard channel
3638665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3639c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
3640c8e4258aSmatthias.ringwald }
364113aa3e4bSMatthias Ringwald #endif
36421e6aba47Smatthias.ringwald 
364313aa3e4bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
36448f2a52f4SMatthias Ringwald static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3645665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
3646665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, services);
3647665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
3648665d90f2SMatthias Ringwald         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
36499d9bbc01Smatthias.ringwald         if ( service->psm == psm){
36509d9bbc01Smatthias.ringwald             return service;
36519d9bbc01Smatthias.ringwald         };
36529d9bbc01Smatthias.ringwald     }
36539d9bbc01Smatthias.ringwald     return NULL;
36549d9bbc01Smatthias.ringwald }
365513aa3e4bSMatthias Ringwald #endif
36569d9bbc01Smatthias.ringwald 
365713aa3e4bSMatthias Ringwald #ifdef ENABLE_CLASSIC
36587192e786SMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
36597192e786SMatthias Ringwald     return l2cap_get_service_internal(&l2cap_services, psm);
36607192e786SMatthias Ringwald }
36617192e786SMatthias Ringwald 
3662be2053a6SMatthias 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){
3663be2053a6SMatthias Ringwald 
3664be2053a6SMatthias Ringwald     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
3665e0abb8e7S[email protected] 
36664bb582b6Smatthias.ringwald     // check for alread registered psm
36679d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
3668277abc2cSmatthias.ringwald     if (service) {
3669be2053a6SMatthias Ringwald         log_error("l2cap_register_service: PSM %u already registered", psm);
3670be2053a6SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
3671277abc2cSmatthias.ringwald     }
36729d9bbc01Smatthias.ringwald 
36734bb582b6Smatthias.ringwald     // alloc structure
3674bb69aaaeS[email protected]     service = btstack_memory_l2cap_service_get();
3675277abc2cSmatthias.ringwald     if (!service) {
3676be2053a6SMatthias Ringwald         log_error("l2cap_register_service: no memory for l2cap_service_t");
3677be2053a6SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
3678277abc2cSmatthias.ringwald     }
36799d9bbc01Smatthias.ringwald 
36809d9bbc01Smatthias.ringwald     // fill in
36819d9bbc01Smatthias.ringwald     service->psm = psm;
36829d9bbc01Smatthias.ringwald     service->mtu = mtu;
368305ae8de3SMatthias Ringwald     service->packet_handler = service_packet_handler;
3684df3354fcS[email protected]     service->required_security_level = security_level;
36859d9bbc01Smatthias.ringwald 
36869d9bbc01Smatthias.ringwald     // add to services list
3687665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
3688c0e866bfSmatthias.ringwald 
3689c0e866bfSmatthias.ringwald     // enable page scan
369015a95bd5SMatthias Ringwald     gap_connectable_control(1);
36915842b6d9Smatthias.ringwald 
3692c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
36939d9bbc01Smatthias.ringwald }
36949d9bbc01Smatthias.ringwald 
36957e8856ebSMatthias Ringwald uint8_t l2cap_unregister_service(uint16_t psm){
3696e0abb8e7S[email protected] 
3697e0abb8e7S[email protected]     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
3698e0abb8e7S[email protected] 
36999d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
37007e8856ebSMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3701665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
3702d3a9df87Smatthias.ringwald     btstack_memory_l2cap_service_free(service);
3703c0e866bfSmatthias.ringwald 
3704c0e866bfSmatthias.ringwald     // disable page scan when no services registered
37057e8856ebSMatthias Ringwald     if (btstack_linked_list_empty(&l2cap_services)) {
370615a95bd5SMatthias Ringwald         gap_connectable_control(0);
37079d9bbc01Smatthias.ringwald     }
3708c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
37097e8856ebSMatthias Ringwald }
371009e9d05bSMatthias Ringwald #endif
37119d9bbc01Smatthias.ringwald 
37127192e786SMatthias Ringwald 
3713cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
371483fd9c76SMatthias Ringwald 
371557be49d6SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
371657be49d6SMatthias Ringwald     if (!channel->waiting_for_can_send_now) return;
371757be49d6SMatthias Ringwald     if (channel->send_sdu_buffer) return;
371857be49d6SMatthias Ringwald     channel->waiting_for_can_send_now = 0;
3719895ff4a5SMatthias Ringwald     log_debug("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
372057be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
372157be49d6SMatthias Ringwald }
372257be49d6SMatthias Ringwald 
372357be49d6SMatthias Ringwald // 1BH2222
372457be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
372557be49d6SMatthias 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",
372657be49d6SMatthias Ringwald              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
372757be49d6SMatthias Ringwald     uint8_t event[19];
372857be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
372957be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
373057be49d6SMatthias Ringwald     event[2] = channel->address_type;
373157be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
373257be49d6SMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
373357be49d6SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
373457be49d6SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
373557be49d6SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
373657be49d6SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_mtu);
373757be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
373857be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
373957be49d6SMatthias Ringwald }
374057be49d6SMatthias Ringwald // 11BH22222
374157be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
374257be49d6SMatthias 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",
374357be49d6SMatthias Ringwald              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
374457be49d6SMatthias Ringwald              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
3745c99bb618SMatthias Ringwald     uint8_t event[23];
374657be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
374757be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
374857be49d6SMatthias Ringwald     event[2] = status;
374957be49d6SMatthias Ringwald     event[3] = channel->address_type;
375057be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[4]);
375157be49d6SMatthias Ringwald     little_endian_store_16(event, 10, channel->con_handle);
3752c1ab6cc1SMatthias Ringwald     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
3753c99bb618SMatthias Ringwald     little_endian_store_16(event, 13, channel->psm);
3754c99bb618SMatthias Ringwald     little_endian_store_16(event, 15, channel->local_cid);
3755c99bb618SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_cid);
3756c99bb618SMatthias Ringwald     little_endian_store_16(event, 19, channel->local_mtu);
3757c99bb618SMatthias Ringwald     little_endian_store_16(event, 21, channel->remote_mtu);
375857be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
375957be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
376057be49d6SMatthias Ringwald }
376187050a0bSMatthias Ringwald // 2
376287050a0bSMatthias Ringwald static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel){
376387050a0bSMatthias Ringwald     log_info("L2CAP_EVENT_LE_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
376487050a0bSMatthias Ringwald     uint8_t event[4];
376587050a0bSMatthias Ringwald     event[0] = L2CAP_EVENT_LE_CHANNEL_CLOSED;
376687050a0bSMatthias Ringwald     event[1] = sizeof(event) - 2;
376787050a0bSMatthias Ringwald     little_endian_store_16(event, 2, channel->local_cid);
376887050a0bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
376987050a0bSMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
377087050a0bSMatthias Ringwald }
377187050a0bSMatthias Ringwald 
37726774d5c9SMatthias Ringwald static void l2cap_le_send_pdu(l2cap_channel_t *channel){
37736774d5c9SMatthias Ringwald     btstack_assert(channel != NULL);
37746774d5c9SMatthias Ringwald     btstack_assert(channel->send_pdu_buffer != NULL);
37756774d5c9SMatthias Ringwald     btstack_assert(channel->credits_outgoing > 0);
37766774d5c9SMatthias Ringwald 
37776774d5c9SMatthias Ringwald     // send part of SDU
37786774d5c9SMatthias Ringwald     hci_reserve_packet_buffer();
37796774d5c9SMatthias Ringwald     uint8_t * acl_buffer = hci_get_outgoing_packet_buffer();
37806774d5c9SMatthias Ringwald     uint8_t * l2cap_payload = acl_buffer + 8;
37816774d5c9SMatthias Ringwald     uint16_t pos = 0;
37826774d5c9SMatthias Ringwald     if (!channel->send_sdu_pos){
37836774d5c9SMatthias Ringwald         // store SDU len
37846774d5c9SMatthias Ringwald         channel->send_sdu_pos += 2;
37856774d5c9SMatthias Ringwald         little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
37866774d5c9SMatthias Ringwald         pos += 2;
37876774d5c9SMatthias Ringwald     }
37886774d5c9SMatthias Ringwald     uint16_t payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
37896774d5c9SMatthias Ringwald     log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
37906535961aSMatthias Ringwald     (void)memcpy(&l2cap_payload[pos],
37916535961aSMatthias Ringwald                  &channel->send_sdu_buffer[channel->send_sdu_pos - 2],
37926535961aSMatthias Ringwald                  payload_size); // -2 for virtual SDU len
37936774d5c9SMatthias Ringwald     pos += payload_size;
37946774d5c9SMatthias Ringwald     channel->send_sdu_pos += payload_size;
37956774d5c9SMatthias Ringwald     l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
37966774d5c9SMatthias Ringwald 
37976774d5c9SMatthias Ringwald     channel->credits_outgoing--;
37986774d5c9SMatthias Ringwald 
37996774d5c9SMatthias Ringwald     hci_send_acl_packet_buffer(8 + pos);
38006774d5c9SMatthias Ringwald 
3801c1ab6cc1SMatthias Ringwald     if (channel->send_sdu_pos >= (channel->send_sdu_len + 2)){
38026774d5c9SMatthias Ringwald         channel->send_sdu_buffer = NULL;
38036774d5c9SMatthias Ringwald         // send done event
38046774d5c9SMatthias Ringwald         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
38056774d5c9SMatthias Ringwald         // inform about can send now
38066774d5c9SMatthias Ringwald         l2cap_le_notify_channel_can_send(channel);
38076774d5c9SMatthias Ringwald     }
38086774d5c9SMatthias Ringwald }
38096774d5c9SMatthias Ringwald 
381057be49d6SMatthias Ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
381157be49d6SMatthias Ringwald void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
381257be49d6SMatthias Ringwald     channel->state = L2CAP_STATE_CLOSED;
381357be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
381457be49d6SMatthias Ringwald     // discard channel
3815421cb104SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3816c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
381757be49d6SMatthias Ringwald }
381857be49d6SMatthias Ringwald 
3819e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
3820e7d0c9aaSMatthias Ringwald     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
38217192e786SMatthias Ringwald }
3822efedfb4cSMatthias Ringwald 
3823da144af5SMatthias Ringwald uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
38247192e786SMatthias Ringwald 
3825da144af5SMatthias Ringwald     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
38267192e786SMatthias Ringwald 
38277192e786SMatthias Ringwald     // check for alread registered psm
38287192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
38297192e786SMatthias Ringwald     if (service) {
3830da144af5SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
38317192e786SMatthias Ringwald     }
38327192e786SMatthias Ringwald 
38337192e786SMatthias Ringwald     // alloc structure
38347192e786SMatthias Ringwald     service = btstack_memory_l2cap_service_get();
38357192e786SMatthias Ringwald     if (!service) {
38367192e786SMatthias Ringwald         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
3837da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
38387192e786SMatthias Ringwald     }
38397192e786SMatthias Ringwald 
38407192e786SMatthias Ringwald     // fill in
38417192e786SMatthias Ringwald     service->psm = psm;
3842da144af5SMatthias Ringwald     service->mtu = 0;
38437192e786SMatthias Ringwald     service->packet_handler = packet_handler;
38447192e786SMatthias Ringwald     service->required_security_level = security_level;
38457192e786SMatthias Ringwald 
38467192e786SMatthias Ringwald     // add to services list
3847665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
38487192e786SMatthias Ringwald 
38497192e786SMatthias Ringwald     // done
38509dd26175SMilanka Ringwald     return ERROR_CODE_SUCCESS;
38517192e786SMatthias Ringwald }
38527192e786SMatthias Ringwald 
3853da144af5SMatthias Ringwald uint8_t l2cap_le_unregister_service(uint16_t psm) {
38547192e786SMatthias Ringwald     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
38557192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
38569367f9b0SMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3857da144af5SMatthias Ringwald 
3858665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
38597192e786SMatthias Ringwald     btstack_memory_l2cap_service_free(service);
3860c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
38617192e786SMatthias Ringwald }
3862da144af5SMatthias Ringwald 
3863da144af5SMatthias Ringwald uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
3864e7d0c9aaSMatthias Ringwald     // get channel
3865421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3866e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3867e7d0c9aaSMatthias Ringwald 
3868e7d0c9aaSMatthias Ringwald     // validate state
3869e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3870e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
3871e7d0c9aaSMatthias Ringwald     }
3872e7d0c9aaSMatthias Ringwald 
3873efedfb4cSMatthias Ringwald     // set state accept connection
387423017473SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
387523017473SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
387623017473SMatthias Ringwald     channel->local_mtu = mtu;
387785aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
387885aeef60SMatthias Ringwald     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
387985aeef60SMatthias Ringwald 
388085aeef60SMatthias Ringwald     // test
388163f0ac45SMatthias Ringwald     // channel->new_credits_incoming = 1;
3882e7d0c9aaSMatthias Ringwald 
3883e7d0c9aaSMatthias Ringwald     // go
3884e7d0c9aaSMatthias Ringwald     l2cap_run();
3885c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
3886da144af5SMatthias Ringwald }
3887da144af5SMatthias Ringwald 
3888da144af5SMatthias Ringwald /**
3889da144af5SMatthias Ringwald  * @brief Deny incoming LE Data Channel connection due to resource constraints
3890da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3891da144af5SMatthias Ringwald  */
3892da144af5SMatthias Ringwald 
3893da144af5SMatthias Ringwald uint8_t l2cap_le_decline_connection(uint16_t local_cid){
3894e7d0c9aaSMatthias Ringwald     // get channel
3895421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3896e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3897e7d0c9aaSMatthias Ringwald 
3898e7d0c9aaSMatthias Ringwald     // validate state
3899e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3900e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
3901e7d0c9aaSMatthias Ringwald     }
3902e7d0c9aaSMatthias Ringwald 
3903efedfb4cSMatthias Ringwald     // set state decline connection
3904e7d0c9aaSMatthias Ringwald     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
3905e7d0c9aaSMatthias Ringwald     channel->reason = 0x04; // no resources available
3906e7d0c9aaSMatthias Ringwald     l2cap_run();
3907c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
3908da144af5SMatthias Ringwald }
3909da144af5SMatthias Ringwald 
39107dafa750SMatthias Ringwald uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
3911da144af5SMatthias Ringwald     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
3912efedfb4cSMatthias Ringwald     uint16_t * out_local_cid) {
3913efedfb4cSMatthias Ringwald 
39147dafa750SMatthias Ringwald     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
3915da144af5SMatthias Ringwald 
39167dafa750SMatthias Ringwald 
39177dafa750SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
39187dafa750SMatthias Ringwald     if (!connection) {
39197dafa750SMatthias Ringwald         log_error("no hci_connection for handle 0x%04x", con_handle);
39207dafa750SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
39217dafa750SMatthias Ringwald     }
39227dafa750SMatthias Ringwald 
39235d18f623SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL, connection->address, connection->address_type, psm, mtu, security_level);
3924da144af5SMatthias Ringwald     if (!channel) {
3925da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
3926da144af5SMatthias Ringwald     }
3927e7d0c9aaSMatthias Ringwald     log_info("l2cap_le_create_channel %p", channel);
3928da144af5SMatthias Ringwald 
3929da144af5SMatthias Ringwald     // store local_cid
3930da144af5SMatthias Ringwald     if (out_local_cid){
3931da144af5SMatthias Ringwald        *out_local_cid = channel->local_cid;
3932da144af5SMatthias Ringwald     }
3933da144af5SMatthias Ringwald 
39347dafa750SMatthias Ringwald     // provide buffer
39357dafa750SMatthias Ringwald     channel->con_handle = con_handle;
3936cd529728SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
39377dafa750SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
393885aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
393985aeef60SMatthias Ringwald     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
394085aeef60SMatthias Ringwald 
3941efedfb4cSMatthias Ringwald     // add to connections list
3942421cb104SMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
3943efedfb4cSMatthias Ringwald 
39447dafa750SMatthias Ringwald     // go
394563f0ac45SMatthias Ringwald     l2cap_run();
3946c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
3947da144af5SMatthias Ringwald }
3948da144af5SMatthias Ringwald 
3949da144af5SMatthias Ringwald /**
3950da144af5SMatthias Ringwald  * @brief Provide credtis for LE Data Channel
3951da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3952da144af5SMatthias Ringwald  * @param credits               Number additional credits for peer
3953da144af5SMatthias Ringwald  */
395464e11ca9SMatthias Ringwald uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
395563f0ac45SMatthias Ringwald 
3956421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
395763f0ac45SMatthias Ringwald     if (!channel) {
395863f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
395963f0ac45SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
396063f0ac45SMatthias Ringwald     }
396163f0ac45SMatthias Ringwald 
3962efedfb4cSMatthias Ringwald     // check state
396363f0ac45SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN){
396463f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
396563f0ac45SMatthias Ringwald     }
396663f0ac45SMatthias Ringwald 
396763f0ac45SMatthias Ringwald     // assert incoming credits + credits <= 0xffff
396863f0ac45SMatthias Ringwald     uint32_t total_credits = channel->credits_incoming;
396963f0ac45SMatthias Ringwald     total_credits += channel->new_credits_incoming;
397063f0ac45SMatthias Ringwald     total_credits += credits;
397163f0ac45SMatthias Ringwald     if (total_credits > 0xffff){
397263f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
397363f0ac45SMatthias Ringwald             channel->new_credits_incoming, credits);
397463f0ac45SMatthias Ringwald     }
397563f0ac45SMatthias Ringwald 
3976efedfb4cSMatthias Ringwald     // set credits_granted
397763f0ac45SMatthias Ringwald     channel->new_credits_incoming += credits;
397863f0ac45SMatthias Ringwald 
397963f0ac45SMatthias Ringwald     // go
398063f0ac45SMatthias Ringwald     l2cap_run();
39819dd26175SMilanka Ringwald     return ERROR_CODE_SUCCESS;
3982da144af5SMatthias Ringwald }
3983da144af5SMatthias Ringwald 
3984da144af5SMatthias Ringwald /**
3985da144af5SMatthias Ringwald  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
3986da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3987da144af5SMatthias Ringwald  */
398864e11ca9SMatthias Ringwald int l2cap_le_can_send_now(uint16_t local_cid){
3989421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
399044276248SMatthias Ringwald     if (!channel) {
399144276248SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
3992da144af5SMatthias Ringwald         return 0;
3993da144af5SMatthias Ringwald     }
3994da144af5SMatthias Ringwald 
399544276248SMatthias Ringwald     // check state
399644276248SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN) return 0;
399744276248SMatthias Ringwald 
399844276248SMatthias Ringwald     // check queue
399944276248SMatthias Ringwald     if (channel->send_sdu_buffer) return 0;
400044276248SMatthias Ringwald 
400144276248SMatthias Ringwald     // fine, go ahead
400244276248SMatthias Ringwald     return 1;
400344276248SMatthias Ringwald }
400444276248SMatthias Ringwald 
4005da144af5SMatthias Ringwald /**
4006da144af5SMatthias Ringwald  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
4007da144af5SMatthias Ringwald  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
4008da144af5SMatthias Ringwald  *       so packet handler should be ready to handle it
4009da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
4010da144af5SMatthias Ringwald  */
401164e11ca9SMatthias Ringwald uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
4012421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
401344276248SMatthias Ringwald     if (!channel) {
401444276248SMatthias Ringwald         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
4015c8b2b785SMilanka Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
401644276248SMatthias Ringwald     }
401744276248SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
401844276248SMatthias Ringwald     l2cap_le_notify_channel_can_send(channel);
4019c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
4020da144af5SMatthias Ringwald }
4021da144af5SMatthias Ringwald 
4022da144af5SMatthias Ringwald /**
4023da144af5SMatthias Ringwald  * @brief Send data via LE Data Channel
4024da144af5SMatthias Ringwald  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
4025da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
4026da144af5SMatthias Ringwald  * @param data                  data to send
4027da144af5SMatthias Ringwald  * @param size                  data size
4028da144af5SMatthias Ringwald  */
402964e11ca9SMatthias Ringwald uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
403064e11ca9SMatthias Ringwald 
4031421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
403264e11ca9SMatthias Ringwald     if (!channel) {
403364e11ca9SMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4034828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
403564e11ca9SMatthias Ringwald     }
403664e11ca9SMatthias Ringwald 
403764e11ca9SMatthias Ringwald     if (len > channel->remote_mtu){
403864e11ca9SMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
403964e11ca9SMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
404064e11ca9SMatthias Ringwald     }
404164e11ca9SMatthias Ringwald 
40427f107edaSMatthias Ringwald     if (channel->send_sdu_buffer){
404364e11ca9SMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
404464e11ca9SMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
404564e11ca9SMatthias Ringwald     }
404664e11ca9SMatthias Ringwald 
40477f107edaSMatthias Ringwald     channel->send_sdu_buffer = data;
40487f107edaSMatthias Ringwald     channel->send_sdu_len    = len;
40497f107edaSMatthias Ringwald     channel->send_sdu_pos    = 0;
405064e11ca9SMatthias Ringwald 
40516774d5c9SMatthias Ringwald     l2cap_notify_channel_can_send();
4052c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
4053da144af5SMatthias Ringwald }
4054da144af5SMatthias Ringwald 
4055da144af5SMatthias Ringwald /**
4056da144af5SMatthias Ringwald  * @brief Disconnect from LE Data Channel
4057da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
4058da144af5SMatthias Ringwald  */
4059828a7f7aSMatthias Ringwald uint8_t l2cap_le_disconnect(uint16_t local_cid)
4060da144af5SMatthias Ringwald {
4061421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4062828a7f7aSMatthias Ringwald     if (!channel) {
4063828a7f7aSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4064828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4065828a7f7aSMatthias Ringwald     }
4066828a7f7aSMatthias Ringwald 
4067828a7f7aSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4068828a7f7aSMatthias Ringwald     l2cap_run();
4069c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
4070da144af5SMatthias Ringwald }
4071da144af5SMatthias Ringwald 
40727f02f414SMatthias Ringwald #endif
4073