xref: /btstack/src/l2cap.c (revision ea6a43fa4b9fc0a3024149aff68253fd3f6d59ec)
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"
53*ea6a43faSMatthias Ringwald #include "btstack_bool.h"
5416ece135SMatthias Ringwald #include "btstack_debug.h"
550e2df43fSMatthias Ringwald #include "btstack_event.h"
56d3a9df87Smatthias.ringwald #include "btstack_memory.h"
5743625864Smatthias.ringwald 
5843625864Smatthias.ringwald #include <stdarg.h>
5943625864Smatthias.ringwald #include <string.h>
6043625864Smatthias.ringwald 
6143625864Smatthias.ringwald #include <stdio.h>
6243625864Smatthias.ringwald 
63a6e314f1SMatthias Ringwald /*
64a6e314f1SMatthias Ringwald  * @brief L2CAP Supervisory function in S-Frames
65a6e314f1SMatthias Ringwald  */
66a6e314f1SMatthias Ringwald typedef enum {
67a6e314f1SMatthias Ringwald     L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY = 0,
68a6e314f1SMatthias Ringwald     L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT,
69a6e314f1SMatthias Ringwald     L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY,
70a6e314f1SMatthias Ringwald     L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT
71a6e314f1SMatthias Ringwald } l2cap_supervisory_function_t;
72a6e314f1SMatthias Ringwald 
73a6e314f1SMatthias Ringwald /**
74a6e314f1SMatthias Ringwald  * @brief L2CAP Information Types used in Information Request & Response
75a6e314f1SMatthias Ringwald  */
76a6e314f1SMatthias Ringwald typedef enum {
77a6e314f1SMatthias Ringwald   L2CAP_INFO_TYPE_CONNECTIONLESS_MTU = 1,
78a6e314f1SMatthias Ringwald   L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED,
79a6e314f1SMatthias Ringwald   L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED,
80a6e314f1SMatthias Ringwald } l2cap_info_type_t;
81a6e314f1SMatthias Ringwald 
82a6e314f1SMatthias Ringwald /**
83a6e314f1SMatthias Ringwald  * @brief L2CAP Configuration Option Types used in Configurateion Request & Response
84a6e314f1SMatthias Ringwald  */
85a6e314f1SMatthias Ringwald typedef enum {
86a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT = 1,
87a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT,
88a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_QUALITY_OF_SERVICE,
89a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL,
90a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE,
91a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_EXTENDED_FLOW_SPECIFICATION,
92a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE,
93a6e314f1SMatthias Ringwald } l2cap_config_option_type_t;
94a6e314f1SMatthias Ringwald 
95a6e314f1SMatthias Ringwald 
96a6e314f1SMatthias Ringwald #define L2CAP_SIG_ID_INVALID 0
97a6e314f1SMatthias Ringwald 
98a6e314f1SMatthias Ringwald // size of HCI ACL + L2CAP Header for regular data packets (8)
99a6e314f1SMatthias Ringwald #define COMPLETE_L2CAP_HEADER (HCI_ACL_HEADER_SIZE + L2CAP_HEADER_SIZE)
100a6e314f1SMatthias Ringwald 
101a6e314f1SMatthias Ringwald // L2CAP Configuration Result Codes
102a6e314f1SMatthias Ringwald #define L2CAP_CONF_RESULT_SUCCESS                  0x0000
103a6e314f1SMatthias Ringwald #define L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS  0x0001
104a6e314f1SMatthias Ringwald #define L2CAP_CONF_RESULT_REJECT                   0x0002
105a6e314f1SMatthias Ringwald #define L2CAP_CONF_RESULT_UNKNOWN_OPTIONS          0x0003
106a6e314f1SMatthias Ringwald #define L2CAP_CONF_RESULT_PENDING                  0x0004
107a6e314f1SMatthias Ringwald #define L2CAP_CONF_RESULT_FLOW_SPEC_REJECTED       0x0005
108a6e314f1SMatthias Ringwald 
109a6e314f1SMatthias Ringwald // L2CAP Reject Result Codes
110a6e314f1SMatthias Ringwald #define L2CAP_REJ_CMD_UNKNOWN                      0x0000
111a6e314f1SMatthias Ringwald 
112a6e314f1SMatthias Ringwald // Response Timeout eXpired
113a6e314f1SMatthias Ringwald #define L2CAP_RTX_TIMEOUT_MS   10000
114a6e314f1SMatthias Ringwald 
115a6e314f1SMatthias Ringwald // Extended Response Timeout eXpired
116a6e314f1SMatthias Ringwald #define L2CAP_ERTX_TIMEOUT_MS 120000
117a6e314f1SMatthias Ringwald 
1184c744e21Smatthias.ringwald // nr of buffered acl packets in outgoing queue to get max performance
1194c744e21Smatthias.ringwald #define NR_BUFFERED_ACL_PACKETS 3
1204c744e21Smatthias.ringwald 
12139bda6d5Smatthias.ringwald // used to cache l2cap rejects, echo, and informational requests
122e16a9cacSmatthias.ringwald #define NR_PENDING_SIGNALING_RESPONSES 3
12339bda6d5Smatthias.ringwald 
12485aeef60SMatthias Ringwald // nr of credits provided to remote if credits fall below watermark
12585aeef60SMatthias Ringwald #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK 5
12685aeef60SMatthias Ringwald #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT 5
12785aeef60SMatthias Ringwald 
12800d93d79Smatthias.ringwald // offsets for L2CAP SIGNALING COMMANDS
12900d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
13000d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
13100d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
13200d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
13300d93d79Smatthias.ringwald 
13409e9d05bSMatthias Ringwald #if defined(ENABLE_LE_DATA_CHANNELS) || defined(ENABLE_CLASSIC)
13509e9d05bSMatthias Ringwald #define L2CAP_USES_CHANNELS
13609e9d05bSMatthias Ringwald #endif
13709e9d05bSMatthias Ringwald 
13833c40538SMatthias Ringwald // prototypes
139675e6881SMatthias Ringwald static void l2cap_run(void);
14033c40538SMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
1413d50b4baSMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size );
14230725612SMatthias Ringwald static void l2cap_notify_channel_can_send(void);
14309e9d05bSMatthias Ringwald static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel);
1446ddef68dSMilanka Ringwald static uint8_t  l2cap_next_sig_id(void);
1457740e150SMatthias Ringwald static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid);
14609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
147474f5c3fSMatthias Ringwald static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel);
148474f5c3fSMatthias Ringwald static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel);
14909e9d05bSMatthias Ringwald static void l2cap_finialize_channel_close(l2cap_channel_t *channel);
15009e9d05bSMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm);
15109e9d05bSMatthias Ringwald static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
15209e9d05bSMatthias Ringwald static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
15309e9d05bSMatthias Ringwald static void l2cap_emit_incoming_connection(l2cap_channel_t *channel);
15409e9d05bSMatthias Ringwald static int  l2cap_channel_ready_for_open(l2cap_channel_t *channel);
15509e9d05bSMatthias Ringwald #endif
156cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
15757be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status);
15887050a0bSMatthias Ringwald static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel);
15957be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel);
16044276248SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel);
161828a7f7aSMatthias Ringwald static void l2cap_le_finialize_channel_close(l2cap_channel_t *channel);
1626774d5c9SMatthias Ringwald static void l2cap_le_send_pdu(l2cap_channel_t *channel);
163e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t psm);
164e7d0c9aaSMatthias Ringwald #endif
165474f5c3fSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
1666a5ffed8SMatthias Ringwald static uint16_t l2cap_next_local_cid(void);
1676a5ffed8SMatthias Ringwald static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid);
168836ae835SMatthias Ringwald static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code);
169474f5c3fSMatthias Ringwald static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size);
170474f5c3fSMatthias Ringwald static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid);
1715d18f623SMatthias 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,
172474f5c3fSMatthias Ringwald         uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level);
173c45d6b2cSMatthias Ringwald static void l2cap_free_channel_entry(l2cap_channel_t * channel);
174474f5c3fSMatthias Ringwald #endif
175212b6be2SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
17696646001SMatthias Ringwald static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel);
177c9300dcaSMatthias Ringwald static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts);
1788a700052SMatthias Ringwald static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts);
179212b6be2SMatthias Ringwald #endif
18033c40538SMatthias Ringwald 
181fad84cafSMatthias Ringwald // l2cap_fixed_channel_t entries
18224eb964eSMatthias Ringwald #ifdef ENABLE_BLE
183fad84cafSMatthias Ringwald static l2cap_fixed_channel_t l2cap_fixed_channel_att;
184fad84cafSMatthias Ringwald static l2cap_fixed_channel_t l2cap_fixed_channel_sm;
18524eb964eSMatthias Ringwald #endif
18624eb964eSMatthias Ringwald #ifdef ENABLE_CLASSIC
187fad84cafSMatthias Ringwald static l2cap_fixed_channel_t l2cap_fixed_channel_connectionless;
18824eb964eSMatthias Ringwald #endif
1895628cf69SMatthias Ringwald 
19009e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1915628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_services;
19209e9d05bSMatthias Ringwald static uint8_t require_security_level2_for_outgoing_sdp;
193ece97caeSMatthias Ringwald static bd_addr_t l2cap_outgoing_classic_addr;
19409e9d05bSMatthias Ringwald #endif
19557be49d6SMatthias Ringwald 
19657be49d6SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1975628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_le_services;
19857be49d6SMatthias Ringwald #endif
19939bda6d5Smatthias.ringwald 
200fad84cafSMatthias Ringwald // single list of channels for Classic Channels, LE Data Channels, Classic Connectionless, ATT, and SM
201421cb104SMatthias Ringwald static btstack_linked_list_t l2cap_channels;
2026a5ffed8SMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
2036ddef68dSMilanka Ringwald // next channel id for new connections
2046ddef68dSMilanka Ringwald static uint16_t  local_source_cid  = 0x40;
2056a5ffed8SMatthias Ringwald #endif
2066ddef68dSMilanka Ringwald // next signaling sequence number
2076ddef68dSMilanka Ringwald static uint8_t   sig_seq_nr  = 0xff;
208421cb104SMatthias Ringwald 
20939bda6d5Smatthias.ringwald // used to cache l2cap rejects, echo, and informational requests
2102b83fb7dSmatthias.ringwald static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
2112b83fb7dSmatthias.ringwald static int signaling_responses_pending;
212fb37a842SMatthias Ringwald static btstack_packet_callback_registration_t hci_event_callback_registration;
21339bda6d5Smatthias.ringwald 
214d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
215d6ed9f9cSMatthias Ringwald // only used for connection parameter update events
216d6ed9f9cSMatthias Ringwald static btstack_packet_handler_t l2cap_event_packet_handler;
21725818320SMatthias Ringwald static uint16_t l2cap_le_custom_max_mtu;
218d6ed9f9cSMatthias Ringwald #endif
219d6ed9f9cSMatthias Ringwald 
22085ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
22185ddcd84SMatthias Ringwald 
222e288be62SMatthias Ringwald // enable for testing
223e288be62SMatthias Ringwald // #define L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL 16
224e288be62SMatthias Ringwald 
22585ddcd84SMatthias Ringwald /*
22685ddcd84SMatthias Ringwald  * CRC lookup table for generator polynom D^16 + D^15 + D^2 + 1
22785ddcd84SMatthias Ringwald  */
22885ddcd84SMatthias Ringwald static const uint16_t crc16_table[256] = {
22985ddcd84SMatthias Ringwald     0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
23085ddcd84SMatthias Ringwald     0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841,
23185ddcd84SMatthias Ringwald     0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41,
23285ddcd84SMatthias Ringwald     0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040,
23385ddcd84SMatthias Ringwald     0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441,
23485ddcd84SMatthias Ringwald     0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840,
23585ddcd84SMatthias Ringwald     0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40,
23685ddcd84SMatthias Ringwald     0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041,
23785ddcd84SMatthias Ringwald     0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
23885ddcd84SMatthias Ringwald     0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840,
23985ddcd84SMatthias Ringwald     0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
24085ddcd84SMatthias Ringwald     0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041,
24185ddcd84SMatthias Ringwald     0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440,
24285ddcd84SMatthias Ringwald     0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841,
24385ddcd84SMatthias Ringwald     0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41,
24485ddcd84SMatthias Ringwald     0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040,
24585ddcd84SMatthias Ringwald };
24685ddcd84SMatthias Ringwald 
24785ddcd84SMatthias Ringwald static uint16_t crc16_calc(uint8_t * data, uint16_t len){
24885ddcd84SMatthias Ringwald     uint16_t crc = 0;   // initial value = 0
24985ddcd84SMatthias Ringwald     while (len--){
25085ddcd84SMatthias Ringwald         crc = (crc >> 8) ^ crc16_table[ (crc ^ ((uint16_t) *data++)) & 0x00FF ];
25185ddcd84SMatthias Ringwald     }
25285ddcd84SMatthias Ringwald     return crc;
25385ddcd84SMatthias Ringwald }
25485ddcd84SMatthias Ringwald 
255474f5c3fSMatthias 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){
256474f5c3fSMatthias Ringwald     return (((uint16_t) sar) << 14) | (req_seq << 8) | (final << 7) | (tx_seq << 1) | 0;
257474f5c3fSMatthias Ringwald }
258474f5c3fSMatthias Ringwald 
259474f5c3fSMatthias 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){
260474f5c3fSMatthias Ringwald     return (req_seq << 8) | (final << 7) | (poll << 4) | (((int) supervisory_function) << 2) | 1;
261474f5c3fSMatthias Ringwald }
262474f5c3fSMatthias Ringwald 
263474f5c3fSMatthias Ringwald static int l2cap_next_ertm_seq_nr(int seq_nr){
264474f5c3fSMatthias Ringwald     return (seq_nr + 1) & 0x3f;
265474f5c3fSMatthias Ringwald }
266474f5c3fSMatthias Ringwald 
267474f5c3fSMatthias Ringwald static int l2cap_ertm_can_store_packet_now(l2cap_channel_t * channel){
268474f5c3fSMatthias Ringwald     // get num free tx buffers
269a8409e80SMatthias Ringwald     int num_free_tx_buffers = channel->num_tx_buffers - channel->num_stored_tx_frames;
270474f5c3fSMatthias Ringwald     // calculate num tx buffers for remote MTU
271474f5c3fSMatthias Ringwald     int num_tx_buffers_for_max_remote_mtu;
272b90eac91SMatthias Ringwald     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
273b90eac91SMatthias Ringwald     if (channel->remote_mtu <= effective_mps){
274474f5c3fSMatthias Ringwald         // MTU fits into single packet
275474f5c3fSMatthias Ringwald         num_tx_buffers_for_max_remote_mtu = 1;
276474f5c3fSMatthias Ringwald     } else {
277474f5c3fSMatthias Ringwald         // include SDU Length
278b90eac91SMatthias Ringwald         num_tx_buffers_for_max_remote_mtu = (channel->remote_mtu + 2 + (effective_mps - 1)) / effective_mps;
279474f5c3fSMatthias Ringwald     }
280a8409e80SMatthias 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);
281474f5c3fSMatthias Ringwald     return num_tx_buffers_for_max_remote_mtu <= num_free_tx_buffers;
282474f5c3fSMatthias Ringwald }
283474f5c3fSMatthias Ringwald 
284ef2faf56SMatthias Ringwald static void l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel_t * l2cap_channel){
285ef2faf56SMatthias Ringwald     log_info("Retransmit unacknowleged frames");
286ef2faf56SMatthias Ringwald     l2cap_channel->unacked_frames = 0;;
287ef2faf56SMatthias Ringwald     l2cap_channel->tx_send_index  = l2cap_channel->tx_read_index;
288ef2faf56SMatthias Ringwald }
289ef2faf56SMatthias Ringwald 
290474f5c3fSMatthias Ringwald static void l2cap_ertm_next_tx_write_index(l2cap_channel_t * channel){
291474f5c3fSMatthias Ringwald     channel->tx_write_index++;
292474f5c3fSMatthias Ringwald     if (channel->tx_write_index < channel->num_tx_buffers) return;
293474f5c3fSMatthias Ringwald     channel->tx_write_index = 0;
294474f5c3fSMatthias Ringwald }
295474f5c3fSMatthias Ringwald 
296474f5c3fSMatthias Ringwald static void l2cap_ertm_start_monitor_timer(l2cap_channel_t * channel){
297550189ffSMatthias Ringwald     log_info("Start Monitor timer");
298474f5c3fSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->monitor_timer);
299474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->monitor_timer, &l2cap_ertm_monitor_timeout_callback);
300474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer_context(&channel->monitor_timer, channel);
301474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer(&channel->monitor_timer, channel->local_monitor_timeout_ms);
302474f5c3fSMatthias Ringwald     btstack_run_loop_add_timer(&channel->monitor_timer);
303474f5c3fSMatthias Ringwald }
304474f5c3fSMatthias Ringwald 
305550189ffSMatthias Ringwald static void l2cap_ertm_stop_monitor_timer(l2cap_channel_t * channel){
306550189ffSMatthias Ringwald     log_info("Stop Monitor timer");
307550189ffSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->monitor_timer);
308550189ffSMatthias Ringwald }
309474f5c3fSMatthias Ringwald 
310474f5c3fSMatthias Ringwald static void l2cap_ertm_start_retransmission_timer(l2cap_channel_t * channel){
311550189ffSMatthias Ringwald     log_info("Start Retransmission timer");
312474f5c3fSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->retransmission_timer);
313474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->retransmission_timer, &l2cap_ertm_retransmission_timeout_callback);
314474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer_context(&channel->retransmission_timer, channel);
315474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer(&channel->retransmission_timer, channel->local_retransmission_timeout_ms);
316474f5c3fSMatthias Ringwald     btstack_run_loop_add_timer(&channel->retransmission_timer);
317474f5c3fSMatthias Ringwald }
318474f5c3fSMatthias Ringwald 
319474f5c3fSMatthias Ringwald static void l2cap_ertm_stop_retransmission_timer(l2cap_channel_t * l2cap_channel){
320550189ffSMatthias Ringwald     log_info("Stop Retransmission timer");
321474f5c3fSMatthias Ringwald     btstack_run_loop_remove_timer(&l2cap_channel->retransmission_timer);
322474f5c3fSMatthias Ringwald }
323474f5c3fSMatthias Ringwald 
324474f5c3fSMatthias Ringwald static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts){
325550189ffSMatthias Ringwald     log_info("Monitor timeout");
326474f5c3fSMatthias Ringwald     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
327474f5c3fSMatthias Ringwald 
328474f5c3fSMatthias Ringwald     // TODO: we assume that it's the oldest packet
329474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
330474f5c3fSMatthias Ringwald     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
331474f5c3fSMatthias Ringwald 
332474f5c3fSMatthias Ringwald     // check retry count
333474f5c3fSMatthias Ringwald     if (tx_state->retry_count < l2cap_channel->remote_max_transmit){
334474f5c3fSMatthias Ringwald         // increment retry count
335474f5c3fSMatthias Ringwald         tx_state->retry_count++;
336474f5c3fSMatthias Ringwald 
337ef2faf56SMatthias Ringwald         // start retransmit
338ef2faf56SMatthias Ringwald         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
339ef2faf56SMatthias Ringwald 
340ef2faf56SMatthias Ringwald         // start monitor timer
341474f5c3fSMatthias Ringwald         l2cap_ertm_start_monitor_timer(l2cap_channel);
342474f5c3fSMatthias Ringwald 
343474f5c3fSMatthias Ringwald         // send RR/P=1
344474f5c3fSMatthias Ringwald         l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
345474f5c3fSMatthias Ringwald     } else {
346474f5c3fSMatthias Ringwald         log_info("Monitor timer expired & retry count >= max transmit -> disconnect");
347474f5c3fSMatthias Ringwald         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
348474f5c3fSMatthias Ringwald     }
349474f5c3fSMatthias Ringwald     l2cap_run();
350474f5c3fSMatthias Ringwald }
351474f5c3fSMatthias Ringwald 
352474f5c3fSMatthias Ringwald static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts){
353550189ffSMatthias Ringwald     log_info("Retransmission timeout");
354474f5c3fSMatthias Ringwald     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
355474f5c3fSMatthias Ringwald 
356474f5c3fSMatthias Ringwald     // TODO: we assume that it's the oldest packet
357474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
358474f5c3fSMatthias Ringwald     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
359474f5c3fSMatthias Ringwald 
360474f5c3fSMatthias Ringwald     // set retry count = 1
361474f5c3fSMatthias Ringwald     tx_state->retry_count = 1;
362474f5c3fSMatthias Ringwald 
363ef2faf56SMatthias Ringwald     // start retransmit
364ef2faf56SMatthias Ringwald     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
365ef2faf56SMatthias Ringwald 
366474f5c3fSMatthias Ringwald     // start monitor timer
367474f5c3fSMatthias Ringwald     l2cap_ertm_start_monitor_timer(l2cap_channel);
368474f5c3fSMatthias Ringwald 
369474f5c3fSMatthias Ringwald     // send RR/P=1
370474f5c3fSMatthias Ringwald     l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
371474f5c3fSMatthias Ringwald     l2cap_run();
372474f5c3fSMatthias Ringwald }
373474f5c3fSMatthias Ringwald 
374474f5c3fSMatthias Ringwald static int l2cap_ertm_send_information_frame(l2cap_channel_t * channel, int index, int final){
375474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
376474f5c3fSMatthias Ringwald     hci_reserve_packet_buffer();
377474f5c3fSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
378474f5c3fSMatthias Ringwald     uint16_t control = l2cap_encanced_control_field_for_information_frame(tx_state->tx_seq, final, channel->req_seq, tx_state->sar);
379474f5c3fSMatthias Ringwald     log_info("I-Frame: control 0x%04x", control);
380474f5c3fSMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
3816535961aSMatthias Ringwald     (void)memcpy(&acl_buffer[8 + 2],
3826535961aSMatthias Ringwald                  &channel->tx_packets_data[index * channel->local_mps],
3836535961aSMatthias Ringwald                  tx_state->len);
3841e1a46bbSMatthias Ringwald     // (re-)start retransmission timer on
3851e1a46bbSMatthias Ringwald     l2cap_ertm_start_retransmission_timer(channel);
386474f5c3fSMatthias Ringwald     // send
387474f5c3fSMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2 + tx_state->len);
388474f5c3fSMatthias Ringwald }
389474f5c3fSMatthias Ringwald 
390474f5c3fSMatthias 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){
391474f5c3fSMatthias Ringwald     // get next index for storing packets
392474f5c3fSMatthias Ringwald     int index = channel->tx_write_index;
393474f5c3fSMatthias Ringwald 
394474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
395474f5c3fSMatthias Ringwald     tx_state->tx_seq = channel->next_tx_seq;
396474f5c3fSMatthias Ringwald     tx_state->sar = sar;
397474f5c3fSMatthias Ringwald     tx_state->retry_count = 0;
398474f5c3fSMatthias Ringwald 
3993b81f0d3SMatthias Ringwald     uint8_t * tx_packet = &channel->tx_packets_data[index * channel->local_mps];
400b90eac91SMatthias 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);
401474f5c3fSMatthias Ringwald     int pos = 0;
402474f5c3fSMatthias Ringwald     if (sar == L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU){
403474f5c3fSMatthias Ringwald         little_endian_store_16(tx_packet, 0, sdu_length);
404474f5c3fSMatthias Ringwald         pos += 2;
405474f5c3fSMatthias Ringwald     }
4066535961aSMatthias Ringwald     (void)memcpy(&tx_packet[pos], data, len);
407b90eac91SMatthias Ringwald     tx_state->len = pos + len;
408474f5c3fSMatthias Ringwald 
409474f5c3fSMatthias Ringwald     // update
410a8409e80SMatthias Ringwald     channel->num_stored_tx_frames++;
411474f5c3fSMatthias Ringwald     channel->next_tx_seq = l2cap_next_ertm_seq_nr(channel->next_tx_seq);
412474f5c3fSMatthias Ringwald     l2cap_ertm_next_tx_write_index(channel);
41394301352SMatthias Ringwald 
414a8409e80SMatthias 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);
41594301352SMatthias Ringwald 
416474f5c3fSMatthias Ringwald }
417474f5c3fSMatthias Ringwald 
418474f5c3fSMatthias Ringwald static int l2cap_ertm_send(l2cap_channel_t * channel, uint8_t * data, uint16_t len){
419474f5c3fSMatthias Ringwald     if (len > channel->remote_mtu){
420a8409e80SMatthias Ringwald         log_error("l2cap_ertm_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
421474f5c3fSMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
422474f5c3fSMatthias Ringwald     }
423474f5c3fSMatthias Ringwald 
424a8409e80SMatthias Ringwald     if (!l2cap_ertm_can_store_packet_now(channel)){
425a8409e80SMatthias Ringwald         log_error("l2cap_ertm_send cid 0x%02x, fragment store full", channel->local_cid);
426a8409e80SMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
427a8409e80SMatthias Ringwald     }
428a8409e80SMatthias Ringwald 
429474f5c3fSMatthias Ringwald     // check if it needs to get fragmented
430b90eac91SMatthias Ringwald     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
431b90eac91SMatthias Ringwald     if (len > effective_mps){
432474f5c3fSMatthias Ringwald         // fragmentation needed.
433474f5c3fSMatthias Ringwald         l2cap_segmentation_and_reassembly_t sar =  L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU;
434474f5c3fSMatthias Ringwald         int chunk_len;
435474f5c3fSMatthias Ringwald         while (len){
436474f5c3fSMatthias Ringwald             switch (sar){
437474f5c3fSMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
438b90eac91SMatthias Ringwald                     chunk_len = effective_mps - 2;    // sdu_length
439474f5c3fSMatthias Ringwald                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
440474f5c3fSMatthias Ringwald                     len -= chunk_len;
441474f5c3fSMatthias Ringwald                     sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU;
442474f5c3fSMatthias Ringwald                     break;
443474f5c3fSMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
444b90eac91SMatthias Ringwald                     chunk_len = effective_mps;
445474f5c3fSMatthias Ringwald                     if (chunk_len >= len){
446474f5c3fSMatthias Ringwald                         sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU;
447474f5c3fSMatthias Ringwald                         chunk_len = len;
448474f5c3fSMatthias Ringwald                     }
449474f5c3fSMatthias Ringwald                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
450474f5c3fSMatthias Ringwald                     len -= chunk_len;
451474f5c3fSMatthias Ringwald                     break;
452474f5c3fSMatthias Ringwald                 default:
453474f5c3fSMatthias Ringwald                     break;
454474f5c3fSMatthias Ringwald             }
455474f5c3fSMatthias Ringwald         }
456474f5c3fSMatthias Ringwald 
457474f5c3fSMatthias Ringwald     } else {
458474f5c3fSMatthias Ringwald         l2cap_ertm_store_fragment(channel, L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU, 0, data, len);
459474f5c3fSMatthias Ringwald     }
460474f5c3fSMatthias Ringwald 
461474f5c3fSMatthias Ringwald     // try to send
462d89ab698SMatthias Ringwald     l2cap_notify_channel_can_send();
463474f5c3fSMatthias Ringwald     return 0;
464474f5c3fSMatthias Ringwald }
465474f5c3fSMatthias Ringwald 
4667cbe539fSMatthias Ringwald static uint16_t l2cap_setup_options_ertm_request(l2cap_channel_t * channel, uint8_t * config_options){
467fcb125edSMatthias Ringwald     int pos = 0;
468fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
469fcb125edSMatthias Ringwald     config_options[pos++] = 9;      // length
470fcb125edSMatthias Ringwald     config_options[pos++] = (uint8_t) channel->mode;
471fcb125edSMatthias Ringwald     config_options[pos++] = channel->num_rx_buffers;    // == TxWindows size
472fcb125edSMatthias Ringwald     config_options[pos++] = channel->local_max_transmit;
473fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
474fcb125edSMatthias Ringwald     pos += 2;
475fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
476fcb125edSMatthias Ringwald     pos += 2;
477fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_mps);
478fcb125edSMatthias Ringwald     pos += 2;
4796574158aSMatthias Ringwald     //
480fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT;
481fcb125edSMatthias Ringwald     config_options[pos++] = 2;     // length
482fcb125edSMatthias Ringwald     little_endian_store_16(config_options, pos, channel->local_mtu);
483fcb125edSMatthias Ringwald     pos += 2;
484c425ea4aSMatthias Ringwald 
485c425ea4aSMatthias Ringwald     // Issue: iOS (e.g. 10.2) uses "No FCS" as default while Core 5.0 specifies "FCS" as default
486c425ea4aSMatthias Ringwald     // Workaround: try to actively negotiate FCS option
487fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
488fcb125edSMatthias Ringwald     config_options[pos++] = 1;     // length
489fcb125edSMatthias Ringwald     config_options[pos++] = channel->fcs_option;
490f2c70799Sandryblack     return pos; // 11+4+3=18
491474f5c3fSMatthias Ringwald }
492474f5c3fSMatthias Ringwald 
4937cbe539fSMatthias Ringwald static uint16_t l2cap_setup_options_ertm_response(l2cap_channel_t * channel, uint8_t * config_options){
494fcb125edSMatthias Ringwald     int pos = 0;
495fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
496fcb125edSMatthias Ringwald     config_options[pos++] = 9;      // length
497fcb125edSMatthias Ringwald     config_options[pos++] = (uint8_t) channel->mode;
4987cbe539fSMatthias Ringwald     // less or equal to remote tx window size
499fcb125edSMatthias Ringwald     config_options[pos++] = btstack_min(channel->num_tx_buffers, channel->remote_tx_window_size);
5007cbe539fSMatthias Ringwald     // max transmit in response shall be ignored -> use sender values
501fcb125edSMatthias Ringwald     config_options[pos++] = channel->remote_max_transmit;
5027cbe539fSMatthias Ringwald     // A value for the Retransmission time-out shall be sent in a positive Configuration Response
5037cbe539fSMatthias Ringwald     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
504fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
505fcb125edSMatthias Ringwald     pos += 2;
5067cbe539fSMatthias Ringwald     // A value for the Monitor time-out shall be sent in a positive Configuration Response
5077cbe539fSMatthias Ringwald     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
508fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
509fcb125edSMatthias Ringwald     pos += 2;
5107cbe539fSMatthias Ringwald     // less or equal to remote mps
511b90eac91SMatthias Ringwald     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
512b90eac91SMatthias Ringwald     little_endian_store_16( config_options, pos, effective_mps);
513fcb125edSMatthias Ringwald     pos += 2;
5146574158aSMatthias Ringwald     //
515fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
516fcb125edSMatthias Ringwald     config_options[pos++] = 2;     // length
517fcb125edSMatthias Ringwald     little_endian_store_16(config_options, pos, channel->remote_mtu);
518fcb125edSMatthias Ringwald     pos += 2;
519fcb125edSMatthias Ringwald #if 0
520d64e9771SMatthias Ringwald     //
521fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
522fcb125edSMatthias Ringwald     config_options[pos++] = 1;     // length
523fcb125edSMatthias Ringwald     config_options[pos++] = channel->fcs_option;
524fcb125edSMatthias Ringwald #endif
525f2c70799Sandryblack     return pos; // 11+4=15
5267cbe539fSMatthias Ringwald }
5277cbe539fSMatthias Ringwald 
528474f5c3fSMatthias Ringwald static int l2cap_ertm_send_supervisor_frame(l2cap_channel_t * channel, uint16_t control){
529474f5c3fSMatthias Ringwald     hci_reserve_packet_buffer();
530474f5c3fSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
531474f5c3fSMatthias Ringwald     log_info("S-Frame: control 0x%04x", control);
532474f5c3fSMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
533474f5c3fSMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2);
534474f5c3fSMatthias Ringwald }
535474f5c3fSMatthias Ringwald 
5365774a392SMatthias Ringwald static uint8_t l2cap_ertm_validate_local_config(l2cap_ertm_config_t * ertm_config){
537474f5c3fSMatthias Ringwald 
538474f5c3fSMatthias Ringwald     uint8_t result = ERROR_CODE_SUCCESS;
5399c0e62d3SMatthias Ringwald     if (ertm_config->max_transmit < 1){
540474f5c3fSMatthias Ringwald         log_error("max_transmit must be >= 1");
541474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
542474f5c3fSMatthias Ringwald     }
5439c0e62d3SMatthias Ringwald     if (ertm_config->retransmission_timeout_ms < 2000){
544474f5c3fSMatthias Ringwald         log_error("retransmission_timeout_ms must be >= 2000 ms");
545474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
546474f5c3fSMatthias Ringwald     }
5479c0e62d3SMatthias Ringwald     if (ertm_config->monitor_timeout_ms < 12000){
548474f5c3fSMatthias Ringwald         log_error("monitor_timeout_ms must be >= 12000 ms");
549474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
550474f5c3fSMatthias Ringwald     }
5519c0e62d3SMatthias Ringwald     if (ertm_config->local_mtu < 48){
552474f5c3fSMatthias Ringwald         log_error("local_mtu must be >= 48");
553474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
554474f5c3fSMatthias Ringwald     }
5559c0e62d3SMatthias Ringwald     if (ertm_config->num_rx_buffers < 1){
556474f5c3fSMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
557474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
558474f5c3fSMatthias Ringwald     }
5599c0e62d3SMatthias Ringwald     if (ertm_config->num_tx_buffers < 1){
560474f5c3fSMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
561474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
562474f5c3fSMatthias Ringwald     }
563474f5c3fSMatthias Ringwald     return result;
564474f5c3fSMatthias Ringwald }
565474f5c3fSMatthias Ringwald 
5669c0e62d3SMatthias Ringwald static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
567474f5c3fSMatthias Ringwald 
568474f5c3fSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
5699c0e62d3SMatthias Ringwald     channel->ertm_mandatory = ertm_config->ertm_mandatory;
5709c0e62d3SMatthias Ringwald     channel->local_max_transmit = ertm_config->max_transmit;
5719c0e62d3SMatthias Ringwald     channel->local_retransmission_timeout_ms = ertm_config->retransmission_timeout_ms;
5729c0e62d3SMatthias Ringwald     channel->local_monitor_timeout_ms = ertm_config->monitor_timeout_ms;
5739c0e62d3SMatthias Ringwald     channel->local_mtu = ertm_config->local_mtu;
5749c0e62d3SMatthias Ringwald     channel->num_rx_buffers = ertm_config->num_rx_buffers;
5759c0e62d3SMatthias Ringwald     channel->num_tx_buffers = ertm_config->num_tx_buffers;
576474f5c3fSMatthias Ringwald 
577c342091bSMatthias Ringwald     // align buffer to 16-byte boundary to assert l2cap_ertm_rx_packet_state_t is aligned
578474f5c3fSMatthias Ringwald     int bytes_till_alignment = 16 - (((uintptr_t) buffer) & 0x0f);
579474f5c3fSMatthias Ringwald     buffer += bytes_till_alignment;
580474f5c3fSMatthias Ringwald     size   -= bytes_till_alignment;
581474f5c3fSMatthias Ringwald 
582c342091bSMatthias Ringwald     // setup state buffers - use void cast to avoid -Wcast-align warning
583474f5c3fSMatthias Ringwald     uint32_t pos = 0;
584c342091bSMatthias Ringwald     channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) (void *) &buffer[pos];
5859c0e62d3SMatthias Ringwald     pos += ertm_config->num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
586c342091bSMatthias Ringwald     channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) (void *) &buffer[pos];
5879c0e62d3SMatthias Ringwald     pos += ertm_config->num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
588474f5c3fSMatthias Ringwald 
589474f5c3fSMatthias Ringwald     // setup reassembly buffer
590474f5c3fSMatthias Ringwald     channel->reassembly_buffer = &buffer[pos];
5919c0e62d3SMatthias Ringwald     pos += ertm_config->local_mtu;
592474f5c3fSMatthias Ringwald 
593474f5c3fSMatthias Ringwald     // divide rest of data equally
5949c0e62d3SMatthias Ringwald     channel->local_mps = (size - pos) / (ertm_config->num_rx_buffers + ertm_config->num_tx_buffers);
5950d3ee2efSMatthias Ringwald     log_info("Local MPS: %u", channel->local_mps);
596474f5c3fSMatthias Ringwald     channel->rx_packets_data = &buffer[pos];
5970d3ee2efSMatthias Ringwald     pos += ertm_config->num_rx_buffers * channel->local_mps;
598474f5c3fSMatthias Ringwald     channel->tx_packets_data = &buffer[pos];
5996574158aSMatthias Ringwald 
600c425ea4aSMatthias Ringwald     channel->fcs_option = ertm_config->fcs_option;
601474f5c3fSMatthias Ringwald }
602474f5c3fSMatthias Ringwald 
603474f5c3fSMatthias Ringwald uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
6049c0e62d3SMatthias Ringwald     l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
605474f5c3fSMatthias Ringwald 
6069c0e62d3SMatthias 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);
607474f5c3fSMatthias Ringwald 
608474f5c3fSMatthias Ringwald     // validate local config
6095774a392SMatthias Ringwald     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
610474f5c3fSMatthias Ringwald     if (result) return result;
611474f5c3fSMatthias Ringwald 
612f16129ceSMatthias 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);
613474f5c3fSMatthias Ringwald     if (!channel) {
614474f5c3fSMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
615474f5c3fSMatthias Ringwald     }
616474f5c3fSMatthias Ringwald 
617474f5c3fSMatthias Ringwald     // configure ERTM
6189c0e62d3SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
619474f5c3fSMatthias Ringwald 
620474f5c3fSMatthias Ringwald     // add to connections list
621474f5c3fSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
622474f5c3fSMatthias Ringwald 
623474f5c3fSMatthias Ringwald     // store local_cid
624474f5c3fSMatthias Ringwald     if (out_local_cid){
625474f5c3fSMatthias Ringwald        *out_local_cid = channel->local_cid;
626474f5c3fSMatthias Ringwald     }
627474f5c3fSMatthias Ringwald 
628474f5c3fSMatthias Ringwald     // check if hci connection is already usable
629f16129ceSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
630474f5c3fSMatthias Ringwald     if (conn){
631474f5c3fSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
632474f5c3fSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
633474f5c3fSMatthias Ringwald         // check if remote supported fearures are already received
634474f5c3fSMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
635474f5c3fSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
636474f5c3fSMatthias Ringwald         }
637474f5c3fSMatthias Ringwald     }
638474f5c3fSMatthias Ringwald 
639474f5c3fSMatthias Ringwald     l2cap_run();
640474f5c3fSMatthias Ringwald 
641474f5c3fSMatthias Ringwald     return 0;
642474f5c3fSMatthias Ringwald }
643474f5c3fSMatthias Ringwald 
644474f5c3fSMatthias Ringwald static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel){
645474f5c3fSMatthias Ringwald     if (l2cap_ertm_can_store_packet_now(channel)){
646474f5c3fSMatthias Ringwald         channel->waiting_for_can_send_now = 0;
647474f5c3fSMatthias Ringwald         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
648474f5c3fSMatthias Ringwald     }
649474f5c3fSMatthias Ringwald }
650474f5c3fSMatthias Ringwald 
6519c0e62d3SMatthias Ringwald uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
652474f5c3fSMatthias Ringwald 
653474f5c3fSMatthias Ringwald     log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
654f68b21d7SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
655474f5c3fSMatthias Ringwald     if (!channel) {
656474f5c3fSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
657474f5c3fSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
658474f5c3fSMatthias Ringwald     }
659474f5c3fSMatthias Ringwald 
660474f5c3fSMatthias Ringwald     // validate local config
6615774a392SMatthias Ringwald     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
662474f5c3fSMatthias Ringwald     if (result) return result;
663474f5c3fSMatthias Ringwald 
664474f5c3fSMatthias Ringwald     // configure L2CAP ERTM
6659c0e62d3SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
666474f5c3fSMatthias Ringwald 
667836ae835SMatthias Ringwald     // default: continue
668474f5c3fSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
669474f5c3fSMatthias Ringwald 
6708b7155e0SMatthias Ringwald     // verify remote ERTM support
671836ae835SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
672836ae835SMatthias Ringwald     if (connection == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
673836ae835SMatthias Ringwald 
674836ae835SMatthias Ringwald     if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
6758b7155e0SMatthias Ringwald         // ERTM not possible, select basic mode and release buffer
6768b7155e0SMatthias Ringwald         channel->mode = L2CAP_CHANNEL_MODE_BASIC;
6778b7155e0SMatthias Ringwald         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
678836ae835SMatthias Ringwald 
6798b7155e0SMatthias Ringwald         // bail if ERTM is mandatory
680836ae835SMatthias Ringwald         if (channel->ertm_mandatory){
681836ae835SMatthias Ringwald             // We chose 'no resources available' for "ERTM mandatory but you don't even know ERTM exists"
6828b7155e0SMatthias Ringwald             log_info("ERTM mandatory -> reject connection");
683836ae835SMatthias Ringwald             channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
684836ae835SMatthias Ringwald             channel->reason = 0x04; // no resources available
6858b7155e0SMatthias Ringwald         }  else {
6868b7155e0SMatthias Ringwald             log_info("ERTM not supported by remote -> use Basic mode");
687836ae835SMatthias Ringwald         }
688836ae835SMatthias Ringwald     }
689836ae835SMatthias Ringwald 
690474f5c3fSMatthias Ringwald     // process
691474f5c3fSMatthias Ringwald     l2cap_run();
692474f5c3fSMatthias Ringwald 
693474f5c3fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
694474f5c3fSMatthias Ringwald }
695474f5c3fSMatthias Ringwald 
696474f5c3fSMatthias Ringwald uint8_t l2cap_ertm_set_busy(uint16_t local_cid){
697f68b21d7SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
698474f5c3fSMatthias Ringwald     if (!channel) {
699474f5c3fSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
700474f5c3fSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
701474f5c3fSMatthias Ringwald     }
702474f5c3fSMatthias Ringwald     if (!channel->local_busy){
703474f5c3fSMatthias Ringwald         channel->local_busy = 1;
704474f5c3fSMatthias Ringwald         channel->send_supervisor_frame_receiver_not_ready = 1;
705474f5c3fSMatthias Ringwald         l2cap_run();
706474f5c3fSMatthias Ringwald     }
707474f5c3fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
708474f5c3fSMatthias Ringwald }
709474f5c3fSMatthias Ringwald 
710474f5c3fSMatthias Ringwald uint8_t l2cap_ertm_set_ready(uint16_t local_cid){
711f68b21d7SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
712474f5c3fSMatthias Ringwald     if (!channel) {
713474f5c3fSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
714474f5c3fSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
715474f5c3fSMatthias Ringwald     }
716474f5c3fSMatthias Ringwald     if (channel->local_busy){
717474f5c3fSMatthias Ringwald         channel->local_busy = 0;
718474f5c3fSMatthias Ringwald         channel->send_supervisor_frame_receiver_ready_poll = 1;
719474f5c3fSMatthias Ringwald         l2cap_run();
720474f5c3fSMatthias Ringwald     }
721474f5c3fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
722474f5c3fSMatthias Ringwald }
723474f5c3fSMatthias Ringwald 
7241e1a46bbSMatthias Ringwald // Process-ReqSeq
7251e1a46bbSMatthias Ringwald static void l2cap_ertm_process_req_seq(l2cap_channel_t * l2cap_channel, uint8_t req_seq){
726474f5c3fSMatthias Ringwald     int num_buffers_acked = 0;
727474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
72894301352SMatthias 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);
729ff3cc4a5SMatthias Ringwald     while (true){
7301e1a46bbSMatthias Ringwald 
73194301352SMatthias Ringwald         // no unack packets left
73294301352SMatthias Ringwald         if (l2cap_channel->unacked_frames == 0) {
7331e1a46bbSMatthias Ringwald             // stop retransmission timer
7341e1a46bbSMatthias Ringwald             l2cap_ertm_stop_retransmission_timer(l2cap_channel);
7351e1a46bbSMatthias Ringwald             break;
7361e1a46bbSMatthias Ringwald         }
7371e1a46bbSMatthias Ringwald 
738474f5c3fSMatthias Ringwald         tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
739474f5c3fSMatthias Ringwald         // calc delta
740474f5c3fSMatthias Ringwald         int delta = (req_seq - tx_state->tx_seq) & 0x03f;
741474f5c3fSMatthias Ringwald         if (delta == 0) break;  // all packets acknowledged
742474f5c3fSMatthias Ringwald         if (delta > l2cap_channel->remote_tx_window_size) break;
743474f5c3fSMatthias Ringwald 
744474f5c3fSMatthias Ringwald         num_buffers_acked++;
745a8409e80SMatthias Ringwald         l2cap_channel->num_stored_tx_frames--;
74694301352SMatthias Ringwald         l2cap_channel->unacked_frames--;
747474f5c3fSMatthias Ringwald         log_info("RR seq %u => packet with tx_seq %u done", req_seq, tx_state->tx_seq);
748474f5c3fSMatthias Ringwald 
749474f5c3fSMatthias Ringwald         l2cap_channel->tx_read_index++;
750474f5c3fSMatthias Ringwald         if (l2cap_channel->tx_read_index >= l2cap_channel->num_rx_buffers){
751474f5c3fSMatthias Ringwald             l2cap_channel->tx_read_index = 0;
752474f5c3fSMatthias Ringwald         }
753474f5c3fSMatthias Ringwald     }
754474f5c3fSMatthias Ringwald     if (num_buffers_acked){
755a8409e80SMatthias Ringwald         log_info("num_buffers_acked %u", num_buffers_acked);
756474f5c3fSMatthias Ringwald     l2cap_ertm_notify_channel_can_send(l2cap_channel);
757474f5c3fSMatthias Ringwald }
758474f5c3fSMatthias Ringwald }
759474f5c3fSMatthias Ringwald 
760474f5c3fSMatthias Ringwald static l2cap_ertm_tx_packet_state_t * l2cap_ertm_get_tx_state(l2cap_channel_t * l2cap_channel, uint8_t tx_seq){
761474f5c3fSMatthias Ringwald     int i;
762474f5c3fSMatthias Ringwald     for (i=0;i<l2cap_channel->num_tx_buffers;i++){
763474f5c3fSMatthias Ringwald         l2cap_ertm_tx_packet_state_t * tx_state = &l2cap_channel->tx_packets_state[i];
764474f5c3fSMatthias Ringwald         if (tx_state->tx_seq == tx_seq) return tx_state;
765474f5c3fSMatthias Ringwald     }
766474f5c3fSMatthias Ringwald     return NULL;
767474f5c3fSMatthias Ringwald }
768474f5c3fSMatthias Ringwald 
769474f5c3fSMatthias Ringwald // @param delta number of frames in the future, >= 1
770122c2b05SMatthias Ringwald // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
7713d244bfaSMatthias 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){
772474f5c3fSMatthias Ringwald     log_info("Store SDU with delta %u", delta);
773474f5c3fSMatthias Ringwald     // get rx state for packet to store
774474f5c3fSMatthias Ringwald     int index = l2cap_channel->rx_store_index + delta - 1;
775474f5c3fSMatthias Ringwald     if (index > l2cap_channel->num_rx_buffers){
776474f5c3fSMatthias Ringwald         index -= l2cap_channel->num_rx_buffers;
777474f5c3fSMatthias Ringwald     }
778474f5c3fSMatthias Ringwald     log_info("Index of packet to store %u", index);
779474f5c3fSMatthias Ringwald     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
780474f5c3fSMatthias Ringwald     // check if buffer is free
781474f5c3fSMatthias Ringwald     if (rx_state->valid){
782474f5c3fSMatthias Ringwald         log_error("Packet buffer already used");
783474f5c3fSMatthias Ringwald         return;
784474f5c3fSMatthias Ringwald     }
785474f5c3fSMatthias Ringwald     rx_state->valid = 1;
786474f5c3fSMatthias Ringwald     rx_state->sar = sar;
787474f5c3fSMatthias Ringwald     rx_state->len = size;
788474f5c3fSMatthias Ringwald     uint8_t * rx_buffer = &l2cap_channel->rx_packets_data[index];
7896535961aSMatthias Ringwald     (void)memcpy(rx_buffer, payload, size);
790474f5c3fSMatthias Ringwald }
791474f5c3fSMatthias Ringwald 
792122c2b05SMatthias Ringwald // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
7933d244bfaSMatthias 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){
794122c2b05SMatthias Ringwald     uint16_t reassembly_sdu_length;
795474f5c3fSMatthias Ringwald     switch (sar){
796474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
797122c2b05SMatthias Ringwald             // assert total packet size <= our mtu
798122c2b05SMatthias Ringwald             if (size > l2cap_channel->local_mtu) break;
799474f5c3fSMatthias Ringwald             // packet complete -> disapatch
8003d244bfaSMatthias Ringwald             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, (uint8_t*) payload, size);
801474f5c3fSMatthias Ringwald             break;
802474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
803122c2b05SMatthias Ringwald             // read SDU len
804122c2b05SMatthias Ringwald             reassembly_sdu_length = little_endian_read_16(payload, 0);
805474f5c3fSMatthias Ringwald             payload += 2;
806474f5c3fSMatthias Ringwald             size    -= 2;
807122c2b05SMatthias Ringwald             // assert reassembled size <= our mtu
808122c2b05SMatthias Ringwald             if (reassembly_sdu_length > l2cap_channel->local_mtu) break;
809122c2b05SMatthias Ringwald             // store start segment
810122c2b05SMatthias Ringwald             l2cap_channel->reassembly_sdu_length = reassembly_sdu_length;
8116535961aSMatthias Ringwald             (void)memcpy(&l2cap_channel->reassembly_buffer[0], payload, size);
812474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos = size;
813474f5c3fSMatthias Ringwald             break;
814474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
815122c2b05SMatthias Ringwald             // assert size of reassembled data <= our mtu
816122c2b05SMatthias Ringwald             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
817122c2b05SMatthias Ringwald             // store continuation segment
8186535961aSMatthias Ringwald             (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
8196535961aSMatthias Ringwald                          payload, size);
820474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos += size;
821474f5c3fSMatthias Ringwald             break;
822474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
823122c2b05SMatthias Ringwald             // assert size of reassembled data <= our mtu
824122c2b05SMatthias Ringwald             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
825122c2b05SMatthias Ringwald             // store continuation segment
8266535961aSMatthias Ringwald             (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
8276535961aSMatthias Ringwald                          payload, size);
828474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos += size;
829122c2b05SMatthias Ringwald             // assert size of reassembled data matches announced sdu length
830122c2b05SMatthias Ringwald             if (l2cap_channel->reassembly_pos != l2cap_channel->reassembly_sdu_length) break;
831474f5c3fSMatthias Ringwald             // packet complete -> disapatch
832474f5c3fSMatthias Ringwald             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->reassembly_buffer, l2cap_channel->reassembly_pos);
833474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos = 0;
834474f5c3fSMatthias Ringwald             break;
835474f5c3fSMatthias Ringwald     }
836474f5c3fSMatthias Ringwald }
837474f5c3fSMatthias Ringwald 
838d89ab698SMatthias Ringwald static void l2cap_ertm_channel_send_information_frame(l2cap_channel_t * channel){
839d89ab698SMatthias Ringwald     channel->unacked_frames++;
840d89ab698SMatthias Ringwald     int index = channel->tx_send_index;
841d89ab698SMatthias Ringwald     channel->tx_send_index++;
842d89ab698SMatthias Ringwald     if (channel->tx_send_index >= channel->num_tx_buffers){
843d89ab698SMatthias Ringwald         channel->tx_send_index = 0;
844d89ab698SMatthias Ringwald     }
845d89ab698SMatthias Ringwald     l2cap_ertm_send_information_frame(channel, index, 0);   // final = 0
846d89ab698SMatthias Ringwald }
847d89ab698SMatthias Ringwald 
84885ddcd84SMatthias Ringwald #endif
84985ddcd84SMatthias Ringwald 
8506a5ffed8SMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
8516ddef68dSMilanka Ringwald static uint16_t l2cap_next_local_cid(void){
8526268fbfeSMilanka Ringwald     do {
8536268fbfeSMilanka Ringwald         if (local_source_cid == 0xffff) {
8546268fbfeSMilanka Ringwald             local_source_cid = 0x40;
8556268fbfeSMilanka Ringwald         } else {
8566268fbfeSMilanka Ringwald             local_source_cid++;
8576268fbfeSMilanka Ringwald         }
8586268fbfeSMilanka Ringwald     } while (l2cap_get_channel_for_local_cid(local_source_cid) != NULL);
8596268fbfeSMilanka Ringwald     return local_source_cid;
8606ddef68dSMilanka Ringwald }
8616a5ffed8SMatthias Ringwald #endif
8626ddef68dSMilanka Ringwald 
8636ddef68dSMilanka Ringwald static uint8_t l2cap_next_sig_id(void){
8646ddef68dSMilanka Ringwald     if (sig_seq_nr == 0xff) {
8656ddef68dSMilanka Ringwald         sig_seq_nr = 1;
8666ddef68dSMilanka Ringwald     } else {
8676ddef68dSMilanka Ringwald         sig_seq_nr++;
8686ddef68dSMilanka Ringwald     }
8696ddef68dSMilanka Ringwald     return sig_seq_nr;
8706ddef68dSMilanka Ringwald }
8716ddef68dSMilanka Ringwald 
87271de195eSMatthias Ringwald void l2cap_init(void){
8732b83fb7dSmatthias.ringwald     signaling_responses_pending = 0;
874808a48abSmatthias.ringwald 
875f5454fc6Smatthias.ringwald     l2cap_channels = NULL;
876fad84cafSMatthias Ringwald 
877fad84cafSMatthias Ringwald #ifdef ENABLE_CLASSIC
878f5454fc6Smatthias.ringwald     l2cap_services = NULL;
87909e9d05bSMatthias Ringwald     require_security_level2_for_outgoing_sdp = 0;
880fad84cafSMatthias Ringwald 
881fad84cafSMatthias Ringwald     // Setup Connectionless Channel
882fad84cafSMatthias Ringwald     l2cap_fixed_channel_connectionless.local_cid     = L2CAP_CID_CONNECTIONLESS_CHANNEL;
8837740e150SMatthias Ringwald     l2cap_fixed_channel_connectionless.channel_type  = L2CAP_CHANNEL_TYPE_CONNECTIONLESS;
884fad84cafSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_connectionless);
88509e9d05bSMatthias Ringwald #endif
886a3dc965aSMatthias Ringwald 
887a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
8887192e786SMatthias Ringwald     l2cap_le_services = NULL;
889a3dc965aSMatthias Ringwald #endif
890f5454fc6Smatthias.ringwald 
891d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
89233c40538SMatthias Ringwald     l2cap_event_packet_handler = NULL;
89325818320SMatthias Ringwald     l2cap_le_custom_max_mtu = 0;
894fad84cafSMatthias Ringwald 
895fad84cafSMatthias Ringwald     // Setup fixed ATT Channel
896fad84cafSMatthias Ringwald     l2cap_fixed_channel_att.local_cid    = L2CAP_CID_ATTRIBUTE_PROTOCOL;
8977740e150SMatthias Ringwald     l2cap_fixed_channel_att.channel_type = L2CAP_CHANNEL_TYPE_LE_FIXED;
898fad84cafSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_att);
899fad84cafSMatthias Ringwald 
900fad84cafSMatthias Ringwald     // Setup fixed SM Channel
901fad84cafSMatthias Ringwald     l2cap_fixed_channel_sm.local_cid     = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
9027740e150SMatthias Ringwald     l2cap_fixed_channel_sm.channel_type  = L2CAP_CHANNEL_TYPE_LE_FIXED;
903fad84cafSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_sm);
904d6ed9f9cSMatthias Ringwald #endif
905f5454fc6Smatthias.ringwald 
906fcadd0caSmatthias.ringwald     //
9072718e2e7Smatthias.ringwald     // register callback with HCI
908fcadd0caSmatthias.ringwald     //
909d9a7306aSMatthias Ringwald     hci_event_callback_registration.callback = &l2cap_hci_event_handler;
910fb37a842SMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
911fb37a842SMatthias Ringwald 
912d9a7306aSMatthias Ringwald     hci_register_acl_packet_handler(&l2cap_acl_handler);
913fb37a842SMatthias Ringwald 
914be005ed6SMatthias Ringwald #ifdef ENABLE_CLASSIC
91515a95bd5SMatthias Ringwald     gap_connectable_control(0); // no services yet
916be005ed6SMatthias Ringwald #endif
917fcadd0caSmatthias.ringwald }
918fcadd0caSmatthias.ringwald 
919ffbf8201SMatthias Ringwald void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
920d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
92133c40538SMatthias Ringwald     l2cap_event_packet_handler = handler;
922d6ed9f9cSMatthias Ringwald #else
9235774a392SMatthias Ringwald     UNUSED(handler);    // ok: no code
924d6ed9f9cSMatthias Ringwald #endif
9251e6aba47Smatthias.ringwald }
9261e6aba47Smatthias.ringwald 
92709e9d05bSMatthias Ringwald void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
928fad84cafSMatthias Ringwald     UNUSED(con_handle);  // ok: there is no con handle
9299ec2630cSMatthias Ringwald 
930f68b21d7SMatthias Ringwald     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
931fad84cafSMatthias Ringwald     if (!channel) return;
932fad84cafSMatthias Ringwald     channel->waiting_for_can_send_now = 1;
93309e9d05bSMatthias Ringwald     l2cap_notify_channel_can_send();
93409e9d05bSMatthias Ringwald }
93509e9d05bSMatthias Ringwald 
93609e9d05bSMatthias Ringwald int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
9375774a392SMatthias Ringwald     UNUSED(channel_id); // ok: only depends on Controller LE buffers
9389ec2630cSMatthias Ringwald 
93909e9d05bSMatthias Ringwald     return hci_can_send_acl_packet_now(con_handle);
94009e9d05bSMatthias Ringwald }
94109e9d05bSMatthias Ringwald 
94209e9d05bSMatthias Ringwald uint8_t *l2cap_get_outgoing_buffer(void){
94309e9d05bSMatthias Ringwald     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
94409e9d05bSMatthias Ringwald }
94509e9d05bSMatthias Ringwald 
9464e6fa3a2SMatthias Ringwald // only for L2CAP Basic Channels
94709e9d05bSMatthias Ringwald int l2cap_reserve_packet_buffer(void){
94809e9d05bSMatthias Ringwald     return hci_reserve_packet_buffer();
94909e9d05bSMatthias Ringwald }
95009e9d05bSMatthias Ringwald 
9514e6fa3a2SMatthias Ringwald // only for L2CAP Basic Channels
95209e9d05bSMatthias Ringwald void l2cap_release_packet_buffer(void){
95309e9d05bSMatthias Ringwald     hci_release_packet_buffer();
95409e9d05bSMatthias Ringwald }
95509e9d05bSMatthias Ringwald 
956f511cefaSMatthias 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){
95709e9d05bSMatthias Ringwald     // 0 - Connection handle : PB=pb : BC=00
958f511cefaSMatthias Ringwald     little_endian_store_16(acl_buffer, 0, con_handle | (packet_boundary << 12) | (0 << 14));
95909e9d05bSMatthias Ringwald     // 2 - ACL length
96009e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 2,  len + 4);
96109e9d05bSMatthias Ringwald     // 4 - L2CAP packet length
96209e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 4,  len + 0);
96309e9d05bSMatthias Ringwald     // 6 - L2CAP channel DEST
96409e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 6,  remote_cid);
96509e9d05bSMatthias Ringwald }
96609e9d05bSMatthias Ringwald 
967f511cefaSMatthias Ringwald // assumption - only on LE connections
96809e9d05bSMatthias Ringwald int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
96909e9d05bSMatthias Ringwald 
97009e9d05bSMatthias Ringwald     if (!hci_is_packet_buffer_reserved()){
97109e9d05bSMatthias Ringwald         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
97209e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
97309e9d05bSMatthias Ringwald     }
97409e9d05bSMatthias Ringwald 
97509e9d05bSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
97609e9d05bSMatthias Ringwald         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
97709e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
97809e9d05bSMatthias Ringwald     }
97909e9d05bSMatthias Ringwald 
98009e9d05bSMatthias Ringwald     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
98109e9d05bSMatthias Ringwald 
98209e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
983f511cefaSMatthias Ringwald     l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
98409e9d05bSMatthias Ringwald     // send
98509e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len+8);
98609e9d05bSMatthias Ringwald }
98709e9d05bSMatthias Ringwald 
988f511cefaSMatthias Ringwald // assumption - only on LE connections
98909e9d05bSMatthias Ringwald int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
99009e9d05bSMatthias Ringwald 
99109e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(con_handle)){
99209e9d05bSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", cid);
99309e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
99409e9d05bSMatthias Ringwald     }
99509e9d05bSMatthias Ringwald 
99609e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
99709e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
99809e9d05bSMatthias Ringwald 
9996535961aSMatthias Ringwald     (void)memcpy(&acl_buffer[8], data, len);
100009e9d05bSMatthias Ringwald 
100109e9d05bSMatthias Ringwald     return l2cap_send_prepared_connectionless(con_handle, cid, len);
100209e9d05bSMatthias Ringwald }
100309e9d05bSMatthias Ringwald 
100409e9d05bSMatthias Ringwald static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
1005d9d23054SMatthias Ringwald     log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
100609e9d05bSMatthias Ringwald     uint8_t event[4];
100709e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
100809e9d05bSMatthias Ringwald     event[1] = sizeof(event) - 2;
100909e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, channel);
101009e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
101109e9d05bSMatthias Ringwald     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
101209e9d05bSMatthias Ringwald }
101309e9d05bSMatthias Ringwald 
101409e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
101517a9b554SMatthias Ringwald static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
101658de5610Smatthias.ringwald     (* (channel->packet_handler))(type, channel->local_cid, data, size);
101758de5610Smatthias.ringwald }
101858de5610Smatthias.ringwald 
101944276248SMatthias Ringwald static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
102044276248SMatthias Ringwald     uint8_t event[4];
102144276248SMatthias Ringwald     event[0] = event_code;
102244276248SMatthias Ringwald     event[1] = sizeof(event) - 2;
102344276248SMatthias Ringwald     little_endian_store_16(event, 2, channel->local_cid);
102444276248SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
102544276248SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
102644276248SMatthias Ringwald }
102709e9d05bSMatthias Ringwald #endif
102844276248SMatthias Ringwald 
102909e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
103058de5610Smatthias.ringwald void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
1031c9dc710bS[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",
1032fc64f94aSMatthias Ringwald              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
1033c9dc710bS[email protected]              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
10347f1690cfSMatthias Ringwald     uint8_t event[26];
103558de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
103658de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
103758de5610Smatthias.ringwald     event[2] = status;
1038724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
1039fc64f94aSMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
1040f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
1041f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
1042f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
1043f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 17, channel->local_mtu);
1044f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 19, channel->remote_mtu);
1045f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 21, channel->flush_timeout);
1046c1ab6cc1SMatthias Ringwald     event[23] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
10477f1690cfSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
10487f1690cfSMatthias Ringwald     log_info("ERTM mode %u, fcs enabled %u", channel->mode, channel->fcs_option);
10497f1690cfSMatthias Ringwald     event[24] = channel->mode;
10507f1690cfSMatthias Ringwald     event[25] = channel->fcs_option;
10517f1690cfSMatthias Ringwald 
10527f1690cfSMatthias Ringwald #else
10537f1690cfSMatthias Ringwald     event[24] = L2CAP_CHANNEL_MODE_BASIC;
10547f1690cfSMatthias Ringwald     event[25] = 0;
10557f1690cfSMatthias Ringwald #endif
105658de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
105717a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
105858de5610Smatthias.ringwald }
105958de5610Smatthias.ringwald 
106044276248SMatthias Ringwald static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
1061e0abb8e7S[email protected]     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
106244276248SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
106358de5610Smatthias.ringwald }
106458de5610Smatthias.ringwald 
106544276248SMatthias Ringwald static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
1066e0abb8e7S[email protected]     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
1067fc64f94aSMatthias Ringwald              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
106858de5610Smatthias.ringwald     uint8_t event[16];
106958de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
107058de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
1071724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[2]);
1072fc64f94aSMatthias Ringwald     little_endian_store_16(event,  8, channel->con_handle);
1073f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 10, channel->psm);
1074f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 12, channel->local_cid);
1075f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 14, channel->remote_cid);
107658de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
107717a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
10780af41d30Smatthias.ringwald }
1079f62db1e3Smatthias.ringwald 
108066a72640SMatthias Ringwald static void l2cap_handle_channel_open_failed(l2cap_channel_t * channel, uint8_t status){
108166a72640SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
108266a72640SMatthias Ringwald     // emit ertm buffer released, as it's not needed. if in basic mode, it was either not allocated or already released
108366a72640SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
108466a72640SMatthias Ringwald         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
108566a72640SMatthias Ringwald     }
108666a72640SMatthias Ringwald #endif
1087624873c3SMatthias Ringwald     l2cap_emit_channel_opened(channel, status);
1088624873c3SMatthias Ringwald }
1089624873c3SMatthias Ringwald 
109066a72640SMatthias Ringwald static void l2cap_handle_channel_closed(l2cap_channel_t * channel){
109166a72640SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
109266a72640SMatthias Ringwald     // emit ertm buffer released, as it's not needed anymore. if in basic mode, it was either not allocated or already released
109366a72640SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
109466a72640SMatthias Ringwald         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
109566a72640SMatthias Ringwald     }
109666a72640SMatthias Ringwald #endif
109766a72640SMatthias Ringwald     l2cap_emit_channel_closed(channel);
109866a72640SMatthias Ringwald }
1099dd3bf36fSMatthias Ringwald #endif
1100dd3bf36fSMatthias Ringwald 
1101dd3bf36fSMatthias Ringwald static l2cap_fixed_channel_t * l2cap_channel_item_by_cid(uint16_t cid){
1102dd3bf36fSMatthias Ringwald     btstack_linked_list_iterator_t it;
1103dd3bf36fSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1104dd3bf36fSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1105dd3bf36fSMatthias Ringwald         l2cap_fixed_channel_t * channel = (l2cap_fixed_channel_t*) btstack_linked_list_iterator_next(&it);
1106dd3bf36fSMatthias Ringwald         if (channel->local_cid == cid) {
1107dd3bf36fSMatthias Ringwald             return channel;
1108dd3bf36fSMatthias Ringwald         }
1109dd3bf36fSMatthias Ringwald     }
1110dd3bf36fSMatthias Ringwald     return NULL;
1111dd3bf36fSMatthias Ringwald }
111266a72640SMatthias Ringwald 
1113fad84cafSMatthias Ringwald // used for fixed channels in LE (ATT/SM) and Classic (Connectionless Channel). CID < 0x04
1114fad84cafSMatthias Ringwald static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid){
1115fad84cafSMatthias Ringwald     if (local_cid >= 0x40) return NULL;
1116fad84cafSMatthias Ringwald     return (l2cap_fixed_channel_t*) l2cap_channel_item_by_cid(local_cid);
1117fad84cafSMatthias Ringwald }
111824eb964eSMatthias Ringwald 
111924eb964eSMatthias Ringwald // used for Classic Channels + LE Data Channels. local_cid >= 0x40
112024eb964eSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
112124eb964eSMatthias Ringwald static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
112224eb964eSMatthias Ringwald     if (local_cid < 0x40) return NULL;
112324eb964eSMatthias Ringwald     return (l2cap_channel_t*) l2cap_channel_item_by_cid(local_cid);
112424eb964eSMatthias Ringwald }
11250b9d7e78SMatthias Ringwald 
112630725612SMatthias Ringwald void l2cap_request_can_send_now_event(uint16_t local_cid){
112730725612SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
112830725612SMatthias Ringwald     if (!channel) return;
112930725612SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
113096646001SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
113196646001SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
113296646001SMatthias Ringwald         l2cap_ertm_notify_channel_can_send(channel);
113396646001SMatthias Ringwald         return;
113496646001SMatthias Ringwald     }
113596646001SMatthias Ringwald #endif
113630725612SMatthias Ringwald     l2cap_notify_channel_can_send();
113730725612SMatthias Ringwald }
113830725612SMatthias Ringwald 
113996646001SMatthias Ringwald int  l2cap_can_send_packet_now(uint16_t local_cid){
114096646001SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
114196646001SMatthias Ringwald     if (!channel) return 0;
114296646001SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
114396646001SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
114496646001SMatthias Ringwald         return l2cap_ertm_can_store_packet_now(channel);
114596646001SMatthias Ringwald     }
114696646001SMatthias Ringwald #endif
11470b9d7e78SMatthias Ringwald     return hci_can_send_acl_packet_now(channel->con_handle);
11487856fb31S[email protected] }
11497856fb31S[email protected] 
115083e7cdd9SMatthias Ringwald int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
115183e7cdd9SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
115283e7cdd9SMatthias Ringwald     if (!channel) return 0;
11530b20b13bSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
11540b20b13bSMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
11550b20b13bSMatthias Ringwald         return 0;
11560b20b13bSMatthias Ringwald     }
11570b20b13bSMatthias Ringwald #endif
11580b9d7e78SMatthias Ringwald     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
115983e7cdd9SMatthias Ringwald }
11600b20b13bSMatthias Ringwald 
116196cbd662Smatthias.ringwald uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
116296cbd662Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
116396cbd662Smatthias.ringwald     if (channel) {
116496cbd662Smatthias.ringwald         return channel->remote_mtu;
116596cbd662Smatthias.ringwald     }
116696cbd662Smatthias.ringwald     return 0;
116796cbd662Smatthias.ringwald }
116824eb964eSMatthias Ringwald #endif
116996cbd662Smatthias.ringwald 
117024eb964eSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
1171fad84cafSMatthias Ringwald static int l2cap_is_dynamic_channel_type(l2cap_channel_type_t channel_type){
1172fad84cafSMatthias Ringwald     switch (channel_type){
1173fad84cafSMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CLASSIC:
1174fad84cafSMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
1175fad84cafSMatthias Ringwald             return 1;
1176fad84cafSMatthias Ringwald         default:
1177fad84cafSMatthias Ringwald             return 0;
1178fad84cafSMatthias Ringwald     }
1179fad84cafSMatthias Ringwald }
118024eb964eSMatthias Ringwald #endif
1181fad84cafSMatthias Ringwald 
118224eb964eSMatthias Ringwald #ifdef ENABLE_CLASSIC
1183fad84cafSMatthias Ringwald // RTX Timer only exist for dynamic channels
1184ec820d77SMatthias Ringwald static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
1185665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1186665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1187665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1188665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1189fad84cafSMatthias Ringwald         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
11905932bd7cS[email protected]         if (&channel->rtx == ts) {
11915932bd7cS[email protected]             return channel;
11925932bd7cS[email protected]         }
11935932bd7cS[email protected]     }
11945932bd7cS[email protected]     return NULL;
11955932bd7cS[email protected] }
11965932bd7cS[email protected] 
1197ec820d77SMatthias Ringwald static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
11985932bd7cS[email protected]     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
119995d2c8f4SMatthias Ringwald     if (!channel) return;
12005932bd7cS[email protected] 
12015932bd7cS[email protected]     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
12025932bd7cS[email protected] 
12035932bd7cS[email protected]     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
12045932bd7cS[email protected]     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
12055932bd7cS[email protected]     // notify client
120666a72640SMatthias Ringwald     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
12075932bd7cS[email protected] 
12085932bd7cS[email protected]     // discard channel
1209665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1210c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
12115932bd7cS[email protected] }
12125932bd7cS[email protected] 
121313aa3e4bSMatthias Ringwald #endif
121413aa3e4bSMatthias Ringwald 
121513aa3e4bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
12165932bd7cS[email protected] static void l2cap_stop_rtx(l2cap_channel_t * channel){
12175932bd7cS[email protected]     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
1218528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->rtx);
12195932bd7cS[email protected] }
122013aa3e4bSMatthias Ringwald #endif
122113aa3e4bSMatthias Ringwald 
122213aa3e4bSMatthias Ringwald #ifdef ENABLE_CLASSIC
12235932bd7cS[email protected] 
12245932bd7cS[email protected] static void l2cap_start_rtx(l2cap_channel_t * channel){
12255932bd7cS[email protected]     l2cap_stop_rtx(channel);
1226cb0ff06bS[email protected]     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
1227528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1228528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
1229528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
12305932bd7cS[email protected] }
12315932bd7cS[email protected] 
12325932bd7cS[email protected] static void l2cap_start_ertx(l2cap_channel_t * channel){
12335932bd7cS[email protected]     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
12345932bd7cS[email protected]     l2cap_stop_rtx(channel);
1235528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1236528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
1237528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
12385932bd7cS[email protected] }
12395932bd7cS[email protected] 
124071de195eSMatthias Ringwald void l2cap_require_security_level_2_for_outgoing_sdp(void){
1241ac301f95S[email protected]     require_security_level2_for_outgoing_sdp = 1;
1242ac301f95S[email protected] }
1243ac301f95S[email protected] 
1244df3354fcS[email protected] static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
124584e3541eSMilanka Ringwald     return (psm == BLUETOOTH_PSM_SDP) && (!require_security_level2_for_outgoing_sdp);
1246df3354fcS[email protected] }
12475932bd7cS[email protected] 
124863854e74SMatthias Ringwald static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1249a35252c8S[email protected]     if (!hci_can_send_acl_packet_now(handle)){
12509da54300S[email protected]         log_info("l2cap_send_signaling_packet, cannot send");
1251b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
1252b1d43497Smatthias.ringwald     }
1253b1d43497Smatthias.ringwald 
12549da54300S[email protected]     // log_info("l2cap_send_signaling_packet type %u", cmd);
12552a373862S[email protected]     hci_reserve_packet_buffer();
1256facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
125758de5610Smatthias.ringwald     va_list argptr;
125858de5610Smatthias.ringwald     va_start(argptr, identifier);
125970efece1S[email protected]     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
126058de5610Smatthias.ringwald     va_end(argptr);
12619da54300S[email protected]     // log_info("l2cap_send_signaling_packet con %u!", handle);
1262826f7347S[email protected]     return hci_send_acl_packet_buffer(len);
126358de5610Smatthias.ringwald }
126458de5610Smatthias.ringwald 
1265f511cefaSMatthias Ringwald // assumption - only on Classic connections
12664e6fa3a2SMatthias Ringwald // cannot be used for L2CAP ERTM
1267b1d43497Smatthias.ringwald int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
1268b1d43497Smatthias.ringwald 
1269c8b9416aS[email protected]     if (!hci_is_packet_buffer_reserved()){
1270c8b9416aS[email protected]         log_error("l2cap_send_prepared called without reserving packet first");
1271c8b9416aS[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
1272c8b9416aS[email protected]     }
1273c8b9416aS[email protected] 
127458de5610Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1275b1d43497Smatthias.ringwald     if (!channel) {
12769da54300S[email protected]         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
1277b1d43497Smatthias.ringwald         return -1;   // TODO: define error
12786218e6f1Smatthias.ringwald     }
12796218e6f1Smatthias.ringwald 
1280fc64f94aSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
12819da54300S[email protected]         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
1282a35252c8S[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
1283a35252c8S[email protected]     }
1284a35252c8S[email protected] 
1285fc64f94aSMatthias Ringwald     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
1286b1d43497Smatthias.ringwald 
128785ddcd84SMatthias Ringwald     int fcs_size = 0;
128885ddcd84SMatthias Ringwald 
128985ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
12906574158aSMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->fcs_option){
129185ddcd84SMatthias Ringwald         fcs_size = 2;
129285ddcd84SMatthias Ringwald     }
129385ddcd84SMatthias Ringwald #endif
129485ddcd84SMatthias Ringwald 
1295f511cefaSMatthias Ringwald     // set non-flushable packet boundary flag if supported on Controller
1296facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1297f511cefaSMatthias Ringwald     uint8_t packet_boundary_flag = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
129885ddcd84SMatthias Ringwald     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
129985ddcd84SMatthias Ringwald 
130085ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1301b72f6906SMatthias Ringwald     if (fcs_size){
130285ddcd84SMatthias Ringwald         // calculate FCS over l2cap data
130385ddcd84SMatthias Ringwald         uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
130485ddcd84SMatthias Ringwald         log_info("I-Frame: fcs 0x%04x", fcs);
130585ddcd84SMatthias Ringwald         little_endian_store_16(acl_buffer, 8 + len, fcs);
130658de5610Smatthias.ringwald     }
130785ddcd84SMatthias Ringwald #endif
130885ddcd84SMatthias Ringwald 
130985ddcd84SMatthias Ringwald     // send
131085ddcd84SMatthias Ringwald     return hci_send_acl_packet_buffer(len+8+fcs_size);
131185ddcd84SMatthias Ringwald }
131285ddcd84SMatthias Ringwald 
1313f511cefaSMatthias Ringwald // assumption - only on Classic connections
1314ce8f182eSMatthias Ringwald int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
1315a35252c8S[email protected]     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1316a35252c8S[email protected]     if (!channel) {
1317ce8f182eSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
1318a35252c8S[email protected]         return -1;   // TODO: define error
1319a35252c8S[email protected]     }
1320a35252c8S[email protected] 
1321f0fb4cd7SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1322f0fb4cd7SMatthias Ringwald     // send in ERTM
1323f0fb4cd7SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1324f0fb4cd7SMatthias Ringwald         return l2cap_ertm_send(channel, data, len);
1325f0fb4cd7SMatthias Ringwald     }
1326f0fb4cd7SMatthias Ringwald #endif
1327f0fb4cd7SMatthias Ringwald 
1328f0efaa57S[email protected]     if (len > channel->remote_mtu){
1329ce8f182eSMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
1330f0efaa57S[email protected]         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
1331f0efaa57S[email protected]     }
1332f0efaa57S[email protected] 
1333fc64f94aSMatthias Ringwald     if (!hci_can_send_acl_packet_now(channel->con_handle)){
1334ce8f182eSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
1335b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
1336b1d43497Smatthias.ringwald     }
1337b1d43497Smatthias.ringwald 
13382a373862S[email protected]     hci_reserve_packet_buffer();
1339facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
13406535961aSMatthias Ringwald     (void)memcpy(&acl_buffer[8], data, len);
1341f0fb4cd7SMatthias Ringwald     return l2cap_send_prepared(local_cid, len);
1342b1d43497Smatthias.ringwald }
1343b1d43497Smatthias.ringwald 
1344fc64f94aSMatthias Ringwald int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
1345fc64f94aSMatthias Ringwald     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
13460e37e417S[email protected] }
13470e37e417S[email protected] 
134828ca2b46S[email protected] static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
134928ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
135028ca2b46S[email protected] }
135128ca2b46S[email protected] 
135228ca2b46S[email protected] static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
135328ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
135428ca2b46S[email protected] }
135509e9d05bSMatthias Ringwald #endif
135628ca2b46S[email protected] 
135728ca2b46S[email protected] 
135809e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
135963854e74SMatthias Ringwald static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
136009e9d05bSMatthias Ringwald 
136109e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(handle)){
136209e9d05bSMatthias Ringwald         log_info("l2cap_send_le_signaling_packet, cannot send");
136309e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
136409e9d05bSMatthias Ringwald     }
136509e9d05bSMatthias Ringwald 
136609e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
136709e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
136809e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
136909e9d05bSMatthias Ringwald     va_list argptr;
137009e9d05bSMatthias Ringwald     va_start(argptr, identifier);
137109e9d05bSMatthias Ringwald     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
137209e9d05bSMatthias Ringwald     va_end(argptr);
137309e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
137409e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len);
137509e9d05bSMatthias Ringwald }
137609e9d05bSMatthias Ringwald #endif
137709e9d05bSMatthias Ringwald 
137809e9d05bSMatthias Ringwald uint16_t l2cap_max_mtu(void){
137909e9d05bSMatthias Ringwald     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
138009e9d05bSMatthias Ringwald }
138109e9d05bSMatthias Ringwald 
13823e329ddfSandryblack #ifdef ENABLE_BLE
138309e9d05bSMatthias Ringwald uint16_t l2cap_max_le_mtu(void){
138425818320SMatthias Ringwald     if (l2cap_le_custom_max_mtu != 0) return l2cap_le_custom_max_mtu;
138509e9d05bSMatthias Ringwald     return l2cap_max_mtu();
138609e9d05bSMatthias Ringwald }
1387b1d43497Smatthias.ringwald 
138825818320SMatthias Ringwald void l2cap_set_max_le_mtu(uint16_t max_mtu){
138925818320SMatthias Ringwald     if (max_mtu < l2cap_max_mtu()){
139025818320SMatthias Ringwald         l2cap_le_custom_max_mtu = max_mtu;
139125818320SMatthias Ringwald     }
139225818320SMatthias Ringwald }
13933e329ddfSandryblack #endif
139425818320SMatthias Ringwald 
1395d2afdd38SMatthias Ringwald #ifdef ENABLE_CLASSIC
1396d2afdd38SMatthias Ringwald 
13976b99230fSMatthias Ringwald static uint16_t l2cap_setup_options_mtu(uint8_t * config_options, uint16_t mtu){
1398d64e9771SMatthias Ringwald     config_options[0] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
1399d2afdd38SMatthias Ringwald     config_options[1] = 2; // len param
14006b99230fSMatthias Ringwald     little_endian_store_16(config_options, 2, mtu);
1401d2afdd38SMatthias Ringwald     return 4;
1402d2afdd38SMatthias Ringwald }
1403d2afdd38SMatthias Ringwald 
1404450ad7ecSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
14056b99230fSMatthias Ringwald static int l2cap_ertm_mode(l2cap_channel_t * channel){
1406450ad7ecSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
14076b99230fSMatthias Ringwald     return ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE)
14086b99230fSMatthias Ringwald         &&  (connection->l2cap_state.extended_feature_mask & 0x08));
1409450ad7ecSMatthias Ringwald }
1410450ad7ecSMatthias Ringwald #endif
14116b99230fSMatthias Ringwald 
14126b99230fSMatthias Ringwald static uint16_t l2cap_setup_options_request(l2cap_channel_t * channel, uint8_t * config_options){
14136b99230fSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1414313d3a26SMatthias Ringwald     // use ERTM options if supported by remote and channel ready to use it
1415313d3a26SMatthias Ringwald     if (l2cap_ertm_mode(channel) && channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
14167cbe539fSMatthias Ringwald         return l2cap_setup_options_ertm_request(channel, config_options);
14176b99230fSMatthias Ringwald     }
14186b99230fSMatthias Ringwald #endif
14196b99230fSMatthias Ringwald     uint16_t mtu = channel->local_mtu;
14206b99230fSMatthias Ringwald     return l2cap_setup_options_mtu(config_options, mtu);
14216b99230fSMatthias Ringwald }
14226b99230fSMatthias Ringwald 
1423b8134563SMatthias Ringwald static uint16_t l2cap_setup_options_mtu_response(l2cap_channel_t * channel, uint8_t * config_options){
142432717978SMatthias Ringwald     uint16_t mtu = btstack_min(channel->local_mtu, channel->remote_mtu);
14256b99230fSMatthias Ringwald     return l2cap_setup_options_mtu(config_options, mtu);
14266dca2a0cSMatthias Ringwald }
14276dca2a0cSMatthias Ringwald 
14281b9cb13dSMatthias Ringwald static uint32_t l2cap_extended_features_mask(void){
14291b9cb13dSMatthias Ringwald     // extended features request supported, features: fixed channels, unicast connectionless data reception
14301b9cb13dSMatthias Ringwald     uint32_t features = 0x280;
14311b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
143254901195SMatthias Ringwald     features |= 0x0028;
14331b9cb13dSMatthias Ringwald #endif
14341b9cb13dSMatthias Ringwald     return features;
14351b9cb13dSMatthias Ringwald }
1436d2afdd38SMatthias Ringwald #endif
14371b9cb13dSMatthias Ringwald 
14383a600bd4SMatthias Ringwald //
1439b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
14403a600bd4SMatthias Ringwald static void l2cap_run_for_classic_channel(l2cap_channel_t * channel){
144109e9d05bSMatthias Ringwald 
1442f2c70799Sandryblack #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1443f2c70799Sandryblack     uint8_t  config_options[18];
1444f2c70799Sandryblack #else
144543ec931dSMatthias Ringwald     uint8_t  config_options[10];
1446f2c70799Sandryblack #endif
1447baf94f06S[email protected] 
14482cd0be45Smatthias.ringwald     switch (channel->state){
14492cd0be45Smatthias.ringwald 
1450df3354fcS[email protected]         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1451ad671560S[email protected]         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
1452fc64f94aSMatthias Ringwald             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1453a00031e2S[email protected]             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
1454ad671560S[email protected]                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
1455fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
1456ad671560S[email protected]             }
1457ad671560S[email protected]             break;
1458ad671560S[email protected] 
145902b22dc4Smatthias.ringwald         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1460baf94f06S[email protected]             if (!hci_can_send_command_packet_now()) break;
146164472d52Smatthias.ringwald             // send connection request - set state first
146264472d52Smatthias.ringwald             channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
146302b22dc4Smatthias.ringwald             // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
14646535961aSMatthias Ringwald             (void)memcpy(l2cap_outgoing_classic_addr, channel->address, 6);
1465b4eb4420SMatthias Ringwald             hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_get_allow_role_switch());
146602b22dc4Smatthias.ringwald             break;
146702b22dc4Smatthias.ringwald 
1468e7ff783cSmatthias.ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
1469fc64f94aSMatthias Ringwald             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
147022c29ab4SMatthias Ringwald             channel->state = L2CAP_STATE_INVALID;
1471fc64f94aSMatthias Ringwald             l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
1472e7ff783cSmatthias.ringwald             // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1473817374d9SMatthias Ringwald             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1474c45d6b2cSMatthias Ringwald             l2cap_free_channel_entry(channel);
147575e67d8aSMatthias Ringwald             channel = NULL;
1476e7ff783cSmatthias.ringwald             break;
1477e7ff783cSmatthias.ringwald 
1478552d92a1Smatthias.ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
1479fc64f94aSMatthias Ringwald             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1480fa8473a4Smatthias.ringwald             channel->state = L2CAP_STATE_CONFIG;
148128ca2b46S[email protected]             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1482fc64f94aSMatthias Ringwald             l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
1483552d92a1Smatthias.ringwald             break;
1484552d92a1Smatthias.ringwald 
14856fdcc387Smatthias.ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
1486fc64f94aSMatthias Ringwald             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
14876fdcc387Smatthias.ringwald             // success, start l2cap handshake
1488b1988dceSmatthias.ringwald             channel->local_sig_id = l2cap_next_sig_id();
14896fdcc387Smatthias.ringwald             channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
1490fc64f94aSMatthias Ringwald             l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
14915932bd7cS[email protected]             l2cap_start_rtx(channel);
14926fdcc387Smatthias.ringwald             break;
14936fdcc387Smatthias.ringwald 
1494fa8473a4Smatthias.ringwald         case L2CAP_STATE_CONFIG:
1495fc64f94aSMatthias Ringwald             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
149661c3f6deSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
149761c3f6deSMatthias Ringwald             // fallback to basic mode if ERTM requested but not not supported by remote
149861c3f6deSMatthias Ringwald             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
149961c3f6deSMatthias Ringwald                 if (!l2cap_ertm_mode(channel)){
150061c3f6deSMatthias Ringwald                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
150161c3f6deSMatthias Ringwald                     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
150261c3f6deSMatthias Ringwald                 }
150361c3f6deSMatthias Ringwald             }
150461c3f6deSMatthias Ringwald #endif
150573cf2b3dSmatthias.ringwald             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
150663a7246aSmatthias.ringwald                 uint16_t flags = 0;
150728ca2b46S[email protected]                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
150863a7246aSmatthias.ringwald                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
150963a7246aSmatthias.ringwald                     flags = 1;
151063a7246aSmatthias.ringwald                 } else {
151128ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
151263a7246aSmatthias.ringwald                 }
151363a7246aSmatthias.ringwald                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
1514ac8f1300SMatthias Ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1515fc64f94aSMatthias 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);
1516ac8f1300SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1517ac8f1300SMatthias Ringwald                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
1518ac8f1300SMatthias Ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1519ac8f1300SMatthias Ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1520b8134563SMatthias Ringwald                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1521ac8f1300SMatthias 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);
1522b8134563SMatthias Ringwald                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM){
1523b8134563SMatthias Ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
1524b8134563SMatthias Ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1525b8134563SMatthias Ringwald                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1526b8134563SMatthias 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);
1527ac8f1300SMatthias Ringwald #endif
1528ac8f1300SMatthias Ringwald                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
152963a7246aSmatthias.ringwald                     channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1530b8134563SMatthias Ringwald                     uint16_t options_size = l2cap_setup_options_mtu_response(channel, config_options);
1531ac8f1300SMatthias 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);
153263a7246aSmatthias.ringwald                 } else {
1533ac8f1300SMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
153463a7246aSmatthias.ringwald                 }
153563a7246aSmatthias.ringwald                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1536fa8473a4Smatthias.ringwald             }
153773cf2b3dSmatthias.ringwald             else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
153828ca2b46S[email protected]                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
153928ca2b46S[email protected]                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
1540b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
15416b99230fSMatthias Ringwald                 uint16_t options_size = l2cap_setup_options_request(channel, config_options);
15426dca2a0cSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options);
15435932bd7cS[email protected]                 l2cap_start_rtx(channel);
1544fa8473a4Smatthias.ringwald             }
1545fa8473a4Smatthias.ringwald             if (l2cap_channel_ready_for_open(channel)){
1546552d92a1Smatthias.ringwald                 channel->state = L2CAP_STATE_OPEN;
1547552d92a1Smatthias.ringwald                 l2cap_emit_channel_opened(channel, 0);  // success
1548fa8473a4Smatthias.ringwald             }
1549552d92a1Smatthias.ringwald             break;
1550552d92a1Smatthias.ringwald 
1551e7ff783cSmatthias.ringwald         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1552fc64f94aSMatthias Ringwald             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
155322c29ab4SMatthias Ringwald             channel->state = L2CAP_STATE_INVALID;
1554fc64f94aSMatthias Ringwald             l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
15555932bd7cS[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 :)
1556756102d3Smatthias.ringwald             l2cap_finialize_channel_close(channel);  // -- remove from list
155764cb054cSMatthias Ringwald             channel = NULL;
1558e7ff783cSmatthias.ringwald             break;
1559e7ff783cSmatthias.ringwald 
1560e7ff783cSmatthias.ringwald         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1561fc64f94aSMatthias Ringwald             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1562b1988dceSmatthias.ringwald             channel->local_sig_id = l2cap_next_sig_id();
15632cd0be45Smatthias.ringwald             channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1564fc64f94aSMatthias Ringwald             l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
15652cd0be45Smatthias.ringwald             break;
15662cd0be45Smatthias.ringwald         default:
15672cd0be45Smatthias.ringwald             break;
15682cd0be45Smatthias.ringwald     }
156938f62777SMatthias Ringwald 
157038f62777SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
157164cb054cSMatthias Ringwald 
157275e67d8aSMatthias Ringwald     // handle channel finalize on L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE and L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE
15733a600bd4SMatthias Ringwald     if (!channel) return;
15749700d53bSMilanka Ringwald 
15759700d53bSMilanka Ringwald     // ERTM mode
15763a600bd4SMatthias Ringwald     if (channel->mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) return;
15779700d53bSMilanka Ringwald 
15789700d53bSMilanka Ringwald     // check if we can still send
15793a600bd4SMatthias Ringwald     if (channel->con_handle == HCI_CON_HANDLE_INVALID) return;
15803a600bd4SMatthias Ringwald     if (!hci_can_send_acl_packet_now(channel->con_handle)) return;
1581675e6881SMatthias Ringwald 
1582d84e866fSMatthias Ringwald     if (channel->send_supervisor_frame_receiver_ready){
158378cd8a22SMatthias Ringwald         channel->send_supervisor_frame_receiver_ready = 0;
1584d2afdd38SMatthias Ringwald         log_info("Send S-Frame: RR %u, final %u", channel->req_seq, channel->set_final_bit_after_packet_with_poll_bit_set);
1585d2afdd38SMatthias 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);
1586d2afdd38SMatthias Ringwald         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
158738f62777SMatthias Ringwald         l2cap_ertm_send_supervisor_frame(channel, control);
15883a600bd4SMatthias Ringwald         return;
158938f62777SMatthias Ringwald     }
159062041d70SMatthias Ringwald     if (channel->send_supervisor_frame_receiver_ready_poll){
159178cd8a22SMatthias Ringwald         channel->send_supervisor_frame_receiver_ready_poll = 0;
159262041d70SMatthias Ringwald         log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
159362041d70SMatthias Ringwald         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
159462041d70SMatthias Ringwald         l2cap_ertm_send_supervisor_frame(channel, control);
15953a600bd4SMatthias Ringwald         return;
159662041d70SMatthias Ringwald     }
15978f1c9639SMatthias Ringwald     if (channel->send_supervisor_frame_receiver_not_ready){
159878cd8a22SMatthias Ringwald         channel->send_supervisor_frame_receiver_not_ready = 0;
15998f1c9639SMatthias Ringwald         log_info("Send S-Frame: RNR %u", channel->req_seq);
16008f1c9639SMatthias Ringwald         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
16018f1c9639SMatthias Ringwald         l2cap_ertm_send_supervisor_frame(channel, control);
16023a600bd4SMatthias Ringwald         return;
16038f1c9639SMatthias Ringwald     }
1604c7309e8dSMatthias Ringwald     if (channel->send_supervisor_frame_reject){
1605c7309e8dSMatthias Ringwald         channel->send_supervisor_frame_reject = 0;
1606c7309e8dSMatthias Ringwald         log_info("Send S-Frame: REJ %u", channel->req_seq);
1607c7309e8dSMatthias Ringwald         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 0, 0, channel->req_seq);
1608c7309e8dSMatthias Ringwald         l2cap_ertm_send_supervisor_frame(channel, control);
16093a600bd4SMatthias Ringwald         return;
1610c7309e8dSMatthias Ringwald     }
1611df2191a7SMatthias Ringwald     if (channel->send_supervisor_frame_selective_reject){
1612df2191a7SMatthias Ringwald         channel->send_supervisor_frame_selective_reject = 0;
1613df2191a7SMatthias Ringwald         log_info("Send S-Frame: SREJ %u", channel->expected_tx_seq);
1614f85ade6bSMatthias 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);
1615f85ade6bSMatthias Ringwald         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1616df2191a7SMatthias Ringwald         l2cap_ertm_send_supervisor_frame(channel, control);
16173a600bd4SMatthias Ringwald         return;
1618df2191a7SMatthias Ringwald     }
16197b7901d8SMatthias Ringwald 
16207b7901d8SMatthias Ringwald     if (channel->srej_active){
16217b7901d8SMatthias Ringwald         int i;
16227b7901d8SMatthias Ringwald         for (i=0;i<channel->num_tx_buffers;i++){
16237b7901d8SMatthias Ringwald             l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
16247b7901d8SMatthias Ringwald             if (tx_state->retransmission_requested) {
16257b7901d8SMatthias Ringwald                 tx_state->retransmission_requested = 0;
1626d2afdd38SMatthias Ringwald                 uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set;
1627d2afdd38SMatthias Ringwald                 channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1628d2afdd38SMatthias Ringwald                 l2cap_ertm_send_information_frame(channel, i, final);
16297b7901d8SMatthias Ringwald                 break;
16307b7901d8SMatthias Ringwald             }
16317b7901d8SMatthias Ringwald         }
16327b7901d8SMatthias Ringwald         if (i == channel->num_tx_buffers){
16337b7901d8SMatthias Ringwald             // no retransmission request found
16347b7901d8SMatthias Ringwald             channel->srej_active = 0;
16357b7901d8SMatthias Ringwald         } else {
16367b7901d8SMatthias Ringwald             // packet was sent
16373a600bd4SMatthias Ringwald             return;
16383a600bd4SMatthias Ringwald         }
16393a600bd4SMatthias Ringwald     }
16403a600bd4SMatthias Ringwald #endif
16413a600bd4SMatthias Ringwald }
16423a600bd4SMatthias Ringwald #endif
16433a600bd4SMatthias Ringwald 
1644*ea6a43faSMatthias Ringwald static void l2cap_run_signaling_response() {
16453a600bd4SMatthias Ringwald 
16463a600bd4SMatthias Ringwald     // check pending signaling responses
16473a600bd4SMatthias Ringwald     while (signaling_responses_pending){
16483a600bd4SMatthias Ringwald 
16493a600bd4SMatthias Ringwald         hci_con_handle_t handle = signaling_responses[0].handle;
16503a600bd4SMatthias Ringwald 
16513a600bd4SMatthias Ringwald         if (!hci_can_send_acl_packet_now(handle)) break;
16523a600bd4SMatthias Ringwald 
16533a600bd4SMatthias Ringwald         uint8_t  sig_id        = signaling_responses[0].sig_id;
16543a600bd4SMatthias Ringwald         uint8_t  response_code = signaling_responses[0].code;
16553a600bd4SMatthias Ringwald         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
16563a600bd4SMatthias Ringwald #ifdef ENABLE_CLASSIC
16573a600bd4SMatthias Ringwald         uint16_t info_type     = signaling_responses[0].data;  // INFORMATION_REQUEST
16583a600bd4SMatthias Ringwald         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
16593a600bd4SMatthias Ringwald #endif
16603a600bd4SMatthias Ringwald 
16613a600bd4SMatthias Ringwald         // remove first item before sending (to avoid sending response mutliple times)
16623a600bd4SMatthias Ringwald         signaling_responses_pending--;
16633a600bd4SMatthias Ringwald         int i;
16643a600bd4SMatthias Ringwald         for (i=0; i < signaling_responses_pending; i++){
16653a600bd4SMatthias Ringwald             (void)memcpy(&signaling_responses[i],
16663a600bd4SMatthias Ringwald                          &signaling_responses[i + 1],
16673a600bd4SMatthias Ringwald                          sizeof(l2cap_signaling_response_t));
16683a600bd4SMatthias Ringwald         }
16693a600bd4SMatthias Ringwald 
16703a600bd4SMatthias Ringwald         switch (response_code){
16713a600bd4SMatthias Ringwald #ifdef ENABLE_CLASSIC
16723a600bd4SMatthias Ringwald             case CONNECTION_REQUEST:
16733a600bd4SMatthias Ringwald                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
16743a600bd4SMatthias Ringwald                 // also disconnect if result is 0x0003 - security blocked
16753a600bd4SMatthias Ringwald                 if (result == 0x0003){
16763a600bd4SMatthias Ringwald                     hci_disconnect_security_block(handle);
16773a600bd4SMatthias Ringwald                 }
16783a600bd4SMatthias Ringwald                 break;
16793a600bd4SMatthias Ringwald             case ECHO_REQUEST:
16803a600bd4SMatthias Ringwald                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
16813a600bd4SMatthias Ringwald                 break;
16823a600bd4SMatthias Ringwald             case INFORMATION_REQUEST:
16833a600bd4SMatthias Ringwald                 switch (info_type){
16843a600bd4SMatthias Ringwald                     case L2CAP_INFO_TYPE_CONNECTIONLESS_MTU: {
16853a600bd4SMatthias Ringwald                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
16863a600bd4SMatthias Ringwald                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(connectionless_mtu), &connectionless_mtu);
16873a600bd4SMatthias Ringwald                         }
16883a600bd4SMatthias Ringwald                         break;
16893a600bd4SMatthias Ringwald                     case L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED: {
16903a600bd4SMatthias Ringwald                             uint32_t features = l2cap_extended_features_mask();
16913a600bd4SMatthias Ringwald                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(features), &features);
16923a600bd4SMatthias Ringwald                         }
16933a600bd4SMatthias Ringwald                         break;
16943a600bd4SMatthias Ringwald                     case L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED: {
16953a600bd4SMatthias Ringwald                             uint8_t map[8];
16963a600bd4SMatthias Ringwald                             memset(map, 0, 8);
16973a600bd4SMatthias Ringwald                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
16983a600bd4SMatthias Ringwald                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(map), &map);
16993a600bd4SMatthias Ringwald                         }
17003a600bd4SMatthias Ringwald                         break;
17013a600bd4SMatthias Ringwald                     default:
17023a600bd4SMatthias Ringwald                         // all other types are not supported
17033a600bd4SMatthias Ringwald                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 1, 0, NULL);
17043a600bd4SMatthias Ringwald                         break;
17053a600bd4SMatthias Ringwald                 }
17063a600bd4SMatthias Ringwald                 break;
17073a600bd4SMatthias Ringwald             case COMMAND_REJECT:
17083a600bd4SMatthias Ringwald                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
17093a600bd4SMatthias Ringwald                 break;
17103a600bd4SMatthias Ringwald #endif
17113a600bd4SMatthias Ringwald #ifdef ENABLE_BLE
17123a600bd4SMatthias Ringwald             case LE_CREDIT_BASED_CONNECTION_REQUEST:
17133a600bd4SMatthias Ringwald                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
17143a600bd4SMatthias Ringwald                 break;
17153a600bd4SMatthias Ringwald             case COMMAND_REJECT_LE:
17163a600bd4SMatthias Ringwald                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
17173a600bd4SMatthias Ringwald                 break;
17183a600bd4SMatthias Ringwald #endif
17193a600bd4SMatthias Ringwald             default:
17203a600bd4SMatthias Ringwald                 // should not happen
17213a600bd4SMatthias Ringwald                 break;
17223a600bd4SMatthias Ringwald         }
17233a600bd4SMatthias Ringwald     }
1724*ea6a43faSMatthias Ringwald }
17253a600bd4SMatthias Ringwald 
17263a600bd4SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1727*ea6a43faSMatthias Ringwald static bool l2ap_run_ertm(void){
17283a600bd4SMatthias Ringwald     // send l2cap information request if neccessary
1729*ea6a43faSMatthias Ringwald     btstack_linked_list_iterator_t it;
17303a600bd4SMatthias Ringwald     hci_connections_get_iterator(&it);
17313a600bd4SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
17323a600bd4SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
17333a600bd4SMatthias Ringwald         if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST){
17343a600bd4SMatthias Ringwald             if (!hci_can_send_acl_packet_now(connection->con_handle)) break;
17353a600bd4SMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
17363a600bd4SMatthias Ringwald             uint8_t sig_id = l2cap_next_sig_id();
17373a600bd4SMatthias Ringwald             uint8_t info_type = L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED;
17383a600bd4SMatthias Ringwald             l2cap_send_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
1739*ea6a43faSMatthias Ringwald             return true;
17407b7901d8SMatthias Ringwald         }
17417b7901d8SMatthias Ringwald     }
1742*ea6a43faSMatthias Ringwald     return false;
17432cd0be45Smatthias.ringwald }
174409e9d05bSMatthias Ringwald #endif
1745da886c03S[email protected] 
1746cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1747*ea6a43faSMatthias Ringwald static void l2cap_run_le_data_channels(void){
1748*ea6a43faSMatthias Ringwald     btstack_linked_list_iterator_t it;
1749421cb104SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1750efedfb4cSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1751b5803aafSMatthias Ringwald         uint16_t mps;
1752efedfb4cSMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1753421cb104SMatthias Ringwald 
1754421cb104SMatthias Ringwald         if (channel->channel_type != L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL) continue;
1755421cb104SMatthias Ringwald 
1756efedfb4cSMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1757efedfb4cSMatthias Ringwald         switch (channel->state){
17585cb87675SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
17595cb87675SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
17605cb87675SMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
17615cb87675SMatthias Ringwald                 // le psm, source cid, mtu, mps, initial credits
17621b8b8d05SMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
176363f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
176463f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
1765b5803aafSMatthias Ringwald                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
1766b5803aafSMatthias 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);
17675cb87675SMatthias Ringwald                 break;
176823017473SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
176923017473SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
177023017473SMatthias Ringwald                 // TODO: support larger MPS
177123017473SMatthias Ringwald                 channel->state = L2CAP_STATE_OPEN;
177263f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
177363f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
1774b5803aafSMatthias Ringwald                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
1775b5803aafSMatthias 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);
177664e11ca9SMatthias Ringwald                 // notify client
177744276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0);
177823017473SMatthias Ringwald                 break;
1779e7d0c9aaSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
1780e7d0c9aaSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1781e7d0c9aaSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
178263f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
1783e7d0c9aaSMatthias Ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1784e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1785c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
1786e7d0c9aaSMatthias Ringwald                 break;
17877f107edaSMatthias Ringwald             case L2CAP_STATE_OPEN:
178885aeef60SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
178985aeef60SMatthias Ringwald 
179085aeef60SMatthias Ringwald                 // send credits
179185aeef60SMatthias Ringwald                 if (channel->new_credits_incoming){
179285aeef60SMatthias Ringwald                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
179385aeef60SMatthias Ringwald                     channel->local_sig_id = l2cap_next_sig_id();
179485aeef60SMatthias Ringwald                     uint16_t new_credits = channel->new_credits_incoming;
179585aeef60SMatthias Ringwald                     channel->new_credits_incoming = 0;
179685aeef60SMatthias Ringwald                     channel->credits_incoming += new_credits;
179785aeef60SMatthias Ringwald                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
17986774d5c9SMatthias Ringwald                 }
179985aeef60SMatthias Ringwald                 break;
180085aeef60SMatthias Ringwald 
1801828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1802828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1803828a7f7aSMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
1804828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1805828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1806828a7f7aSMatthias Ringwald                 break;
1807828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1808828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1809828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1810828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1811828a7f7aSMatthias Ringwald                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
1812828a7f7aSMatthias Ringwald                 break;
1813efedfb4cSMatthias Ringwald             default:
1814efedfb4cSMatthias Ringwald                 break;
1815efedfb4cSMatthias Ringwald         }
1816efedfb4cSMatthias Ringwald     }
1817*ea6a43faSMatthias Ringwald }
1818*ea6a43faSMatthias Ringwald #endif
1819*ea6a43faSMatthias Ringwald 
1820*ea6a43faSMatthias Ringwald // MARK: L2CAP_RUN
1821*ea6a43faSMatthias Ringwald // process outstanding signaling tasks
1822*ea6a43faSMatthias Ringwald static void l2cap_run(void){
1823*ea6a43faSMatthias Ringwald 
1824*ea6a43faSMatthias Ringwald     // log_info("l2cap_run: entered");
1825*ea6a43faSMatthias Ringwald     l2cap_run_signaling_response();
1826*ea6a43faSMatthias Ringwald 
1827*ea6a43faSMatthias Ringwald     bool done;
1828*ea6a43faSMatthias Ringwald 
1829*ea6a43faSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1830*ea6a43faSMatthias Ringwald     done = l2ap_run_ertm();
1831*ea6a43faSMatthias Ringwald     if (done) return;
1832*ea6a43faSMatthias Ringwald #endif
1833*ea6a43faSMatthias Ringwald 
1834*ea6a43faSMatthias Ringwald #if defined(ENABLE_CLASSIC) || defined(ENABLE_BLE)
1835*ea6a43faSMatthias Ringwald     btstack_linked_list_iterator_t it;
1836*ea6a43faSMatthias Ringwald #endif
1837*ea6a43faSMatthias Ringwald 
1838*ea6a43faSMatthias Ringwald #ifdef ENABLE_CLASSIC
1839*ea6a43faSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1840*ea6a43faSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1841*ea6a43faSMatthias Ringwald 
1842*ea6a43faSMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1843*ea6a43faSMatthias Ringwald 
1844*ea6a43faSMatthias Ringwald         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CLASSIC) continue;
1845*ea6a43faSMatthias Ringwald 
1846*ea6a43faSMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1847*ea6a43faSMatthias Ringwald         l2cap_run_for_classic_channel(channel);
1848*ea6a43faSMatthias Ringwald     }
1849*ea6a43faSMatthias Ringwald #endif
1850*ea6a43faSMatthias Ringwald 
1851*ea6a43faSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1852*ea6a43faSMatthias Ringwald     l2cap_run_le_data_channels();
185309e9d05bSMatthias Ringwald     #endif
1854efedfb4cSMatthias Ringwald 
185509e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
1856da886c03S[email protected]     // send l2cap con paramter update if necessary
1857da886c03S[email protected]     hci_connections_get_iterator(&it);
1858665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
1859665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1860c1ab6cc1SMatthias Ringwald         if ((connection->address_type != BD_ADDR_TYPE_LE_PUBLIC) && (connection->address_type != BD_ADDR_TYPE_LE_RANDOM)) continue;
1861b68d7bc3SMatthias Ringwald         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
1862da886c03S[email protected]         switch (connection->le_con_parameter_update_state){
1863b68d7bc3SMatthias Ringwald             case CON_PARAMETER_UPDATE_SEND_REQUEST:
1864b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1865fe8aebe6SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, l2cap_next_sig_id(),
1866b68d7bc3SMatthias Ringwald                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
1867b68d7bc3SMatthias Ringwald                 break;
1868da886c03S[email protected]             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
1869b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
1870b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
1871da886c03S[email protected]                 break;
1872da886c03S[email protected]             case CON_PARAMETER_UPDATE_DENY:
1873b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1874b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
1875da886c03S[email protected]                 break;
1876da886c03S[email protected]             default:
1877da886c03S[email protected]                 break;
1878da886c03S[email protected]         }
1879da886c03S[email protected]     }
18804d7157c3S[email protected] #endif
1881da886c03S[email protected] 
188222c29ab4SMatthias Ringwald     // log_info("l2cap_run: exit");
18832cd0be45Smatthias.ringwald }
18842cd0be45Smatthias.ringwald 
188509e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1886fc64f94aSMatthias Ringwald static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
1887505f1c30SMatthias Ringwald     if ((channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE) || (channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION)) {
1888e5ac0afcSMatthias Ringwald         log_info("connection complete con_handle %04x - for channel %p cid 0x%04x", (int) con_handle, channel, channel->local_cid);
18892df5dadcS[email protected]         // success, start l2cap handshake
1890fc64f94aSMatthias Ringwald         channel->con_handle = con_handle;
18912df5dadcS[email protected]         // check remote SSP feature first
18922df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
18932df5dadcS[email protected]     }
18942df5dadcS[email protected] }
18952df5dadcS[email protected] 
18961b9cb13dSMatthias Ringwald static void l2cap_ready_to_connect(l2cap_channel_t * channel){
18971b9cb13dSMatthias Ringwald 
18981b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
189927e0774aSMatthias Ringwald     // assumption: outgoing connection
19001b9cb13dSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
19011b9cb13dSMatthias Ringwald     if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
19021b9cb13dSMatthias Ringwald         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
19031b9cb13dSMatthias Ringwald         channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
19041b9cb13dSMatthias Ringwald         return;
19051b9cb13dSMatthias Ringwald     }
19061b9cb13dSMatthias Ringwald #endif
19071b9cb13dSMatthias Ringwald 
19081b9cb13dSMatthias Ringwald     // fine, go ahead
19091b9cb13dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
19101b9cb13dSMatthias Ringwald }
19111b9cb13dSMatthias Ringwald 
19122df5dadcS[email protected] static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
19132df5dadcS[email protected]     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
19142df5dadcS[email protected] 
1915bbc80a48SMatthias Ringwald     // we have been waiting for remote supported features
1916ac301f95S[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));
1917bbc80a48SMatthias Ringwald     if (l2cap_security_level_0_allowed_for_PSM(channel->psm) == 0){
19182df5dadcS[email protected]         // request security level 2
19192df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
1920dfce2622SMilanka Ringwald         channel->required_security_level = LEVEL_2;
1921fc64f94aSMatthias Ringwald         gap_request_security_level(channel->con_handle, LEVEL_2);
19222df5dadcS[email protected]         return;
19232df5dadcS[email protected]     }
19241b9cb13dSMatthias Ringwald 
19251b9cb13dSMatthias Ringwald     l2cap_ready_to_connect(channel);
19262df5dadcS[email protected] }
192709e9d05bSMatthias Ringwald #endif
19282df5dadcS[email protected] 
192909e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
19305d18f623SMatthias 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,
1931da144af5SMatthias Ringwald     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
1932da144af5SMatthias Ringwald 
1933da144af5SMatthias Ringwald     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1934da144af5SMatthias Ringwald     if (!channel) {
1935da144af5SMatthias Ringwald         return NULL;
1936da144af5SMatthias Ringwald     }
1937da144af5SMatthias Ringwald 
1938da144af5SMatthias Ringwald     // fill in
1939da144af5SMatthias Ringwald     channel->packet_handler = packet_handler;
19405d18f623SMatthias Ringwald     channel->channel_type   = channel_type;
1941da144af5SMatthias Ringwald     bd_addr_copy(channel->address, address);
1942da144af5SMatthias Ringwald     channel->address_type = address_type;
1943da144af5SMatthias Ringwald     channel->psm = psm;
1944da144af5SMatthias Ringwald     channel->local_mtu  = local_mtu;
1945b37a9357SMatthias Ringwald     channel->remote_mtu = L2CAP_DEFAULT_MTU;
1946da144af5SMatthias Ringwald     channel->required_security_level = security_level;
1947da144af5SMatthias Ringwald 
1948da144af5SMatthias Ringwald     //
1949da144af5SMatthias Ringwald     channel->local_cid = l2cap_next_local_cid();
1950e0780573SMatthias Ringwald     channel->con_handle = HCI_CON_HANDLE_INVALID;
1951da144af5SMatthias Ringwald 
1952da144af5SMatthias Ringwald     // set initial state
1953da144af5SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
1954da144af5SMatthias Ringwald     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
1955da144af5SMatthias Ringwald     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
1956da144af5SMatthias Ringwald     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
195738f62777SMatthias Ringwald 
1958c45d6b2cSMatthias Ringwald     log_info("create channel %p, local_cid 0x%04x", channel, channel->local_cid);
1959e5ac0afcSMatthias Ringwald 
1960da144af5SMatthias Ringwald     return channel;
1961da144af5SMatthias Ringwald }
1962c45d6b2cSMatthias Ringwald 
1963c45d6b2cSMatthias Ringwald static void l2cap_free_channel_entry(l2cap_channel_t * channel){
1964c45d6b2cSMatthias Ringwald     log_info("free channel %p, local_cid 0x%04x", channel, channel->local_cid);
19658f4dd6c1SMatthias Ringwald     // assert all timers are stopped
1966b5bab9c8SMatthias Ringwald     l2cap_stop_rtx(channel);
19678f4dd6c1SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
19688f4dd6c1SMatthias Ringwald     l2cap_ertm_stop_retransmission_timer(channel);
19698f4dd6c1SMatthias Ringwald     l2cap_ertm_stop_monitor_timer(channel);
19708f4dd6c1SMatthias Ringwald #endif
1971b5bab9c8SMatthias Ringwald     // free  memory
1972c45d6b2cSMatthias Ringwald     btstack_memory_l2cap_channel_free(channel);
1973c45d6b2cSMatthias Ringwald }
197409e9d05bSMatthias Ringwald #endif
197509e9d05bSMatthias Ringwald 
197609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1977da144af5SMatthias Ringwald 
19789077cb15SMatthias Ringwald /**
19799077cb15SMatthias Ringwald  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
19809077cb15SMatthias Ringwald  * @param packet_handler
19819077cb15SMatthias Ringwald  * @param address
19829077cb15SMatthias Ringwald  * @param psm
19839077cb15SMatthias Ringwald  * @param mtu
19849077cb15SMatthias Ringwald  * @param local_cid
19859077cb15SMatthias Ringwald  */
19869077cb15SMatthias Ringwald 
19879d139fbaSMatthias 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){
19889d139fbaSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
19899d139fbaSMatthias Ringwald     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1990da144af5SMatthias Ringwald 
19919d139fbaSMatthias 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);
1992da144af5SMatthias Ringwald 
1993f16129ceSMatthias 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);
1994fc64f94aSMatthias Ringwald     if (!channel) {
19959077cb15SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
19969077cb15SMatthias Ringwald     }
19979077cb15SMatthias Ringwald 
19981b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
19991b9cb13dSMatthias Ringwald     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
20001b9cb13dSMatthias Ringwald #endif
20011b9cb13dSMatthias Ringwald 
20029077cb15SMatthias Ringwald     // add to connections list
2003fc64f94aSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
20049077cb15SMatthias Ringwald 
20059077cb15SMatthias Ringwald     // store local_cid
20069077cb15SMatthias Ringwald     if (out_local_cid){
2007fc64f94aSMatthias Ringwald        *out_local_cid = channel->local_cid;
20089077cb15SMatthias Ringwald     }
20099077cb15SMatthias Ringwald 
20109077cb15SMatthias Ringwald     // check if hci connection is already usable
2011f16129ceSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
201257a9eeaeSMatthias Ringwald     if (conn && conn->con_handle != HCI_CON_HANDLE_INVALID){
2013e5ac0afcSMatthias Ringwald         log_info("l2cap_create_channel, hci connection 0x%04x already exists", conn->con_handle);
2014fc64f94aSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
20159077cb15SMatthias Ringwald         // check if remote supported fearures are already received
20169077cb15SMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
2017fc64f94aSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
20189077cb15SMatthias Ringwald         }
20199077cb15SMatthias Ringwald     }
20209077cb15SMatthias Ringwald 
20219077cb15SMatthias Ringwald     l2cap_run();
20229077cb15SMatthias Ringwald 
2023c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
20249077cb15SMatthias Ringwald }
20259077cb15SMatthias Ringwald 
20261ea99aafSMilanka Ringwald void l2cap_disconnect(uint16_t local_cid, uint8_t reason){
2027e0abb8e7S[email protected]     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
2028b35f641cSmatthias.ringwald     // find channel for local_cid
2029b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2030f62db1e3Smatthias.ringwald     if (channel) {
2031e7ff783cSmatthias.ringwald         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2032f62db1e3Smatthias.ringwald     }
20332cd0be45Smatthias.ringwald     // process
20342cd0be45Smatthias.ringwald     l2cap_run();
203543625864Smatthias.ringwald }
20361e6aba47Smatthias.ringwald 
2037afde0c52Smatthias.ringwald static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
2038ceec418aSMatthias Ringwald     // mark all channels before emitting open events as these could trigger new connetion requests to the same device
2039665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
2040665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2041665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2042665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2043fad84cafSMatthias Ringwald         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2044058e3d6bSMatthias Ringwald         if (bd_addr_cmp( channel->address, address) != 0) continue;
2045c22aecc9S[email protected]         // channel for this address found
2046c22aecc9S[email protected]         switch (channel->state){
2047c22aecc9S[email protected]             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2048c22aecc9S[email protected]             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2049ceec418aSMatthias Ringwald                 channel->state = L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD;
2050c22aecc9S[email protected]                 break;
2051c22aecc9S[email protected]             default:
2052c22aecc9S[email protected]                 break;
2053afde0c52Smatthias.ringwald         }
2054afde0c52Smatthias.ringwald     }
2055ceec418aSMatthias Ringwald     // emit and free marked entries. restart loop to deal with list changes
2056ceec418aSMatthias Ringwald     int done = 0;
2057ceec418aSMatthias Ringwald     while (!done) {
2058ceec418aSMatthias Ringwald         done = 1;
2059ceec418aSMatthias Ringwald         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2060ceec418aSMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
2061ceec418aSMatthias Ringwald             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2062fad84cafSMatthias Ringwald             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2063ceec418aSMatthias Ringwald             if (channel->state == L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD){
2064ceec418aSMatthias Ringwald                 done = 0;
2065ceec418aSMatthias Ringwald                 // failure, forward error code
206666a72640SMatthias Ringwald                 l2cap_handle_channel_open_failed(channel, status);
2067ceec418aSMatthias Ringwald                 // discard channel
2068ceec418aSMatthias Ringwald                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2069c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
2070ceec418aSMatthias Ringwald                 break;
2071ceec418aSMatthias Ringwald             }
2072ceec418aSMatthias Ringwald         }
2073ceec418aSMatthias Ringwald     }
2074ceec418aSMatthias Ringwald 
2075afde0c52Smatthias.ringwald }
2076afde0c52Smatthias.ringwald 
2077afde0c52Smatthias.ringwald static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
2078665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
2079665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2080665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2081665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2082fad84cafSMatthias Ringwald         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2083058e3d6bSMatthias Ringwald         if ( ! bd_addr_cmp( channel->address, address) ){
20842df5dadcS[email protected]             l2cap_handle_connection_complete(handle, channel);
2085afde0c52Smatthias.ringwald         }
2086afde0c52Smatthias.ringwald     }
20876fdcc387Smatthias.ringwald     // process
20886fdcc387Smatthias.ringwald     l2cap_run();
2089afde0c52Smatthias.ringwald }
209009e9d05bSMatthias Ringwald #endif
2091b448a0e7Smatthias.ringwald 
20926774d5c9SMatthias Ringwald static bool l2cap_channel_ready_to_send(l2cap_channel_t * channel){
20936774d5c9SMatthias Ringwald     switch (channel->channel_type){
20946774d5c9SMatthias Ringwald #ifdef ENABLE_CLASSIC
20956774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CLASSIC:
20966774d5c9SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2097d89ab698SMatthias Ringwald             // send if we have more data and remote windows isn't full yet
2098d89ab698SMatthias Ringwald             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2099d89ab698SMatthias Ringwald                 if (channel->unacked_frames >= btstack_min(channel->num_stored_tx_frames, channel->remote_tx_window_size)) return false;
21006774d5c9SMatthias Ringwald                 return hci_can_send_acl_classic_packet_now() != 0;
2101d89ab698SMatthias Ringwald             }
2102d89ab698SMatthias Ringwald #endif
2103d89ab698SMatthias Ringwald             if (!channel->waiting_for_can_send_now) return false;
2104d89ab698SMatthias Ringwald             return (hci_can_send_acl_classic_packet_now() != 0);
21056774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
21066774d5c9SMatthias Ringwald             if (!channel->waiting_for_can_send_now) return false;
21076774d5c9SMatthias Ringwald             return hci_can_send_acl_classic_packet_now() != 0;
21086774d5c9SMatthias Ringwald #endif
21096774d5c9SMatthias Ringwald #ifdef ENABLE_BLE
21106774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_FIXED:
21116774d5c9SMatthias Ringwald             if (!channel->waiting_for_can_send_now) return false;
21126774d5c9SMatthias Ringwald             return hci_can_send_acl_le_packet_now() != 0;
21136774d5c9SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
21146774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
21156774d5c9SMatthias Ringwald             if (channel->send_sdu_buffer == NULL) return false;
21166774d5c9SMatthias Ringwald             if (channel->credits_outgoing == 0) return false;
21176774d5c9SMatthias Ringwald             return hci_can_send_acl_le_packet_now() != 0;
21186774d5c9SMatthias Ringwald #endif
21196774d5c9SMatthias Ringwald #endif
21206774d5c9SMatthias Ringwald         default:
21216774d5c9SMatthias Ringwald             return false;
21226774d5c9SMatthias Ringwald     }
21236774d5c9SMatthias Ringwald }
21246774d5c9SMatthias Ringwald 
21256774d5c9SMatthias Ringwald static void l2cap_channel_trigger_send(l2cap_channel_t * channel){
21266774d5c9SMatthias Ringwald     switch (channel->channel_type){
2127d89ab698SMatthias Ringwald #ifdef ENABLE_CLASSIC
2128d89ab698SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CLASSIC:
2129d89ab698SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2130d89ab698SMatthias Ringwald             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2131d89ab698SMatthias Ringwald                 l2cap_ertm_channel_send_information_frame(channel);
2132d89ab698SMatthias Ringwald                 return;
2133d89ab698SMatthias Ringwald             }
2134d89ab698SMatthias Ringwald #endif
2135d89ab698SMatthias Ringwald             channel->waiting_for_can_send_now = 0;
2136d89ab698SMatthias Ringwald             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2137d89ab698SMatthias Ringwald             break;
2138d89ab698SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2139d89ab698SMatthias Ringwald             channel->waiting_for_can_send_now = 0;
2140d89ab698SMatthias Ringwald             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2141d89ab698SMatthias Ringwald             break;
2142d89ab698SMatthias Ringwald #endif
21436774d5c9SMatthias Ringwald #ifdef ENABLE_BLE
2144d89ab698SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_FIXED:
2145d89ab698SMatthias Ringwald             channel->waiting_for_can_send_now = 0;
2146d89ab698SMatthias Ringwald             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2147d89ab698SMatthias Ringwald             break;
21486774d5c9SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
21496774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
21506774d5c9SMatthias Ringwald             l2cap_le_send_pdu(channel);
21516774d5c9SMatthias Ringwald             break;
21526774d5c9SMatthias Ringwald #endif
21536774d5c9SMatthias Ringwald #endif
21546774d5c9SMatthias Ringwald         default:
21556774d5c9SMatthias Ringwald             break;
21566774d5c9SMatthias Ringwald     }
21576774d5c9SMatthias Ringwald }
21586774d5c9SMatthias Ringwald 
215933c40538SMatthias Ringwald static void l2cap_notify_channel_can_send(void){
21606774d5c9SMatthias Ringwald     bool done = false;
21617740e150SMatthias Ringwald     while (!done){
21626774d5c9SMatthias Ringwald         done = true;
216333c40538SMatthias Ringwald         btstack_linked_list_iterator_t it;
216433c40538SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &l2cap_channels);
216533c40538SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
216633c40538SMatthias Ringwald             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
21676774d5c9SMatthias Ringwald             bool ready = l2cap_channel_ready_to_send(channel);
21686774d5c9SMatthias Ringwald             if (!ready) continue;
21696774d5c9SMatthias Ringwald 
21706774d5c9SMatthias Ringwald             // requeue channel for fairness
21717740e150SMatthias Ringwald             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
21727740e150SMatthias Ringwald             btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
21736774d5c9SMatthias Ringwald 
21746774d5c9SMatthias Ringwald             // trigger sending
21756774d5c9SMatthias Ringwald             l2cap_channel_trigger_send(channel);
21766774d5c9SMatthias Ringwald 
21777740e150SMatthias Ringwald             // exit inner loop as we just broke the iterator, but try again
21786774d5c9SMatthias Ringwald             done = false;
21797740e150SMatthias Ringwald             break;
21807740e150SMatthias Ringwald         }
218133c40538SMatthias Ringwald     }
218233c40538SMatthias Ringwald }
218333c40538SMatthias Ringwald 
21842053036dSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
21852053036dSMatthias Ringwald 
21862053036dSMatthias Ringwald static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){
21872053036dSMatthias Ringwald     // open cannot fail for for incoming connections
21882053036dSMatthias Ringwald     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0;
21892053036dSMatthias Ringwald 
21902053036dSMatthias Ringwald     // check state
21912053036dSMatthias Ringwald     switch (channel->state){
21922053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
21932053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
21942053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES:
21952053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
21962053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
21972053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES:
21982053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
21992053036dSMatthias Ringwald         case L2CAP_STATE_CONFIG:
22002053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
22012053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
22022053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE:
2203ceec418aSMatthias Ringwald         case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD:
22042053036dSMatthias Ringwald             return 1;
22052053036dSMatthias Ringwald 
22062053036dSMatthias Ringwald         case L2CAP_STATE_OPEN:
22072053036dSMatthias Ringwald         case L2CAP_STATE_CLOSED:
22082053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES:
22092053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
22102053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY:
22112053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
22122053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
22132053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
22142053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
22152053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
22162053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
22172053036dSMatthias Ringwald         case L2CAP_STATE_INVALID:
22182053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
22192053036dSMatthias Ringwald             return 0;
22206aa7d794SMatthias Ringwald         // no default here, to get a warning about new states
22212053036dSMatthias Ringwald     }
22226aa7d794SMatthias Ringwald     // still, the compiler insists on a return value
22236aa7d794SMatthias Ringwald     return 0;
22242053036dSMatthias Ringwald }
222513aa3e4bSMatthias Ringwald #endif
22262053036dSMatthias Ringwald 
222713aa3e4bSMatthias Ringwald #ifdef ENABLE_CLASSIC
22282053036dSMatthias Ringwald static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){
22292053036dSMatthias Ringwald     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
223066a72640SMatthias Ringwald         l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
22312053036dSMatthias Ringwald     } else {
223266a72640SMatthias Ringwald         l2cap_handle_channel_closed(channel);
22332053036dSMatthias Ringwald     }
2234c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
22352053036dSMatthias Ringwald }
22362053036dSMatthias Ringwald #endif
22372053036dSMatthias Ringwald 
22382cf36df7SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
22392cf36df7SMatthias Ringwald static void l2cap_handle_hci_le_disconnect_event(l2cap_channel_t * channel){
22402cf36df7SMatthias Ringwald     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
22412cf36df7SMatthias Ringwald         l2cap_emit_le_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
22422cf36df7SMatthias Ringwald     } else {
22432cf36df7SMatthias Ringwald         l2cap_emit_le_channel_closed(channel);
22442cf36df7SMatthias Ringwald     }
2245c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
22462cf36df7SMatthias Ringwald }
22472cf36df7SMatthias Ringwald #endif
22482053036dSMatthias Ringwald 
2249d9a7306aSMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
2250afde0c52Smatthias.ringwald 
22515774a392SMatthias Ringwald     UNUSED(packet_type); // ok: registered with hci_event_callback_registration
22525774a392SMatthias Ringwald     UNUSED(cid);         // ok: there is no channel
22535774a392SMatthias Ringwald     UNUSED(size);        // ok: fixed format events read from HCI buffer
22549ec2630cSMatthias Ringwald 
22555774a392SMatthias Ringwald #ifdef ENABLE_CLASSIC
2256afde0c52Smatthias.ringwald     bd_addr_t address;
22572d00edd4Smatthias.ringwald     int hci_con_used;
22585774a392SMatthias Ringwald #endif
22595774a392SMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
22605774a392SMatthias Ringwald     hci_con_handle_t handle;
226109e9d05bSMatthias Ringwald     btstack_linked_list_iterator_t it;
22625774a392SMatthias Ringwald #endif
2263afde0c52Smatthias.ringwald 
22640e2df43fSMatthias Ringwald     switch(hci_event_packet_get_type(packet)){
2265afde0c52Smatthias.ringwald 
226609e9d05bSMatthias Ringwald         // Notify channel packet handler if they can send now
226709e9d05bSMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
226809e9d05bSMatthias Ringwald         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
2269eea99214SMatthias Ringwald         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
227009e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
227109e9d05bSMatthias Ringwald             l2cap_notify_channel_can_send();
227209e9d05bSMatthias Ringwald             break;
227309e9d05bSMatthias Ringwald 
227409e9d05bSMatthias Ringwald         case HCI_EVENT_COMMAND_STATUS:
2275ece97caeSMatthias Ringwald #ifdef ENABLE_CLASSIC
2276ece97caeSMatthias Ringwald             // check command status for create connection for errors
2277ece97caeSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
2278ece97caeSMatthias Ringwald                 // cache outgoing address and reset
22796535961aSMatthias Ringwald                 (void)memcpy(address, l2cap_outgoing_classic_addr, 6);
2280ece97caeSMatthias Ringwald                 memset(l2cap_outgoing_classic_addr, 0, 6);
2281ece97caeSMatthias Ringwald                 // error => outgoing connection failed
2282ece97caeSMatthias Ringwald                 uint8_t status = hci_event_command_status_get_status(packet);
2283ece97caeSMatthias Ringwald                 if (status){
2284ece97caeSMatthias Ringwald                     l2cap_handle_connection_failed_for_addr(address, status);
2285ece97caeSMatthias Ringwald                 }
2286ece97caeSMatthias Ringwald             }
2287ece97caeSMatthias Ringwald #endif
228809e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
228909e9d05bSMatthias Ringwald             break;
229009e9d05bSMatthias Ringwald 
229109e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2292afde0c52Smatthias.ringwald         // handle connection complete events
2293afde0c52Smatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
2294724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], address);
2295afde0c52Smatthias.ringwald             if (packet[2] == 0){
2296f8fbdce0SMatthias Ringwald                 handle = little_endian_read_16(packet, 3);
2297afde0c52Smatthias.ringwald                 l2cap_handle_connection_success_for_addr(address, handle);
2298afde0c52Smatthias.ringwald             } else {
2299afde0c52Smatthias.ringwald                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
2300afde0c52Smatthias.ringwald             }
2301afde0c52Smatthias.ringwald             break;
2302afde0c52Smatthias.ringwald 
2303afde0c52Smatthias.ringwald         // handle successful create connection cancel command
2304afde0c52Smatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
2305073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
2306afde0c52Smatthias.ringwald                 if (packet[5] == 0){
2307724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[6], address);
2308afde0c52Smatthias.ringwald                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
2309afde0c52Smatthias.ringwald                     l2cap_handle_connection_failed_for_addr(address, 0x16);
231003cfbabcSmatthias.ringwald                 }
23111e6aba47Smatthias.ringwald             }
231239d59809Smatthias.ringwald             l2cap_run();    // try sending signaling packets first
231339d59809Smatthias.ringwald             break;
231409e9d05bSMatthias Ringwald #endif
231527a923d0Smatthias.ringwald 
23162053036dSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
23171e6aba47Smatthias.ringwald         // handle disconnection complete events
2318afde0c52Smatthias.ringwald         case HCI_EVENT_DISCONNECTION_COMPLETE:
2319d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
23202053036dSMatthias Ringwald             // send l2cap open failed or closed events for all channels on this handle and free them
2321665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2322665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2323665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2324fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2325fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
2326665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
2327421cb104SMatthias Ringwald                 switch(channel->channel_type){
2328421cb104SMatthias Ringwald #ifdef ENABLE_CLASSIC
2329421cb104SMatthias Ringwald                     case L2CAP_CHANNEL_TYPE_CLASSIC:
23302053036dSMatthias Ringwald                         l2cap_handle_hci_disconnect_event(channel);
2331421cb104SMatthias Ringwald                         break;
233209e9d05bSMatthias Ringwald #endif
2333a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2334421cb104SMatthias Ringwald                     case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
23352cf36df7SMatthias Ringwald                         l2cap_handle_hci_le_disconnect_event(channel);
2336afde0c52Smatthias.ringwald                         break;
23372053036dSMatthias Ringwald #endif
2338421cb104SMatthias Ringwald                     default:
2339421cb104SMatthias Ringwald                         break;
2340421cb104SMatthias Ringwald                 }
2341421cb104SMatthias Ringwald             }
23429909e5e4SMatthias Ringwald             break;
2343421cb104SMatthias Ringwald #endif
2344fcadd0caSmatthias.ringwald 
23459909e5e4SMatthias Ringwald 
2346ee091cf1Smatthias.ringwald         // HCI Connection Timeouts
234709e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2348afde0c52Smatthias.ringwald         case L2CAP_EVENT_TIMEOUT_CHECK:
2349f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
2350bd04d84aSMatthias Ringwald             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
235180ca58a0Smatthias.ringwald             if (hci_authentication_active_for_handle(handle)) break;
23522d00edd4Smatthias.ringwald             hci_con_used = 0;
2353665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2354665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2355665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2356fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2357fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
23582d00edd4Smatthias.ringwald                 hci_con_used = 1;
2359c22aecc9S[email protected]                 break;
2360ee091cf1Smatthias.ringwald             }
23612d00edd4Smatthias.ringwald             if (hci_con_used) break;
2362d94d3cafS[email protected]             if (!hci_can_send_command_packet_now()) break;
23639edc8742Smatthias.ringwald             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
2364afde0c52Smatthias.ringwald             break;
2365ee091cf1Smatthias.ringwald 
2366df3354fcS[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2367f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
2368665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2369665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2370665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2371fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2372fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
2373e5ac0afcSMatthias Ringwald                 log_info("remote supported features, channel %p, cid %04x - state %u", channel, channel->local_cid, channel->state);
23742df5dadcS[email protected]                 l2cap_handle_remote_supported_features_received(channel);
2375df3354fcS[email protected]             }
2376c22aecc9S[email protected]             break;
2377df3354fcS[email protected] 
23785611a760SMatthias Ringwald         case GAP_EVENT_SECURITY_LEVEL:
2379f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
2380e5ac0afcSMatthias Ringwald             log_info("l2cap - security level update for handle 0x%04x", handle);
2381665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2382665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2383665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2384fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2385fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
23865533f01eS[email protected] 
2387e569dfd9SMatthias Ringwald                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
23885533f01eS[email protected]                 gap_security_level_t required_level = channel->required_security_level;
23895533f01eS[email protected] 
2390e5ac0afcSMatthias Ringwald                 log_info("channel %p, cid %04x - state %u: actual %u >= required %u?", channel, channel->local_cid, channel->state, actual_level, required_level);
2391dfce2622SMilanka Ringwald 
2392df3354fcS[email protected]                 switch (channel->state){
2393df3354fcS[email protected]                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
23945533f01eS[email protected]                         if (actual_level >= required_level){
239552606043SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
239652606043SMatthias Ringwald                             // we need to know if ERTM is supported before sending a config response
239752606043SMatthias Ringwald                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
239852606043SMatthias Ringwald                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
239952606043SMatthias Ringwald                             channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
240052606043SMatthias Ringwald #else
2401f85a9399S[email protected]                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
240244276248SMatthias Ringwald                             l2cap_emit_incoming_connection(channel);
240352606043SMatthias Ringwald #endif
24041eb2563eS[email protected]                         } else {
2405775ecc36SMatthias Ringwald                             channel->reason = 0x0003; // security block
24061eb2563eS[email protected]                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
24071eb2563eS[email protected]                         }
2408df3354fcS[email protected]                         break;
2409df3354fcS[email protected] 
2410df3354fcS[email protected]                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
24115533f01eS[email protected]                         if (actual_level >= required_level){
24121b9cb13dSMatthias Ringwald                             l2cap_ready_to_connect(channel);
2413df3354fcS[email protected]                         } else {
2414df3354fcS[email protected]                             // disconnnect, authentication not good enough
2415df3354fcS[email protected]                             hci_disconnect_security_block(handle);
2416df3354fcS[email protected]                         }
2417df3354fcS[email protected]                         break;
2418df3354fcS[email protected] 
2419df3354fcS[email protected]                     default:
2420df3354fcS[email protected]                         break;
2421df3354fcS[email protected]                 }
2422f85a9399S[email protected]             }
2423f85a9399S[email protected]             break;
242409e9d05bSMatthias Ringwald #endif
2425f85a9399S[email protected] 
2426afde0c52Smatthias.ringwald         default:
2427afde0c52Smatthias.ringwald             break;
2428afde0c52Smatthias.ringwald     }
2429afde0c52Smatthias.ringwald 
2430bd63148eS[email protected]     l2cap_run();
24311e6aba47Smatthias.ringwald }
24321e6aba47Smatthias.ringwald 
2433e74c5f58SMatthias 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){
24344cf56b4aSmatthias.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."
24352b360848Smatthias.ringwald     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
24362b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].handle = handle;
24372b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].code = code;
24382b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].sig_id = sig_id;
2439e74c5f58SMatthias Ringwald         signaling_responses[signaling_responses_pending].cid = cid;
24402b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].data = data;
24412b360848Smatthias.ringwald         signaling_responses_pending++;
24422b360848Smatthias.ringwald         l2cap_run();
24432b360848Smatthias.ringwald     }
24442b360848Smatthias.ringwald }
24452b360848Smatthias.ringwald 
244609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
244709e9d05bSMatthias Ringwald static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
244809e9d05bSMatthias Ringwald     channel->remote_sig_id = identifier;
244909e9d05bSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
245009e9d05bSMatthias Ringwald     l2cap_run();
245109e9d05bSMatthias Ringwald }
245209e9d05bSMatthias Ringwald 
2453b35f641cSmatthias.ringwald static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
2454645658c9Smatthias.ringwald 
24559da54300S[email protected]     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
2456645658c9Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
2457645658c9Smatthias.ringwald     if (!service) {
2458645658c9Smatthias.ringwald         // 0x0002 PSM not supported
2459e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2460645658c9Smatthias.ringwald         return;
2461645658c9Smatthias.ringwald     }
2462645658c9Smatthias.ringwald 
24635061f3afS[email protected]     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
2464645658c9Smatthias.ringwald     if (!hci_connection) {
24652b360848Smatthias.ringwald         //
24669da54300S[email protected]         log_error("no hci_connection for handle %u", handle);
2467645658c9Smatthias.ringwald         return;
2468645658c9Smatthias.ringwald     }
24692bd8b7e7S[email protected] 
2470645658c9Smatthias.ringwald     // alloc structure
24719da54300S[email protected]     // log_info("l2cap_handle_connection_request register channel");
2472f16129ceSMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, hci_connection->address, BD_ADDR_TYPE_ACL,
2473da144af5SMatthias Ringwald     psm, service->mtu, service->required_security_level);
24742b360848Smatthias.ringwald     if (!channel){
24752b360848Smatthias.ringwald         // 0x0004 No resources available
2476e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
24772b360848Smatthias.ringwald         return;
24782b360848Smatthias.ringwald     }
2479da144af5SMatthias Ringwald 
2480fc64f94aSMatthias Ringwald     channel->con_handle = handle;
2481b35f641cSmatthias.ringwald     channel->remote_cid = source_cid;
2482b1988dceSmatthias.ringwald     channel->remote_sig_id = sig_id;
2483645658c9Smatthias.ringwald 
2484f53da564S[email protected]     // limit local mtu to max acl packet length - l2cap header
24852985cb84Smatthias.ringwald     if (channel->local_mtu > l2cap_max_mtu()) {
24862985cb84Smatthias.ringwald         channel->local_mtu = l2cap_max_mtu();
24879775e25bSmatthias.ringwald     }
24889775e25bSmatthias.ringwald 
2489645658c9Smatthias.ringwald     // set initial state
2490df3354fcS[email protected]     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
2491a24785d0SMatthias Ringwald     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
2492e405ae81Smatthias.ringwald 
2493645658c9Smatthias.ringwald     // add to connections list
2494665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
2495645658c9Smatthias.ringwald 
2496f85a9399S[email protected]     // assert security requirements
24971eb2563eS[email protected]     gap_request_security_level(handle, channel->required_security_level);
2498e405ae81Smatthias.ringwald }
2499645658c9Smatthias.ringwald 
2500ce8f182eSMatthias Ringwald void l2cap_accept_connection(uint16_t local_cid){
2501e0abb8e7S[email protected]     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
2502b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2503e405ae81Smatthias.ringwald     if (!channel) {
2504ce8f182eSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
2505e405ae81Smatthias.ringwald         return;
2506e405ae81Smatthias.ringwald     }
2507e405ae81Smatthias.ringwald 
250843ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
250943ec931dSMatthias Ringwald     // configure L2CAP Basic mode
251043ec931dSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
251143ec931dSMatthias Ringwald #endif
251243ec931dSMatthias Ringwald 
2513552d92a1Smatthias.ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
2514e405ae81Smatthias.ringwald 
2515552d92a1Smatthias.ringwald     // process
2516552d92a1Smatthias.ringwald     l2cap_run();
2517e405ae81Smatthias.ringwald }
2518645658c9Smatthias.ringwald 
25197ef6a7bbSMatthias Ringwald void l2cap_decline_connection(uint16_t local_cid){
25207ef6a7bbSMatthias Ringwald     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
2521b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
2522e405ae81Smatthias.ringwald     if (!channel) {
2523ce8f182eSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
2524e405ae81Smatthias.ringwald         return;
2525e405ae81Smatthias.ringwald     }
2526e7ff783cSmatthias.ringwald     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
25277ef6a7bbSMatthias Ringwald     channel->reason = 0x04; // no resources available
2528e7ff783cSmatthias.ringwald     l2cap_run();
2529645658c9Smatthias.ringwald }
2530645658c9Smatthias.ringwald 
2531e9cfb251SMatthias Ringwald // @pre command len is valid, see check in l2cap_signaling_handler_channel
25327f02f414SMatthias Ringwald static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
2533b1988dceSmatthias.ringwald 
2534fcb125edSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2535fcb125edSMatthias Ringwald     uint8_t use_fcs = 1;
2536fcb125edSMatthias Ringwald #endif
2537fcb125edSMatthias Ringwald 
2538b1988dceSmatthias.ringwald     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2539b1988dceSmatthias.ringwald 
2540f8fbdce0SMatthias Ringwald     uint16_t flags = little_endian_read_16(command, 6);
254163a7246aSmatthias.ringwald     if (flags & 1) {
254263a7246aSmatthias.ringwald         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
254363a7246aSmatthias.ringwald     }
254463a7246aSmatthias.ringwald 
25452784b77dSmatthias.ringwald     // accept the other's configuration options
2546f8fbdce0SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
25473de7c0caSmatthias.ringwald     uint16_t pos     = 8;
25483de7c0caSmatthias.ringwald     while (pos < end_pos){
254963a7246aSmatthias.ringwald         uint8_t option_hint = command[pos] >> 7;
255063a7246aSmatthias.ringwald         uint8_t option_type = command[pos] & 0x7f;
25513844aeadSMatthias Ringwald         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
255263a7246aSmatthias.ringwald         pos++;
25531dc511deSmatthias.ringwald         uint8_t length = command[pos++];
25541dc511deSmatthias.ringwald         // MTU { type(8): 1, len(8):2, MTU(16) }
2555c1ab6cc1SMatthias Ringwald         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) && (length == 2)){
2556f8fbdce0SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, pos);
25573844aeadSMatthias Ringwald             log_info("Remote MTU %u", channel->remote_mtu);
25589d139fbaSMatthias Ringwald             if (channel->remote_mtu > l2cap_max_mtu()){
25599d139fbaSMatthias Ringwald                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
25609d139fbaSMatthias Ringwald                 channel->remote_mtu = l2cap_max_mtu();
25619d139fbaSMatthias Ringwald             }
256263a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
256363a7246aSmatthias.ringwald         }
25640fe7a9d0S[email protected]         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
2565e53a3388SMatthias Ringwald         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT) && (length == 2)){
2566f8fbdce0SMatthias Ringwald             channel->flush_timeout = little_endian_read_16(command, pos);
25673844aeadSMatthias Ringwald             log_info("Flush timeout: %u ms", channel->flush_timeout);
25680fe7a9d0S[email protected]         }
2569f2fa388dSMatthias Ringwald 
25706dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
25716dca2a0cSMatthias Ringwald         // Retransmission and Flow Control Option
2572671fb338SMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
25733232a1c6SMatthias Ringwald             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
2574ac8f1300SMatthias Ringwald             switch(channel->mode){
2575ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
257625cd60d3SMatthias Ringwald                     // Store remote config
2577bbc0a9e7SMatthias Ringwald                     channel->remote_tx_window_size = command[pos+1];
2578bbc0a9e7SMatthias Ringwald                     channel->remote_max_transmit   = command[pos+2];
2579bbc0a9e7SMatthias Ringwald                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
2580bbc0a9e7SMatthias Ringwald                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
25813844aeadSMatthias Ringwald                     channel->remote_mps = little_endian_read_16(command, pos + 7);
25823844aeadSMatthias Ringwald                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
2583bbc0a9e7SMatthias Ringwald                         channel->remote_tx_window_size,
2584bbc0a9e7SMatthias Ringwald                         channel->remote_max_transmit,
2585bbc0a9e7SMatthias Ringwald                         channel->remote_retransmission_timeout_ms,
25863844aeadSMatthias Ringwald                         channel->remote_monitor_timeout_ms,
25873844aeadSMatthias Ringwald                         channel->remote_mps);
258825cd60d3SMatthias Ringwald                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
258925cd60d3SMatthias Ringwald                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
259025cd60d3SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2591ac8f1300SMatthias Ringwald                     } else {
2592b8134563SMatthias Ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2593ac8f1300SMatthias Ringwald                     }
2594ac8f1300SMatthias Ringwald                     break;
2595ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
2596ac8f1300SMatthias Ringwald                     switch (mode){
2597ac8f1300SMatthias Ringwald                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2598ac8f1300SMatthias Ringwald                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
2599ac8f1300SMatthias Ringwald                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
2600ac8f1300SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2601ac8f1300SMatthias Ringwald                             }
2602ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
2603ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
2604ac8f1300SMatthias Ringwald                             break;
2605ac8f1300SMatthias Ringwald                         default: // case L2CAP_CHANNEL_MODE_BASIC:
2606ac8f1300SMatthias Ringwald                             // TODO store and evaluate configuration
2607b8134563SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2608ac8f1300SMatthias Ringwald                             break;
2609ac8f1300SMatthias Ringwald                     }
2610ac8f1300SMatthias Ringwald                     break;
2611ac8f1300SMatthias Ringwald                 default:
2612ac8f1300SMatthias Ringwald                     break;
2613ac8f1300SMatthias Ringwald             }
26143232a1c6SMatthias Ringwald         }
26156574158aSMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
2616fcb125edSMatthias Ringwald             use_fcs = command[pos];
26176574158aSMatthias Ringwald         }
26186dca2a0cSMatthias Ringwald #endif
261963a7246aSmatthias.ringwald         // check for unknown options
2620505f1c30SMatthias Ringwald         if ((option_hint == 0) && ((option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) || (option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE))){
2621c177a91cS[email protected]             log_info("l2cap cid %u, unknown options", channel->local_cid);
262263a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
26231dc511deSmatthias.ringwald         }
26241dc511deSmatthias.ringwald         pos += length;
26251dc511deSmatthias.ringwald     }
2626fcb125edSMatthias Ringwald 
2627fcb125edSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2628fcb125edSMatthias Ringwald         // "FCS" has precedence over "No FCS"
2629fcb125edSMatthias Ringwald         uint8_t update = channel->fcs_option || use_fcs;
2630fcb125edSMatthias Ringwald         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
2631fcb125edSMatthias Ringwald         channel->fcs_option = update;
263267f8f607SMatthias Ringwald         // If ERTM mandatory, but remote didn't send Retransmission and Flowcontrol options -> disconnect
263367f8f607SMatthias Ringwald         if (((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM) == 0) & (channel->ertm_mandatory)){
263467f8f607SMatthias Ringwald             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
263567f8f607SMatthias Ringwald         }
2636fcb125edSMatthias Ringwald #endif
26372784b77dSmatthias.ringwald }
26382784b77dSmatthias.ringwald 
2639e9cfb251SMatthias Ringwald // @pre command len is valid, see check in l2cap_signaling_handler_channel
2640f2fa388dSMatthias Ringwald static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
2641f2fa388dSMatthias Ringwald     log_info("l2cap_signaling_handle_configure_response");
26423232a1c6SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
26433232a1c6SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2644f2fa388dSMatthias Ringwald     uint16_t pos     = 10;
26453232a1c6SMatthias Ringwald     while (pos < end_pos){
26463232a1c6SMatthias Ringwald         uint8_t option_hint = command[pos] >> 7;
26473232a1c6SMatthias Ringwald         uint8_t option_type = command[pos] & 0x7f;
2648fcb125edSMatthias Ringwald         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
26493232a1c6SMatthias Ringwald         pos++;
26503232a1c6SMatthias Ringwald         uint8_t length = command[pos++];
26513232a1c6SMatthias Ringwald 
26523232a1c6SMatthias Ringwald         // Retransmission and Flow Control Option
2653671fb338SMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2654ac8f1300SMatthias Ringwald             switch (channel->mode){
2655ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2656f2fa388dSMatthias Ringwald                     if (channel->ertm_mandatory){
2657ac8f1300SMatthias Ringwald                         // ??
2658f2fa388dSMatthias Ringwald                     } else {
2659ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
2660ac8f1300SMatthias Ringwald                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
266166a72640SMatthias Ringwald                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
2662f2fa388dSMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
26633232a1c6SMatthias Ringwald                         }
26643232a1c6SMatthias Ringwald                     }
2665ac8f1300SMatthias Ringwald                     break;
2666ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
2667ac8f1300SMatthias Ringwald                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2668ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
2669ac8f1300SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2670ac8f1300SMatthias Ringwald                     }
2671ac8f1300SMatthias Ringwald                     break;
2672ac8f1300SMatthias Ringwald                 default:
2673ac8f1300SMatthias Ringwald                     break;
26743232a1c6SMatthias Ringwald             }
2675f2fa388dSMatthias Ringwald         }
26763232a1c6SMatthias Ringwald 
26773232a1c6SMatthias Ringwald         // check for unknown options
2678671fb338SMatthias Ringwald         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
26793232a1c6SMatthias Ringwald             log_info("l2cap cid %u, unknown options", channel->local_cid);
26803232a1c6SMatthias Ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
26813232a1c6SMatthias Ringwald         }
26823232a1c6SMatthias Ringwald 
26833232a1c6SMatthias Ringwald         pos += length;
26843232a1c6SMatthias Ringwald     }
2685688f9764SMatthias Ringwald #else
26865774a392SMatthias Ringwald     UNUSED(channel);  // ok: no code
26875774a392SMatthias Ringwald     UNUSED(result);   // ok: no code
26885774a392SMatthias Ringwald     UNUSED(command);  // ok: no code
26893232a1c6SMatthias Ringwald #endif
26903232a1c6SMatthias Ringwald }
26913232a1c6SMatthias Ringwald 
2692fa8473a4Smatthias.ringwald static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
26939da54300S[email protected]     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
269473cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
269573cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
2696019f9b43SMatthias Ringwald     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
2697019f9b43SMatthias Ringwald     if (channel->state == L2CAP_STATE_OPEN) return 0;
2698fa8473a4Smatthias.ringwald     return 1;
2699fa8473a4Smatthias.ringwald }
2700fa8473a4Smatthias.ringwald 
2701fa8473a4Smatthias.ringwald 
2702e9cfb251SMatthias Ringwald // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
27037f02f414SMatthias Ringwald static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
27041e6aba47Smatthias.ringwald 
270500d93d79Smatthias.ringwald     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
270600d93d79Smatthias.ringwald     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2707e9cfb251SMatthias Ringwald     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
270838e5900eSmatthias.ringwald     uint16_t result = 0;
27091e6aba47Smatthias.ringwald 
27109da54300S[email protected]     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
2711b35f641cSmatthias.ringwald 
27129a011532Smatthias.ringwald     // handle DISCONNECT REQUESTS seperately
27139a011532Smatthias.ringwald     if (code == DISCONNECTION_REQUEST){
27149a011532Smatthias.ringwald         switch (channel->state){
2715fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
27169a011532Smatthias.ringwald             case L2CAP_STATE_OPEN:
27172b83fb7dSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
27189a011532Smatthias.ringwald             case L2CAP_STATE_WAIT_DISCONNECT:
27199a011532Smatthias.ringwald                 l2cap_handle_disconnect_request(channel, identifier);
27209a011532Smatthias.ringwald                 break;
27219a011532Smatthias.ringwald 
27229a011532Smatthias.ringwald             default:
27239a011532Smatthias.ringwald                 // ignore in other states
27249a011532Smatthias.ringwald                 break;
27259a011532Smatthias.ringwald         }
27269a011532Smatthias.ringwald         return;
27279a011532Smatthias.ringwald     }
27289a011532Smatthias.ringwald 
272956081214Smatthias.ringwald     // @STATEMACHINE(l2cap)
27301e6aba47Smatthias.ringwald     switch (channel->state) {
27311e6aba47Smatthias.ringwald 
27321e6aba47Smatthias.ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
27331e6aba47Smatthias.ringwald             switch (code){
27341e6aba47Smatthias.ringwald                 case CONNECTION_RESPONSE:
2735e9cfb251SMatthias Ringwald                     if (cmd_len < 8){
2736e9cfb251SMatthias Ringwald                         // command imcomplete
2737e9cfb251SMatthias Ringwald                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2738e9cfb251SMatthias Ringwald                         break;
2739e9cfb251SMatthias Ringwald                     }
27405932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2741f8fbdce0SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
274238e5900eSmatthias.ringwald                     switch (result) {
274338e5900eSmatthias.ringwald                         case 0:
2744169f8b28Smatthias.ringwald                             // successful connection
2745f8fbdce0SMatthias Ringwald                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2746fa8473a4Smatthias.ringwald                             channel->state = L2CAP_STATE_CONFIG;
274728ca2b46S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
274838e5900eSmatthias.ringwald                             break;
274938e5900eSmatthias.ringwald                         case 1:
27505932bd7cS[email protected]                             // connection pending. get some coffee, but start the ERTX
27515932bd7cS[email protected]                             l2cap_start_ertx(channel);
275238e5900eSmatthias.ringwald                             break;
275338e5900eSmatthias.ringwald                         default:
2754eb920dbeSmatthias.ringwald                             // channel closed
2755eb920dbeSmatthias.ringwald                             channel->state = L2CAP_STATE_CLOSED;
2756f32b992eSmatthias.ringwald                             // map l2cap connection response result to BTstack status enumeration
275766a72640SMatthias Ringwald                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
2758eb920dbeSmatthias.ringwald 
2759eb920dbeSmatthias.ringwald                             // drop link key if security block
2760c1ab6cc1SMatthias Ringwald                             if ((L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result) == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
276115a95bd5SMatthias Ringwald                                 gap_drop_link_key_for_bd_addr(channel->address);
2762eb920dbeSmatthias.ringwald                             }
2763eb920dbeSmatthias.ringwald 
2764eb920dbeSmatthias.ringwald                             // discard channel
2765665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2766c45d6b2cSMatthias Ringwald                             l2cap_free_channel_entry(channel);
276738e5900eSmatthias.ringwald                             break;
27681e6aba47Smatthias.ringwald                     }
27691e6aba47Smatthias.ringwald                     break;
277038e5900eSmatthias.ringwald 
277138e5900eSmatthias.ringwald                 default:
27721e6aba47Smatthias.ringwald                     //@TODO: implement other signaling packets
277338e5900eSmatthias.ringwald                     break;
27741e6aba47Smatthias.ringwald             }
27751e6aba47Smatthias.ringwald             break;
27761e6aba47Smatthias.ringwald 
2777fa8473a4Smatthias.ringwald         case L2CAP_STATE_CONFIG:
2778ae280e73Smatthias.ringwald             switch (code) {
2779ae280e73Smatthias.ringwald                 case CONFIGURE_REQUEST:
2780e9cfb251SMatthias Ringwald                     if (cmd_len < 4){
2781e9cfb251SMatthias Ringwald                         // command incomplete
2782e9cfb251SMatthias Ringwald                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2783e9cfb251SMatthias Ringwald                         break;
2784e9cfb251SMatthias Ringwald                     }
278528ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
2786ae280e73Smatthias.ringwald                     l2cap_signaling_handle_configure_request(channel, command);
278763a7246aSmatthias.ringwald                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
278863a7246aSmatthias.ringwald                         // only done if continuation not set
278963a7246aSmatthias.ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
279063a7246aSmatthias.ringwald                     }
2791ae280e73Smatthias.ringwald                     break;
27921e6aba47Smatthias.ringwald                 case CONFIGURE_RESPONSE:
2793e9cfb251SMatthias Ringwald                     if (cmd_len < 6){
2794e9cfb251SMatthias Ringwald                         // command incomplete
2795e9cfb251SMatthias Ringwald                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2796e9cfb251SMatthias Ringwald                         break;
2797e9cfb251SMatthias Ringwald                     }
2798e9cfb251SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
27995932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2800f2fa388dSMatthias Ringwald                     l2cap_signaling_handle_configure_response(channel, result, command);
28015932bd7cS[email protected]                     switch (result){
28025932bd7cS[email protected]                         case 0: // success
28035932bd7cS[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
28045932bd7cS[email protected]                             break;
28055932bd7cS[email protected]                         case 4: // pending
28065932bd7cS[email protected]                             l2cap_start_ertx(channel);
28075932bd7cS[email protected]                             break;
28085932bd7cS[email protected]                         default:
2809a32d6a03SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2810a32d6a03SMatthias Ringwald                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
2811a32d6a03SMatthias Ringwald                                 // remote does not offer ertm but it's required
2812a32d6a03SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2813a32d6a03SMatthias Ringwald                                 break;
2814a32d6a03SMatthias Ringwald                             }
2815a32d6a03SMatthias Ringwald #endif
2816fe9d8984S[email protected]                             // retry on negative result
2817fe9d8984S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2818fe9d8984S[email protected]                             break;
2819fe9d8984S[email protected]                     }
28205a67bd4aSmatthias.ringwald                     break;
28215a67bd4aSmatthias.ringwald                 default:
28225a67bd4aSmatthias.ringwald                     break;
28231e6aba47Smatthias.ringwald             }
2824fa8473a4Smatthias.ringwald             if (l2cap_channel_ready_for_open(channel)){
28252e4c1850SMatthias Ringwald 
28262e4c1850SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
28272e4c1850SMatthias Ringwald                 // assert that packet can be stored in fragment buffers in ertm
28282e4c1850SMatthias Ringwald                 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
28292e4c1850SMatthias Ringwald                     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
28302e4c1850SMatthias Ringwald                     uint16_t usable_mtu = channel->num_tx_buffers == 1 ? effective_mps : channel->num_tx_buffers * effective_mps - 2;
28312e4c1850SMatthias Ringwald                     if (usable_mtu < channel->remote_mtu){
28322e4c1850SMatthias Ringwald                         log_info("Remote MTU %u > max storable ERTM packet, only using MTU = %u", channel->remote_mtu, usable_mtu);
28332e4c1850SMatthias Ringwald                         channel->remote_mtu = usable_mtu;
28342e4c1850SMatthias Ringwald                     }
28352e4c1850SMatthias Ringwald                 }
28362e4c1850SMatthias Ringwald #endif
2837fa8473a4Smatthias.ringwald                 // for open:
28385a67bd4aSmatthias.ringwald                 channel->state = L2CAP_STATE_OPEN;
2839fa8473a4Smatthias.ringwald                 l2cap_emit_channel_opened(channel, 0);
2840c8e4258aSmatthias.ringwald             }
2841c8e4258aSmatthias.ringwald             break;
2842f62db1e3Smatthias.ringwald 
2843f62db1e3Smatthias.ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
2844f62db1e3Smatthias.ringwald             switch (code) {
2845f62db1e3Smatthias.ringwald                 case DISCONNECTION_RESPONSE:
284627a923d0Smatthias.ringwald                     l2cap_finialize_channel_close(channel);
284727a923d0Smatthias.ringwald                     break;
28485a67bd4aSmatthias.ringwald                 default:
28495a67bd4aSmatthias.ringwald                     //@TODO: implement other signaling packets
28505a67bd4aSmatthias.ringwald                     break;
285127a923d0Smatthias.ringwald             }
285227a923d0Smatthias.ringwald             break;
285384836b65Smatthias.ringwald 
285484836b65Smatthias.ringwald         case L2CAP_STATE_CLOSED:
285584836b65Smatthias.ringwald             // @TODO handle incoming requests
285684836b65Smatthias.ringwald             break;
285784836b65Smatthias.ringwald 
285884836b65Smatthias.ringwald         case L2CAP_STATE_OPEN:
285984836b65Smatthias.ringwald             //@TODO: implement other signaling packets, e.g. re-configure
286084836b65Smatthias.ringwald             break;
286110642e45Smatthias.ringwald         default:
286210642e45Smatthias.ringwald             break;
286327a923d0Smatthias.ringwald     }
28649da54300S[email protected]     // log_info("new state %u", channel->state);
286527a923d0Smatthias.ringwald }
286627a923d0Smatthias.ringwald 
286700d93d79Smatthias.ringwald 
2868ed2ed8e1SMatthias Ringwald // @pre command len is valid, see check in l2cap_acl_classic_handler
28697f02f414SMatthias Ringwald static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
287000d93d79Smatthias.ringwald 
28711b9cb13dSMatthias Ringwald     btstack_linked_list_iterator_t it;
28721b9cb13dSMatthias Ringwald 
287300d93d79Smatthias.ringwald     // get code, signalind identifier and command len
287400d93d79Smatthias.ringwald     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
287500d93d79Smatthias.ringwald     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
28760493bf3aSMatthias Ringwald     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
287700d93d79Smatthias.ringwald 
28781b9cb13dSMatthias Ringwald     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
2879505f1c30SMatthias Ringwald     if ((code < 1) || (code == ECHO_RESPONSE) || (code > INFORMATION_RESPONSE)){
2880e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
288100d93d79Smatthias.ringwald         return;
288200d93d79Smatthias.ringwald     }
288300d93d79Smatthias.ringwald 
288400d93d79Smatthias.ringwald     // general commands without an assigned channel
288500d93d79Smatthias.ringwald     switch(code) {
288600d93d79Smatthias.ringwald 
28870493bf3aSMatthias Ringwald         case CONNECTION_REQUEST:
28880493bf3aSMatthias Ringwald             if (cmd_len == 4){
2889f8fbdce0SMatthias Ringwald                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2890f8fbdce0SMatthias Ringwald                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
289100d93d79Smatthias.ringwald                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
28920493bf3aSMatthias Ringwald             } else {
28930493bf3aSMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
289400d93d79Smatthias.ringwald             }
28950493bf3aSMatthias Ringwald             return;
289600d93d79Smatthias.ringwald 
28972b360848Smatthias.ringwald         case ECHO_REQUEST:
2898e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
28992b83fb7dSmatthias.ringwald             return;
290000d93d79Smatthias.ringwald 
29010493bf3aSMatthias Ringwald         case INFORMATION_REQUEST:
29020493bf3aSMatthias Ringwald             if (cmd_len == 2) {
29033e64cb44SMatthias Ringwald                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
29043e64cb44SMatthias Ringwald                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
29050493bf3aSMatthias Ringwald             } else {
29060493bf3aSMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
290700d93d79Smatthias.ringwald             }
29080493bf3aSMatthias Ringwald             return;
290900d93d79Smatthias.ringwald 
29101b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
29111b9cb13dSMatthias Ringwald         case INFORMATION_RESPONSE: {
29121b9cb13dSMatthias Ringwald             hci_connection_t * connection = hci_connection_for_handle(handle);
29131b9cb13dSMatthias Ringwald             if (!connection) return;
29140defadfbSMatthias Ringwald             if (connection->l2cap_state.information_state != L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE) return;
29150defadfbSMatthias Ringwald 
29160defadfbSMatthias Ringwald             // get extended features from response if valid
29170defadfbSMatthias Ringwald             connection->l2cap_state.extended_feature_mask = 0;
29180defadfbSMatthias Ringwald             if (cmd_len >= 6) {
29191b9cb13dSMatthias Ringwald                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
29201b9cb13dSMatthias Ringwald                 uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
29210defadfbSMatthias Ringwald                 if (result == 0 && info_type == L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) {
29221b9cb13dSMatthias Ringwald                     connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
29230defadfbSMatthias Ringwald                 }
29240defadfbSMatthias Ringwald             }
29250defadfbSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
2926543b84e4SMatthias Ringwald             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
29270defadfbSMatthias Ringwald 
29281b9cb13dSMatthias Ringwald             // trigger connection request
29291b9cb13dSMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
29301b9cb13dSMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
29311b9cb13dSMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2932fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2933543b84e4SMatthias Ringwald                 if (channel->con_handle != handle) continue;
2934f8ecb114SMatthias Ringwald 
2935f8ecb114SMatthias Ringwald                 // incoming connection: ask user for channel configuration, esp. if ertm will be mandatory
2936f8ecb114SMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
2937f8ecb114SMatthias Ringwald                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2938f8ecb114SMatthias Ringwald                     l2cap_emit_incoming_connection(channel);
2939f8ecb114SMatthias Ringwald                     continue;
2940f8ecb114SMatthias Ringwald                 }
2941f8ecb114SMatthias Ringwald 
2942f8ecb114SMatthias Ringwald                 // outgoing connection
2943f8ecb114SMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
2944f8ecb114SMatthias Ringwald 
2945dae3b2abSMatthias Ringwald                     // if ERTM was requested, but is not listed in extended feature mask:
2946543b84e4SMatthias Ringwald                     if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2947dae3b2abSMatthias Ringwald 
2948f073f086SMatthias Ringwald                         if (channel->ertm_mandatory){
2949dae3b2abSMatthias Ringwald                             // bail if ERTM is mandatory
2950543b84e4SMatthias Ringwald                             channel->state = L2CAP_STATE_CLOSED;
2951543b84e4SMatthias Ringwald                             // map l2cap connection response result to BTstack status enumeration
295266a72640SMatthias Ringwald                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
2953543b84e4SMatthias Ringwald                             // discard channel
2954543b84e4SMatthias Ringwald                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2955c45d6b2cSMatthias Ringwald                             l2cap_free_channel_entry(channel);
2956543b84e4SMatthias Ringwald                             continue;
2957dae3b2abSMatthias Ringwald 
2958f073f086SMatthias Ringwald                         } else {
2959f073f086SMatthias Ringwald                             // fallback to Basic mode
296066a72640SMatthias Ringwald                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
2961f073f086SMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2962f073f086SMatthias Ringwald                         }
2963dae3b2abSMatthias Ringwald                     }
2964f8ecb114SMatthias Ringwald 
296552606043SMatthias Ringwald                     // respond to connection request
2966f8ecb114SMatthias Ringwald                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
2967f8ecb114SMatthias Ringwald                     continue;
296852606043SMatthias Ringwald                 }
29691b9cb13dSMatthias Ringwald             }
29701b9cb13dSMatthias Ringwald             return;
29711b9cb13dSMatthias Ringwald         }
29721b9cb13dSMatthias Ringwald #endif
29731b9cb13dSMatthias Ringwald 
297400d93d79Smatthias.ringwald         default:
297500d93d79Smatthias.ringwald             break;
297600d93d79Smatthias.ringwald     }
297700d93d79Smatthias.ringwald 
297800d93d79Smatthias.ringwald     // Get potential destination CID
2979f8fbdce0SMatthias Ringwald     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
298000d93d79Smatthias.ringwald 
298100d93d79Smatthias.ringwald     // Find channel for this sig_id and connection handle
2982665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2983665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2984665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2985fad84cafSMatthias Ringwald         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2986fc64f94aSMatthias Ringwald         if (channel->con_handle != handle) continue;
298700d93d79Smatthias.ringwald         if (code & 1) {
2988b1988dceSmatthias.ringwald             // match odd commands (responses) by previous signaling identifier
2989b1988dceSmatthias.ringwald             if (channel->local_sig_id == sig_id) {
299000d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
29914e32727eSmatthias.ringwald                 break;
299200d93d79Smatthias.ringwald             }
299300d93d79Smatthias.ringwald         } else {
2994b1988dceSmatthias.ringwald             // match even commands (requests) by local channel id
299500d93d79Smatthias.ringwald             if (channel->local_cid == dest_cid) {
299600d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
29974e32727eSmatthias.ringwald                 break;
299800d93d79Smatthias.ringwald             }
299900d93d79Smatthias.ringwald         }
300000d93d79Smatthias.ringwald     }
300100d93d79Smatthias.ringwald }
300209e9d05bSMatthias Ringwald #endif
300300d93d79Smatthias.ringwald 
3004e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
300509e9d05bSMatthias Ringwald 
300609e9d05bSMatthias Ringwald static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
300709e9d05bSMatthias Ringwald     uint8_t event[6];
300809e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
300909e9d05bSMatthias Ringwald     event[1] = 4;
301009e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
301109e9d05bSMatthias Ringwald     little_endian_store_16(event, 4, result);
301209e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
301309e9d05bSMatthias Ringwald     if (!l2cap_event_packet_handler) return;
301409e9d05bSMatthias Ringwald     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
301509e9d05bSMatthias Ringwald }
301609e9d05bSMatthias Ringwald 
3017c48b2a2cSMatthias Ringwald // @returns valid
3018c48b2a2cSMatthias Ringwald static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
3019e7d0c9aaSMatthias Ringwald     hci_connection_t * connection;
3020c48b2a2cSMatthias Ringwald     uint16_t result;
3021f299206dSMatthias Ringwald     uint8_t  event[12];
302283fd9c76SMatthias Ringwald 
3023cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
3024a3dc965aSMatthias Ringwald     btstack_linked_list_iterator_t it;
3025a3dc965aSMatthias Ringwald     l2cap_channel_t * channel;
3026a3dc965aSMatthias Ringwald     uint16_t local_cid;
302783fd9c76SMatthias Ringwald     uint16_t le_psm;
302863f0ac45SMatthias Ringwald     uint16_t new_credits;
302963f0ac45SMatthias Ringwald     uint16_t credits_before;
3030e7d0c9aaSMatthias Ringwald     l2cap_service_t * service;
303111cae19eSMilanka Ringwald     uint16_t source_cid;
303283fd9c76SMatthias Ringwald #endif
303300d93d79Smatthias.ringwald 
30341b8b8d05SMatthias Ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3035adcfabadSMatthias Ringwald     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
30361fcd10b7SMatthias Ringwald     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
30371b8b8d05SMatthias Ringwald 
30381b8b8d05SMatthias Ringwald     switch (code){
303900d93d79Smatthias.ringwald 
3040c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_REQUEST:
3041adcfabadSMatthias Ringwald             // check size
30421fcd10b7SMatthias Ringwald             if (len < 8) return 0;
3043e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
3044da886c03S[email protected]             if (connection){
30456d91fb6cSMatthias Ringwald                 if (connection->role != HCI_ROLE_MASTER){
30466d91fb6cSMatthias Ringwald                     // reject command without notifying upper layer when not in master role
3047c48b2a2cSMatthias Ringwald                     return 0;
30486d91fb6cSMatthias Ringwald                 }
3049a4c06b28SMatthias Ringwald                 le_connection_parameter_range_t existing_range;
30504ced4e8cSMatthias Ringwald                 gap_get_connection_parameter_range(&existing_range);
3051d5e694a3SMatthias Ringwald                 uint16_t le_conn_interval_min   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3052d5e694a3SMatthias Ringwald                 uint16_t le_conn_interval_max   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3053d5e694a3SMatthias Ringwald                 uint16_t le_conn_latency        = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3054d5e694a3SMatthias Ringwald                 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
3055da886c03S[email protected] 
305673cd8a2aSMatthias 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);
3057da886c03S[email protected]                 if (update_parameter){
3058da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
3059da886c03S[email protected]                     connection->le_conn_interval_min = le_conn_interval_min;
3060da886c03S[email protected]                     connection->le_conn_interval_max = le_conn_interval_max;
3061da886c03S[email protected]                     connection->le_conn_latency = le_conn_latency;
3062da886c03S[email protected]                     connection->le_supervision_timeout = le_supervision_timeout;
3063da886c03S[email protected]                 } else {
3064da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
3065da886c03S[email protected]                 }
3066c48b2a2cSMatthias Ringwald                 connection->le_con_param_update_identifier = sig_id;
3067da886c03S[email protected]             }
3068da886c03S[email protected] 
306933c40538SMatthias Ringwald             if (!l2cap_event_packet_handler) break;
3070c48b2a2cSMatthias Ringwald 
3071c48b2a2cSMatthias Ringwald             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
3072c48b2a2cSMatthias Ringwald             event[1] = 8;
3073f299206dSMatthias Ringwald             little_endian_store_16(event, 2, handle);
30746535961aSMatthias Ringwald             (void)memcpy(&event[4], &command[4], 8);
3075c48b2a2cSMatthias Ringwald             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
307633c40538SMatthias Ringwald             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
3077ccf076adS[email protected]             break;
3078c48b2a2cSMatthias Ringwald 
30791fcd10b7SMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
30801fcd10b7SMatthias Ringwald             // check size
30811fcd10b7SMatthias Ringwald             if (len < 2) return 0;
30821fcd10b7SMatthias Ringwald             result = little_endian_read_16(command, 4);
30831fcd10b7SMatthias Ringwald             l2cap_emit_connection_parameter_update_response(handle, result);
30841fcd10b7SMatthias Ringwald             break;
30851fcd10b7SMatthias Ringwald 
3086a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
3087a3dc965aSMatthias Ringwald 
308863f0ac45SMatthias Ringwald         case COMMAND_REJECT:
308963f0ac45SMatthias Ringwald             // Find channel for this sig_id and connection handle
309063f0ac45SMatthias Ringwald             channel = NULL;
3091421cb104SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
309263f0ac45SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
309363f0ac45SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3094fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
309563f0ac45SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
309663f0ac45SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
309763f0ac45SMatthias Ringwald                 channel = a_channel;
309863f0ac45SMatthias Ringwald                 break;
309963f0ac45SMatthias Ringwald             }
310063f0ac45SMatthias Ringwald             if (!channel) break;
310163f0ac45SMatthias Ringwald 
310263f0ac45SMatthias Ringwald             // if received while waiting for le connection response, assume legacy device
310363f0ac45SMatthias Ringwald             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
310463f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
310563f0ac45SMatthias Ringwald                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
310644276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0x0002);
310763f0ac45SMatthias Ringwald 
310863f0ac45SMatthias Ringwald                 // discard channel
3109421cb104SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3110c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
311163f0ac45SMatthias Ringwald                 break;
311263f0ac45SMatthias Ringwald             }
311363f0ac45SMatthias Ringwald             break;
311463f0ac45SMatthias Ringwald 
3115e7d0c9aaSMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_REQUEST:
3116adcfabadSMatthias Ringwald             // check size
3117adcfabadSMatthias Ringwald             if (len < 10) return 0;
3118e7d0c9aaSMatthias Ringwald 
3119e7d0c9aaSMatthias Ringwald             // get hci connection, bail if not found (must not happen)
3120e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
3121e7d0c9aaSMatthias Ringwald             if (!connection) return 0;
3122e7d0c9aaSMatthias Ringwald 
3123e7d0c9aaSMatthias Ringwald             // check if service registered
3124e7d0c9aaSMatthias Ringwald             le_psm  = little_endian_read_16(command, 4);
3125e7d0c9aaSMatthias Ringwald             service = l2cap_le_get_service(le_psm);
312611cae19eSMilanka Ringwald             source_cid = little_endian_read_16(command, 6);
3127e7d0c9aaSMatthias Ringwald 
3128e7d0c9aaSMatthias Ringwald             if (service){
3129e7d0c9aaSMatthias Ringwald                 if (source_cid < 0x40){
3130e7d0c9aaSMatthias Ringwald                     // 0x0009 Connection refused - Invalid Source CID
3131e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
3132e7d0c9aaSMatthias Ringwald                     return 1;
3133e7d0c9aaSMatthias Ringwald                 }
3134e7d0c9aaSMatthias Ringwald 
3135e7d0c9aaSMatthias Ringwald                 // go through list of channels for this ACL connection and check if we get a match
3136421cb104SMatthias Ringwald                 btstack_linked_list_iterator_init(&it, &l2cap_channels);
3137e7d0c9aaSMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&it)){
31381b8b8d05SMatthias Ringwald                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3139fad84cafSMatthias Ringwald                     if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
31401b8b8d05SMatthias Ringwald                     if (a_channel->con_handle != handle) continue;
31411b8b8d05SMatthias Ringwald                     if (a_channel->remote_cid != source_cid) continue;
3142e7d0c9aaSMatthias Ringwald                     // 0x000a Connection refused - Source CID already allocated
3143e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
3144e7d0c9aaSMatthias Ringwald                     return 1;
3145e7d0c9aaSMatthias Ringwald                 }
3146e7d0c9aaSMatthias Ringwald 
314783fd9c76SMatthias Ringwald                 // security: check encryption
314883fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_2){
31499c6e867eSMatthias Ringwald                     if (gap_encryption_key_size(handle) == 0){
315083fd9c76SMatthias Ringwald                         // 0x0008 Connection refused - insufficient encryption
3151e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
315283fd9c76SMatthias Ringwald                         return 1;
315383fd9c76SMatthias Ringwald                     }
315483fd9c76SMatthias Ringwald                     // anything less than 16 byte key size is insufficient
31559c6e867eSMatthias Ringwald                     if (gap_encryption_key_size(handle) < 16){
315683fd9c76SMatthias Ringwald                         // 0x0007 Connection refused – insufficient encryption key size
3157e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
315883fd9c76SMatthias Ringwald                         return 1;
315983fd9c76SMatthias Ringwald                     }
316083fd9c76SMatthias Ringwald                 }
316183fd9c76SMatthias Ringwald 
316283fd9c76SMatthias Ringwald                 // security: check authencation
316383fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_3){
31649c6e867eSMatthias Ringwald                     if (!gap_authenticated(handle)){
316583fd9c76SMatthias Ringwald                         // 0x0005 Connection refused – insufficient authentication
3166e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
316783fd9c76SMatthias Ringwald                         return 1;
316883fd9c76SMatthias Ringwald                     }
316983fd9c76SMatthias Ringwald                 }
317083fd9c76SMatthias Ringwald 
317183fd9c76SMatthias Ringwald                 // security: check authorization
317283fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_4){
31739c6e867eSMatthias Ringwald                     if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
317483fd9c76SMatthias Ringwald                         // 0x0006 Connection refused – insufficient authorization
3175e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
317683fd9c76SMatthias Ringwald                         return 1;
317783fd9c76SMatthias Ringwald                     }
317883fd9c76SMatthias Ringwald                 }
3179e7d0c9aaSMatthias Ringwald 
3180e7d0c9aaSMatthias Ringwald                 // allocate channel
31815d18f623SMatthias Ringwald                 channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL, connection->address,
3182e7d0c9aaSMatthias Ringwald                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
3183e7d0c9aaSMatthias Ringwald                 if (!channel){
3184e7d0c9aaSMatthias Ringwald                     // 0x0004 Connection refused – no resources available
3185e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
3186e7d0c9aaSMatthias Ringwald                     return 1;
3187e7d0c9aaSMatthias Ringwald                 }
3188e7d0c9aaSMatthias Ringwald 
3189e7d0c9aaSMatthias Ringwald                 channel->con_handle = handle;
3190e7d0c9aaSMatthias Ringwald                 channel->remote_cid = source_cid;
3191e7d0c9aaSMatthias Ringwald                 channel->remote_sig_id = sig_id;
31927f107edaSMatthias Ringwald                 channel->remote_mtu = little_endian_read_16(command, 8);
31937f107edaSMatthias Ringwald                 channel->remote_mps = little_endian_read_16(command, 10);
31947f107edaSMatthias Ringwald                 channel->credits_outgoing = little_endian_read_16(command, 12);
3195e7d0c9aaSMatthias Ringwald 
3196e7d0c9aaSMatthias Ringwald                 // set initial state
3197e7d0c9aaSMatthias Ringwald                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
3198c99bb618SMatthias Ringwald                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
3199e7d0c9aaSMatthias Ringwald 
3200e7d0c9aaSMatthias Ringwald                 // add to connections list
3201421cb104SMatthias Ringwald                 btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
3202e7d0c9aaSMatthias Ringwald 
3203e7d0c9aaSMatthias Ringwald                 // post connection request event
320444276248SMatthias Ringwald                 l2cap_emit_le_incoming_connection(channel);
3205e7d0c9aaSMatthias Ringwald 
3206e7d0c9aaSMatthias Ringwald             } else {
3207e7d0c9aaSMatthias Ringwald                 // Connection refused – LE_PSM not supported
3208e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
3209e7d0c9aaSMatthias Ringwald             }
3210e7d0c9aaSMatthias Ringwald             break;
32111b8b8d05SMatthias Ringwald 
32121b8b8d05SMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
3213adcfabadSMatthias Ringwald             // check size
3214adcfabadSMatthias Ringwald             if (len < 10) return 0;
3215adcfabadSMatthias Ringwald 
32161b8b8d05SMatthias Ringwald             // Find channel for this sig_id and connection handle
32171b8b8d05SMatthias Ringwald             channel = NULL;
3218421cb104SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
32191b8b8d05SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
32201b8b8d05SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3221fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
32221b8b8d05SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
32231b8b8d05SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
32241b8b8d05SMatthias Ringwald                 channel = a_channel;
32251b8b8d05SMatthias Ringwald                 break;
32261b8b8d05SMatthias Ringwald             }
32271b8b8d05SMatthias Ringwald             if (!channel) break;
32281b8b8d05SMatthias Ringwald 
32291b8b8d05SMatthias Ringwald             // cid + 0
32301b8b8d05SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
32311b8b8d05SMatthias Ringwald             if (result){
32321b8b8d05SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
32331b8b8d05SMatthias Ringwald                 // map l2cap connection response result to BTstack status enumeration
323444276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, result);
32351b8b8d05SMatthias Ringwald 
32361b8b8d05SMatthias Ringwald                 // discard channel
3237421cb104SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3238c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
32391b8b8d05SMatthias Ringwald                 break;
32401b8b8d05SMatthias Ringwald             }
32411b8b8d05SMatthias Ringwald 
32421b8b8d05SMatthias Ringwald             // success
32431b8b8d05SMatthias Ringwald             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
32441b8b8d05SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
32451b8b8d05SMatthias Ringwald             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
32461b8b8d05SMatthias Ringwald             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
32471b8b8d05SMatthias Ringwald             channel->state = L2CAP_STATE_OPEN;
324844276248SMatthias Ringwald             l2cap_emit_le_channel_opened(channel, result);
32491b8b8d05SMatthias Ringwald             break;
32501b8b8d05SMatthias Ringwald 
325185aeef60SMatthias Ringwald         case LE_FLOW_CONTROL_CREDIT:
3252adcfabadSMatthias Ringwald             // check size
3253adcfabadSMatthias Ringwald             if (len < 4) return 0;
3254adcfabadSMatthias Ringwald 
325585aeef60SMatthias Ringwald             // find channel
325685aeef60SMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3257421cb104SMatthias Ringwald             channel = l2cap_get_channel_for_local_cid(local_cid);
325863f0ac45SMatthias Ringwald             if (!channel) {
325963f0ac45SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
326063f0ac45SMatthias Ringwald                 break;
326163f0ac45SMatthias Ringwald             }
326263f0ac45SMatthias Ringwald             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
326363f0ac45SMatthias Ringwald             credits_before = channel->credits_outgoing;
326463f0ac45SMatthias Ringwald             channel->credits_outgoing += new_credits;
326563f0ac45SMatthias Ringwald             // check for credit overrun
326663f0ac45SMatthias Ringwald             if (credits_before > channel->credits_outgoing){
326763f0ac45SMatthias Ringwald                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
326863f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
326963f0ac45SMatthias Ringwald                 break;
327063f0ac45SMatthias Ringwald             }
327163f0ac45SMatthias Ringwald             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
327285aeef60SMatthias Ringwald             break;
327385aeef60SMatthias Ringwald 
3274828a7f7aSMatthias Ringwald         case DISCONNECTION_REQUEST:
3275adcfabadSMatthias Ringwald 
3276adcfabadSMatthias Ringwald             // check size
3277adcfabadSMatthias Ringwald             if (len < 4) return 0;
3278adcfabadSMatthias Ringwald 
3279828a7f7aSMatthias Ringwald             // find channel
3280828a7f7aSMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3281421cb104SMatthias Ringwald             channel = l2cap_get_channel_for_local_cid(local_cid);
328263f34e00SMatthias Ringwald             if (!channel) {
328363f34e00SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
328463f34e00SMatthias Ringwald                 break;
328563f34e00SMatthias Ringwald             }
3286828a7f7aSMatthias Ringwald             channel->remote_sig_id = sig_id;
3287828a7f7aSMatthias Ringwald             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
3288828a7f7aSMatthias Ringwald             break;
3289828a7f7aSMatthias Ringwald 
3290a3dc965aSMatthias Ringwald #endif
3291a3dc965aSMatthias Ringwald 
329263f0ac45SMatthias Ringwald         case DISCONNECTION_RESPONSE:
329363f0ac45SMatthias Ringwald             break;
329463f0ac45SMatthias Ringwald 
3295c48b2a2cSMatthias Ringwald         default:
3296c48b2a2cSMatthias Ringwald             // command unknown -> reject command
3297c48b2a2cSMatthias Ringwald             return 0;
3298ccf076adS[email protected]     }
3299c48b2a2cSMatthias Ringwald     return 1;
3300c48b2a2cSMatthias Ringwald }
3301e7d0c9aaSMatthias Ringwald #endif
3302c48b2a2cSMatthias Ringwald 
3303bb0a72a6SMatthias Ringwald #ifdef ENABLE_CLASSIC
33040b667d41SMatthias Ringwald static void l2cap_acl_classic_handler_for_channel(l2cap_channel_t * l2cap_channel, uint8_t * packet, uint16_t size){
330527e0774aSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
330627e0774aSMatthias Ringwald     if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
330727e0774aSMatthias Ringwald 
33086574158aSMatthias Ringwald         int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
330907c7de86SMatthias Ringwald 
33106574158aSMatthias Ringwald         // assert control + FCS fields are inside
33110b667d41SMatthias Ringwald         if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) return;
33126574158aSMatthias Ringwald 
33136574158aSMatthias Ringwald         if (l2cap_channel->fcs_option){
3314fcb125edSMatthias Ringwald             // verify FCS (required if one side requested it)
331527e0774aSMatthias Ringwald             uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
331627e0774aSMatthias Ringwald             uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
3317e288be62SMatthias Ringwald 
3318e288be62SMatthias Ringwald #ifdef L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL
3319e288be62SMatthias Ringwald             // simulate fcs error
3320e288be62SMatthias Ringwald                         static int counter = 0;
3321e288be62SMatthias Ringwald                         if (++counter == L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL) {
3322e288be62SMatthias Ringwald                             log_info("Simulate fcs error");
3323e288be62SMatthias Ringwald                             fcs_calculated++;
3324e288be62SMatthias Ringwald                             counter = 0;
3325e288be62SMatthias Ringwald                         }
3326e288be62SMatthias Ringwald #endif
3327e288be62SMatthias Ringwald 
33286574158aSMatthias Ringwald             if (fcs_calculated == fcs_packet){
33296574158aSMatthias Ringwald                 log_info("Packet FCS 0x%04x verified", fcs_packet);
33306574158aSMatthias Ringwald             } else {
333127e0774aSMatthias Ringwald                 log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
3332ef2faf56SMatthias Ringwald                 // ERTM State Machine in Bluetooth Spec does not handle 'I-Frame with invalid FCS'
33330b667d41SMatthias Ringwald                 return;
333427e0774aSMatthias Ringwald             }
33356574158aSMatthias Ringwald         }
333627e0774aSMatthias Ringwald 
333727e0774aSMatthias Ringwald         // switch on packet type
333827e0774aSMatthias Ringwald         uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
333938f62777SMatthias Ringwald         uint8_t  req_seq = (control >> 8) & 0x3f;
33402bea1b8dSMatthias Ringwald         int final = (control >> 7) & 0x01;
334127e0774aSMatthias Ringwald         if (control & 1){
334227e0774aSMatthias Ringwald             // S-Frame
334378cd8a22SMatthias Ringwald             int poll  = (control >> 4) & 0x01;
3344bdbe2e49SMatthias Ringwald             l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
33459ffcbce4SMatthias Ringwald             log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
33467b7901d8SMatthias Ringwald             l2cap_ertm_tx_packet_state_t * tx_state;
3347bdbe2e49SMatthias Ringwald             switch (s){
3348bdbe2e49SMatthias Ringwald                 case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
33499ffcbce4SMatthias Ringwald                     log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
33501e1a46bbSMatthias Ringwald                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
33513233d8abSMatthias Ringwald                     if (poll && final){
33523233d8abSMatthias Ringwald                         // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
33533233d8abSMatthias Ringwald                         log_error("P=F=1 in S-Frame");
33543233d8abSMatthias Ringwald                         break;
33553233d8abSMatthias Ringwald                     }
335678cd8a22SMatthias Ringwald                     if (poll){
3357f85ade6bSMatthias Ringwald                         // check if we did request selective retransmission before <==> we have stored SDU segments
3358f85ade6bSMatthias Ringwald                         int i;
3359f85ade6bSMatthias Ringwald                         int num_stored_out_of_order_packets = 0;
3360f85ade6bSMatthias Ringwald                         for (i=0;i<l2cap_channel->num_rx_buffers;i++){
3361f85ade6bSMatthias Ringwald                             int index = l2cap_channel->rx_store_index + i;
3362f85ade6bSMatthias Ringwald                             if (index >= l2cap_channel->num_rx_buffers){
3363f85ade6bSMatthias Ringwald                                 index -= l2cap_channel->num_rx_buffers;
3364f85ade6bSMatthias Ringwald                             }
3365f85ade6bSMatthias Ringwald                             l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3366f85ade6bSMatthias Ringwald                             if (!rx_state->valid) continue;
3367f85ade6bSMatthias Ringwald                             num_stored_out_of_order_packets++;
3368f85ade6bSMatthias Ringwald                         }
3369f85ade6bSMatthias Ringwald                         if (num_stored_out_of_order_packets){
3370f85ade6bSMatthias Ringwald                             l2cap_channel->send_supervisor_frame_selective_reject = 1;
3371f85ade6bSMatthias Ringwald                         } else {
3372d2afdd38SMatthias Ringwald                             l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
337378cd8a22SMatthias Ringwald                         }
3374f85ade6bSMatthias Ringwald                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
3375f85ade6bSMatthias Ringwald                     }
33763233d8abSMatthias Ringwald                     if (final){
3377550189ffSMatthias Ringwald                         // Stop-MonitorTimer
3378550189ffSMatthias Ringwald                         l2cap_ertm_stop_monitor_timer(l2cap_channel);
3379550189ffSMatthias Ringwald                         // If UnackedFrames > 0 then Start-RetransTimer
338094301352SMatthias Ringwald                         if (l2cap_channel->unacked_frames){
3381550189ffSMatthias Ringwald                             l2cap_ertm_start_retransmission_timer(l2cap_channel);
3382550189ffSMatthias Ringwald                         }
33833233d8abSMatthias Ringwald                         // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3384ef2faf56SMatthias Ringwald                         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
33853233d8abSMatthias Ringwald                     }
3386bdbe2e49SMatthias Ringwald                     break;
33879ffcbce4SMatthias Ringwald                 case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
33889ffcbce4SMatthias Ringwald                     log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
33891e1a46bbSMatthias Ringwald                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3390600cf12dSMatthias Ringwald                     // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
3391ef2faf56SMatthias Ringwald                     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
33929ffcbce4SMatthias Ringwald                     break;
33939ffcbce4SMatthias Ringwald                 case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
33949ffcbce4SMatthias Ringwald                     log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
33959ffcbce4SMatthias Ringwald                     break;
33969ffcbce4SMatthias Ringwald                 case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
33977b7901d8SMatthias Ringwald                     log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
33987b7901d8SMatthias Ringwald                     if (poll){
33991e1a46bbSMatthias Ringwald                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
34007b7901d8SMatthias Ringwald                     }
34017b7901d8SMatthias Ringwald                     // find requested i-frame
34027b7901d8SMatthias Ringwald                     tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
34037b7901d8SMatthias Ringwald                     if (tx_state){
34047b7901d8SMatthias Ringwald                         log_info("Retransmission for tx_seq %u requested", req_seq);
3405d2afdd38SMatthias Ringwald                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
34067b7901d8SMatthias Ringwald                         tx_state->retransmission_requested = 1;
34077b7901d8SMatthias Ringwald                         l2cap_channel->srej_active = 1;
34087b7901d8SMatthias Ringwald                     }
34099ffcbce4SMatthias Ringwald                     break;
3410bdbe2e49SMatthias Ringwald                 default:
3411bdbe2e49SMatthias Ringwald                     break;
3412bdbe2e49SMatthias Ringwald             }
341327e0774aSMatthias Ringwald         } else {
341427e0774aSMatthias Ringwald             // I-Frame
341527e0774aSMatthias Ringwald             // get control
341627e0774aSMatthias Ringwald             l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
341738f62777SMatthias Ringwald             uint8_t tx_seq = (control >> 1) & 0x3f;
341838f62777SMatthias Ringwald             log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
3419e8e9809fSMatthias Ringwald             log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
342038f62777SMatthias Ringwald             log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
34211e1a46bbSMatthias Ringwald             l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
342211b576c5SMatthias Ringwald             if (final){
342311b576c5SMatthias Ringwald                 // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3424ef2faf56SMatthias Ringwald                 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
342511b576c5SMatthias Ringwald             }
342607c7de86SMatthias Ringwald 
342707c7de86SMatthias Ringwald             // get SDU
3428826c39d0SMatthias Ringwald             const uint8_t * payload_data = &packet[COMPLETE_L2CAP_HEADER+2];
3429826c39d0SMatthias Ringwald             uint16_t        payload_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
343007c7de86SMatthias Ringwald 
343107c7de86SMatthias Ringwald             // assert SDU size is smaller or equal to our buffers
3432826c39d0SMatthias Ringwald             uint16_t max_payload_size = 0;
3433826c39d0SMatthias Ringwald             switch (sar){
3434826c39d0SMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
3435826c39d0SMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
3436826c39d0SMatthias Ringwald                     // SDU Length + MPS
3437826c39d0SMatthias Ringwald                     max_payload_size = l2cap_channel->local_mps + 2;
3438826c39d0SMatthias Ringwald                     break;
3439826c39d0SMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
3440826c39d0SMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
3441826c39d0SMatthias Ringwald                     max_payload_size = l2cap_channel->local_mps;
3442826c39d0SMatthias Ringwald                     break;
3443826c39d0SMatthias Ringwald             }
3444826c39d0SMatthias Ringwald             if (payload_len > max_payload_size){
3445826c39d0SMatthias Ringwald                 log_info("payload len %u > max payload %u -> drop packet", payload_len, max_payload_size);
34460b667d41SMatthias Ringwald                 return;
3447826c39d0SMatthias Ringwald             }
344807c7de86SMatthias Ringwald 
344938f62777SMatthias Ringwald             // check ordering
345038f62777SMatthias Ringwald             if (l2cap_channel->expected_tx_seq == tx_seq){
345138f62777SMatthias Ringwald                 log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
345238f62777SMatthias Ringwald                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3453f85ade6bSMatthias Ringwald                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3454d48432d4SMatthias Ringwald 
3455e32be409SMatthias Ringwald                 // process SDU
3456826c39d0SMatthias Ringwald                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, payload_data, payload_len);
3457d48432d4SMatthias Ringwald 
345870734707SMatthias Ringwald                 // process stored segments
3459ff3cc4a5SMatthias Ringwald                 while (true){
346070734707SMatthias Ringwald                     int index = l2cap_channel->rx_store_index;
346170734707SMatthias Ringwald                     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
346270734707SMatthias Ringwald                     if (!rx_state->valid) break;
3463f85ade6bSMatthias Ringwald 
3464f85ade6bSMatthias Ringwald                     log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
3465f85ade6bSMatthias Ringwald                     l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3466f85ade6bSMatthias Ringwald                     l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3467f85ade6bSMatthias Ringwald 
346870734707SMatthias Ringwald                     rx_state->valid = 0;
346970734707SMatthias Ringwald                     l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
3470f85ade6bSMatthias Ringwald 
3471f85ade6bSMatthias Ringwald                     // update rx store index
347270734707SMatthias Ringwald                     index++;
347370734707SMatthias Ringwald                     if (index >= l2cap_channel->num_rx_buffers){
347470734707SMatthias Ringwald                         index = 0;
347570734707SMatthias Ringwald                     }
347670734707SMatthias Ringwald                     l2cap_channel->rx_store_index = index;
347770734707SMatthias Ringwald                 }
347870734707SMatthias Ringwald 
3479f85ade6bSMatthias Ringwald                 //
3480f85ade6bSMatthias Ringwald                 l2cap_channel->send_supervisor_frame_receiver_ready = 1;
3481f85ade6bSMatthias Ringwald 
3482c7309e8dSMatthias Ringwald             } else {
3483df2191a7SMatthias Ringwald                 int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
3484df2191a7SMatthias Ringwald                 if (delta < 2){
348570734707SMatthias Ringwald                     // store segment
3486826c39d0SMatthias Ringwald                     l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, payload_data, payload_len);
348770734707SMatthias Ringwald 
3488df2191a7SMatthias Ringwald                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
3489df2191a7SMatthias Ringwald                     l2cap_channel->send_supervisor_frame_selective_reject = 1;
3490df2191a7SMatthias Ringwald                 } else {
3491df2191a7SMatthias Ringwald                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
3492c7309e8dSMatthias Ringwald                     l2cap_channel->send_supervisor_frame_reject = 1;
349327e0774aSMatthias Ringwald                 }
349438f62777SMatthias Ringwald             }
3495df2191a7SMatthias Ringwald         }
34960b667d41SMatthias Ringwald         return;
349727e0774aSMatthias Ringwald     }
349827e0774aSMatthias Ringwald #endif
34993d50b4baSMatthias Ringwald     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
35000b667d41SMatthias Ringwald 
35010b667d41SMatthias Ringwald }
35020b667d41SMatthias Ringwald #endif
35030b667d41SMatthias Ringwald 
35040b667d41SMatthias Ringwald static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
35050b667d41SMatthias Ringwald #ifdef ENABLE_CLASSIC
35060b667d41SMatthias Ringwald     l2cap_channel_t * l2cap_channel;
35070b667d41SMatthias Ringwald     l2cap_fixed_channel_t * l2cap_fixed_channel;
35080b667d41SMatthias Ringwald 
35090b667d41SMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
35100b667d41SMatthias Ringwald     switch (channel_id) {
35110b667d41SMatthias Ringwald 
35120b667d41SMatthias Ringwald         case L2CAP_CID_SIGNALING: {
35130b667d41SMatthias Ringwald             uint32_t command_offset = 8;
35140b667d41SMatthias Ringwald             while ((command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET) < size) {
35150b667d41SMatthias Ringwald                 // assert signaling command is fully inside packet
35160b667d41SMatthias Ringwald                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
35170b667d41SMatthias Ringwald                 uint32_t next_command_offset = command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
35180b667d41SMatthias Ringwald                 if (next_command_offset > size){
35190b667d41SMatthias Ringwald                     log_error("l2cap signaling command len invalid -> drop");
35200b667d41SMatthias Ringwald                     break;
35210b667d41SMatthias Ringwald                 }
35220b667d41SMatthias Ringwald                 // handle signaling command
35230b667d41SMatthias Ringwald                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
35240b667d41SMatthias Ringwald                 // go to next command
35250b667d41SMatthias Ringwald                 command_offset = next_command_offset;
35260b667d41SMatthias Ringwald             }
35270b667d41SMatthias Ringwald             break;
35280b667d41SMatthias Ringwald         }
35290b667d41SMatthias Ringwald         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
35300b667d41SMatthias Ringwald             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL);
35310b667d41SMatthias Ringwald             if (!l2cap_fixed_channel) break;
35320b667d41SMatthias Ringwald             if (!l2cap_fixed_channel->packet_handler) break;
35330b667d41SMatthias Ringwald             (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
35340b667d41SMatthias Ringwald             break;
35350b667d41SMatthias Ringwald 
35360b667d41SMatthias Ringwald         default:
35370b667d41SMatthias Ringwald             // Find channel for this channel_id and connection handle
35380b667d41SMatthias Ringwald             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
35390b667d41SMatthias Ringwald             if (l2cap_channel) {
35400b667d41SMatthias Ringwald                 l2cap_acl_classic_handler_for_channel(l2cap_channel, packet, size);
354100d93d79Smatthias.ringwald             }
3542bb0a72a6SMatthias Ringwald             break;
3543bb0a72a6SMatthias Ringwald     }
3544bb0a72a6SMatthias Ringwald #else
3545bb0a72a6SMatthias Ringwald     UNUSED(handle); // ok: no code
3546bb0a72a6SMatthias Ringwald     UNUSED(packet); // ok: no code
3547bb0a72a6SMatthias Ringwald     UNUSED(size);   // ok: no code
354809e9d05bSMatthias Ringwald #endif
3549bb0a72a6SMatthias Ringwald }
3550bb0a72a6SMatthias Ringwald 
3551bb0a72a6SMatthias Ringwald static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3552bb0a72a6SMatthias Ringwald #ifdef ENABLE_BLE
3553bb0a72a6SMatthias Ringwald 
3554fad84cafSMatthias Ringwald     l2cap_fixed_channel_t * l2cap_fixed_channel;
3555fad84cafSMatthias Ringwald 
3556bb0a72a6SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
3557bb0a72a6SMatthias Ringwald     l2cap_channel_t * l2cap_channel;
3558bb0a72a6SMatthias Ringwald #endif
3559bb0a72a6SMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3560bb0a72a6SMatthias Ringwald     switch (channel_id) {
3561bb0a72a6SMatthias Ringwald 
3562bb0a72a6SMatthias Ringwald         case L2CAP_CID_SIGNALING_LE: {
3563bb0a72a6SMatthias Ringwald             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
3564adcfabadSMatthias Ringwald             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
3565505f1c30SMatthias Ringwald             if ((COMPLETE_L2CAP_HEADER + 4 + len) > size) break;
3566bb0a72a6SMatthias Ringwald             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
3567bb0a72a6SMatthias Ringwald             if (!valid){
3568bb0a72a6SMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3569bb0a72a6SMatthias Ringwald             }
3570bb0a72a6SMatthias Ringwald             break;
3571bb0a72a6SMatthias Ringwald         }
3572bb0a72a6SMatthias Ringwald 
3573bb0a72a6SMatthias Ringwald         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
3574fad84cafSMatthias Ringwald             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL);
3575fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel) break;
3576fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel->packet_handler) break;
3577fad84cafSMatthias Ringwald             (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3578bb0a72a6SMatthias Ringwald             break;
3579bb0a72a6SMatthias Ringwald 
3580bb0a72a6SMatthias Ringwald         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
3581fad84cafSMatthias Ringwald             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
3582fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel) break;
3583fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel->packet_handler) break;
3584fad84cafSMatthias Ringwald             (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3585bb0a72a6SMatthias Ringwald             break;
3586bb0a72a6SMatthias Ringwald 
3587bb0a72a6SMatthias Ringwald         default:
3588bb0a72a6SMatthias Ringwald 
3589a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
3590421cb104SMatthias Ringwald             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
359164e11ca9SMatthias Ringwald             if (l2cap_channel) {
359285aeef60SMatthias Ringwald                 // credit counting
359385aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming == 0){
359485aeef60SMatthias Ringwald                     log_error("LE Data Channel packet received but no incoming credits");
359585aeef60SMatthias Ringwald                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
359685aeef60SMatthias Ringwald                     break;
359785aeef60SMatthias Ringwald                 }
359885aeef60SMatthias Ringwald                 l2cap_channel->credits_incoming--;
359985aeef60SMatthias Ringwald 
360085aeef60SMatthias Ringwald                 // automatic credits
3601c1ab6cc1SMatthias Ringwald                 if ((l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK) && l2cap_channel->automatic_credits){
360285aeef60SMatthias Ringwald                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
360385aeef60SMatthias Ringwald                 }
360485aeef60SMatthias Ringwald 
3605cd529728SMatthias Ringwald                 // first fragment
3606cd529728SMatthias Ringwald                 uint16_t pos = 0;
3607cd529728SMatthias Ringwald                 if (!l2cap_channel->receive_sdu_len){
3608bb98c113SMatthias Ringwald                     uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3609bb98c113SMatthias Ringwald                     if(sdu_len > l2cap_channel->local_mtu) break;   // SDU would be larger than our buffer
3610bb98c113SMatthias Ringwald                     l2cap_channel->receive_sdu_len = sdu_len;
3611cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_pos = 0;
3612cd529728SMatthias Ringwald                     pos  += 2;
3613cd529728SMatthias Ringwald                     size -= 2;
3614cd529728SMatthias Ringwald                 }
3615bb98c113SMatthias Ringwald                 uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
3616bb98c113SMatthias Ringwald                 uint16_t remaining_space = l2cap_channel->local_mtu - l2cap_channel->receive_sdu_pos;
3617bb98c113SMatthias Ringwald                 if (fragment_size > remaining_space) break;         // SDU would cause buffer overrun
36186535961aSMatthias Ringwald                 (void)memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos],
36196535961aSMatthias Ringwald                              &packet[COMPLETE_L2CAP_HEADER + pos],
36206535961aSMatthias Ringwald                              fragment_size);
3621cd529728SMatthias Ringwald                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
3622cd529728SMatthias Ringwald                 // done?
3623895ff4a5SMatthias Ringwald                 log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
3624cd529728SMatthias Ringwald                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
3625cd529728SMatthias Ringwald                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
3626cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = 0;
3627cd529728SMatthias Ringwald                 }
362863f0ac45SMatthias Ringwald             } else {
362963f0ac45SMatthias Ringwald                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
363064e11ca9SMatthias Ringwald             }
363164e11ca9SMatthias Ringwald #endif
36325652b5ffS[email protected]             break;
36335652b5ffS[email protected]     }
3634bb0a72a6SMatthias Ringwald #else
3635bb0a72a6SMatthias Ringwald     UNUSED(handle); // ok: no code
3636bb0a72a6SMatthias Ringwald     UNUSED(packet); // ok: no code
3637bb0a72a6SMatthias Ringwald     UNUSED(size);   // ok: no code
3638bb0a72a6SMatthias Ringwald #endif
3639bb0a72a6SMatthias Ringwald }
3640bb0a72a6SMatthias Ringwald 
3641bb0a72a6SMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
3642bb0a72a6SMatthias Ringwald     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
3643bb0a72a6SMatthias Ringwald     UNUSED(channel);        // ok: there is no channel
3644bb0a72a6SMatthias Ringwald 
3645adcfabadSMatthias Ringwald     // Assert full L2CAP header present
3646adcfabadSMatthias Ringwald     if (size < COMPLETE_L2CAP_HEADER) return;
3647adcfabadSMatthias Ringwald 
3648f16129ceSMatthias Ringwald     // Dispatch to Classic or LE handler (SCO packets are not dispatched to L2CAP)
3649bb0a72a6SMatthias Ringwald     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
3650bb0a72a6SMatthias Ringwald     hci_connection_t *conn = hci_connection_for_handle(handle);
3651bb0a72a6SMatthias Ringwald     if (!conn) return;
3652f16129ceSMatthias Ringwald     if (conn->address_type == BD_ADDR_TYPE_ACL){
3653bb0a72a6SMatthias Ringwald         l2cap_acl_classic_handler(handle, packet, size);
3654bb0a72a6SMatthias Ringwald     } else {
3655bb0a72a6SMatthias Ringwald         l2cap_acl_le_handler(handle, packet, size);
3656bb0a72a6SMatthias Ringwald     }
365700d93d79Smatthias.ringwald 
36581eb2563eS[email protected]     l2cap_run();
36592718e2e7Smatthias.ringwald }
366000d93d79Smatthias.ringwald 
366109e9d05bSMatthias Ringwald // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
366209e9d05bSMatthias Ringwald void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
3663fad84cafSMatthias Ringwald     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
3664fad84cafSMatthias Ringwald     if (!channel) return;
3665fad84cafSMatthias Ringwald     channel->packet_handler = the_packet_handler;
366609e9d05bSMatthias Ringwald }
366709e9d05bSMatthias Ringwald 
366809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
366915ec09bbSmatthias.ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
367027a923d0Smatthias.ringwald void l2cap_finialize_channel_close(l2cap_channel_t * channel){
3671f62db1e3Smatthias.ringwald     channel->state = L2CAP_STATE_CLOSED;
367266a72640SMatthias Ringwald     l2cap_handle_channel_closed(channel);
3673f62db1e3Smatthias.ringwald     // discard channel
3674665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3675c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
3676c8e4258aSmatthias.ringwald }
367713aa3e4bSMatthias Ringwald #endif
36781e6aba47Smatthias.ringwald 
367913aa3e4bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
36808f2a52f4SMatthias Ringwald static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3681665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
3682665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, services);
3683665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
3684665d90f2SMatthias Ringwald         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
36859d9bbc01Smatthias.ringwald         if ( service->psm == psm){
36869d9bbc01Smatthias.ringwald             return service;
36879d9bbc01Smatthias.ringwald         };
36889d9bbc01Smatthias.ringwald     }
36899d9bbc01Smatthias.ringwald     return NULL;
36909d9bbc01Smatthias.ringwald }
369113aa3e4bSMatthias Ringwald #endif
36929d9bbc01Smatthias.ringwald 
369313aa3e4bSMatthias Ringwald #ifdef ENABLE_CLASSIC
36947192e786SMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
36957192e786SMatthias Ringwald     return l2cap_get_service_internal(&l2cap_services, psm);
36967192e786SMatthias Ringwald }
36977192e786SMatthias Ringwald 
3698be2053a6SMatthias 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){
3699be2053a6SMatthias Ringwald 
3700be2053a6SMatthias Ringwald     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
3701e0abb8e7S[email protected] 
37024bb582b6Smatthias.ringwald     // check for alread registered psm
37039d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
3704277abc2cSmatthias.ringwald     if (service) {
3705be2053a6SMatthias Ringwald         log_error("l2cap_register_service: PSM %u already registered", psm);
3706be2053a6SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
3707277abc2cSmatthias.ringwald     }
37089d9bbc01Smatthias.ringwald 
37094bb582b6Smatthias.ringwald     // alloc structure
3710bb69aaaeS[email protected]     service = btstack_memory_l2cap_service_get();
3711277abc2cSmatthias.ringwald     if (!service) {
3712be2053a6SMatthias Ringwald         log_error("l2cap_register_service: no memory for l2cap_service_t");
3713be2053a6SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
3714277abc2cSmatthias.ringwald     }
37159d9bbc01Smatthias.ringwald 
37169d9bbc01Smatthias.ringwald     // fill in
37179d9bbc01Smatthias.ringwald     service->psm = psm;
37189d9bbc01Smatthias.ringwald     service->mtu = mtu;
371905ae8de3SMatthias Ringwald     service->packet_handler = service_packet_handler;
3720df3354fcS[email protected]     service->required_security_level = security_level;
37219d9bbc01Smatthias.ringwald 
37229d9bbc01Smatthias.ringwald     // add to services list
3723665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
3724c0e866bfSmatthias.ringwald 
3725c0e866bfSmatthias.ringwald     // enable page scan
372615a95bd5SMatthias Ringwald     gap_connectable_control(1);
37275842b6d9Smatthias.ringwald 
3728c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
37299d9bbc01Smatthias.ringwald }
37309d9bbc01Smatthias.ringwald 
37317e8856ebSMatthias Ringwald uint8_t l2cap_unregister_service(uint16_t psm){
3732e0abb8e7S[email protected] 
3733e0abb8e7S[email protected]     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
3734e0abb8e7S[email protected] 
37359d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
37367e8856ebSMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3737665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
3738d3a9df87Smatthias.ringwald     btstack_memory_l2cap_service_free(service);
3739c0e866bfSmatthias.ringwald 
3740c0e866bfSmatthias.ringwald     // disable page scan when no services registered
37417e8856ebSMatthias Ringwald     if (btstack_linked_list_empty(&l2cap_services)) {
374215a95bd5SMatthias Ringwald         gap_connectable_control(0);
37439d9bbc01Smatthias.ringwald     }
3744c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
37457e8856ebSMatthias Ringwald }
374609e9d05bSMatthias Ringwald #endif
37479d9bbc01Smatthias.ringwald 
37487192e786SMatthias Ringwald 
3749cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
375083fd9c76SMatthias Ringwald 
375157be49d6SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
375257be49d6SMatthias Ringwald     if (!channel->waiting_for_can_send_now) return;
375357be49d6SMatthias Ringwald     if (channel->send_sdu_buffer) return;
375457be49d6SMatthias Ringwald     channel->waiting_for_can_send_now = 0;
3755895ff4a5SMatthias Ringwald     log_debug("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
375657be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
375757be49d6SMatthias Ringwald }
375857be49d6SMatthias Ringwald 
375957be49d6SMatthias Ringwald // 1BH2222
376057be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
376157be49d6SMatthias 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",
376257be49d6SMatthias Ringwald              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
376357be49d6SMatthias Ringwald     uint8_t event[19];
376457be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
376557be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
376657be49d6SMatthias Ringwald     event[2] = channel->address_type;
376757be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
376857be49d6SMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
376957be49d6SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
377057be49d6SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
377157be49d6SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
377257be49d6SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_mtu);
377357be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
377457be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
377557be49d6SMatthias Ringwald }
377657be49d6SMatthias Ringwald // 11BH22222
377757be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
377857be49d6SMatthias 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",
377957be49d6SMatthias Ringwald              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
378057be49d6SMatthias Ringwald              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
3781c99bb618SMatthias Ringwald     uint8_t event[23];
378257be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
378357be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
378457be49d6SMatthias Ringwald     event[2] = status;
378557be49d6SMatthias Ringwald     event[3] = channel->address_type;
378657be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[4]);
378757be49d6SMatthias Ringwald     little_endian_store_16(event, 10, channel->con_handle);
3788c1ab6cc1SMatthias Ringwald     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
3789c99bb618SMatthias Ringwald     little_endian_store_16(event, 13, channel->psm);
3790c99bb618SMatthias Ringwald     little_endian_store_16(event, 15, channel->local_cid);
3791c99bb618SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_cid);
3792c99bb618SMatthias Ringwald     little_endian_store_16(event, 19, channel->local_mtu);
3793c99bb618SMatthias Ringwald     little_endian_store_16(event, 21, channel->remote_mtu);
379457be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
379557be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
379657be49d6SMatthias Ringwald }
379787050a0bSMatthias Ringwald // 2
379887050a0bSMatthias Ringwald static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel){
379987050a0bSMatthias Ringwald     log_info("L2CAP_EVENT_LE_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
380087050a0bSMatthias Ringwald     uint8_t event[4];
380187050a0bSMatthias Ringwald     event[0] = L2CAP_EVENT_LE_CHANNEL_CLOSED;
380287050a0bSMatthias Ringwald     event[1] = sizeof(event) - 2;
380387050a0bSMatthias Ringwald     little_endian_store_16(event, 2, channel->local_cid);
380487050a0bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
380587050a0bSMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
380687050a0bSMatthias Ringwald }
380787050a0bSMatthias Ringwald 
38086774d5c9SMatthias Ringwald static void l2cap_le_send_pdu(l2cap_channel_t *channel){
38096774d5c9SMatthias Ringwald     btstack_assert(channel != NULL);
38108d783ab1SMatthias Ringwald     btstack_assert(channel->send_sdu_buffer != NULL);
38116774d5c9SMatthias Ringwald     btstack_assert(channel->credits_outgoing > 0);
38126774d5c9SMatthias Ringwald 
38136774d5c9SMatthias Ringwald     // send part of SDU
38146774d5c9SMatthias Ringwald     hci_reserve_packet_buffer();
38156774d5c9SMatthias Ringwald     uint8_t * acl_buffer = hci_get_outgoing_packet_buffer();
38166774d5c9SMatthias Ringwald     uint8_t * l2cap_payload = acl_buffer + 8;
38176774d5c9SMatthias Ringwald     uint16_t pos = 0;
38186774d5c9SMatthias Ringwald     if (!channel->send_sdu_pos){
38196774d5c9SMatthias Ringwald         // store SDU len
38206774d5c9SMatthias Ringwald         channel->send_sdu_pos += 2;
38216774d5c9SMatthias Ringwald         little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
38226774d5c9SMatthias Ringwald         pos += 2;
38236774d5c9SMatthias Ringwald     }
38246774d5c9SMatthias Ringwald     uint16_t payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
38256774d5c9SMatthias Ringwald     log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
38266535961aSMatthias Ringwald     (void)memcpy(&l2cap_payload[pos],
38276535961aSMatthias Ringwald                  &channel->send_sdu_buffer[channel->send_sdu_pos - 2],
38286535961aSMatthias Ringwald                  payload_size); // -2 for virtual SDU len
38296774d5c9SMatthias Ringwald     pos += payload_size;
38306774d5c9SMatthias Ringwald     channel->send_sdu_pos += payload_size;
38316774d5c9SMatthias Ringwald     l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
38326774d5c9SMatthias Ringwald 
38336774d5c9SMatthias Ringwald     channel->credits_outgoing--;
38346774d5c9SMatthias Ringwald 
38356774d5c9SMatthias Ringwald     hci_send_acl_packet_buffer(8 + pos);
38366774d5c9SMatthias Ringwald 
3837c1ab6cc1SMatthias Ringwald     if (channel->send_sdu_pos >= (channel->send_sdu_len + 2)){
38386774d5c9SMatthias Ringwald         channel->send_sdu_buffer = NULL;
38396774d5c9SMatthias Ringwald         // send done event
38406774d5c9SMatthias Ringwald         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
38416774d5c9SMatthias Ringwald         // inform about can send now
38426774d5c9SMatthias Ringwald         l2cap_le_notify_channel_can_send(channel);
38436774d5c9SMatthias Ringwald     }
38446774d5c9SMatthias Ringwald }
38456774d5c9SMatthias Ringwald 
384657be49d6SMatthias Ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
384757be49d6SMatthias Ringwald void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
384857be49d6SMatthias Ringwald     channel->state = L2CAP_STATE_CLOSED;
384957be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
385057be49d6SMatthias Ringwald     // discard channel
3851421cb104SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3852c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
385357be49d6SMatthias Ringwald }
385457be49d6SMatthias Ringwald 
3855e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
3856e7d0c9aaSMatthias Ringwald     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
38577192e786SMatthias Ringwald }
3858efedfb4cSMatthias Ringwald 
3859da144af5SMatthias Ringwald uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
38607192e786SMatthias Ringwald 
3861da144af5SMatthias Ringwald     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
38627192e786SMatthias Ringwald 
38637192e786SMatthias Ringwald     // check for alread registered psm
38647192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
38657192e786SMatthias Ringwald     if (service) {
3866da144af5SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
38677192e786SMatthias Ringwald     }
38687192e786SMatthias Ringwald 
38697192e786SMatthias Ringwald     // alloc structure
38707192e786SMatthias Ringwald     service = btstack_memory_l2cap_service_get();
38717192e786SMatthias Ringwald     if (!service) {
38727192e786SMatthias Ringwald         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
3873da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
38747192e786SMatthias Ringwald     }
38757192e786SMatthias Ringwald 
38767192e786SMatthias Ringwald     // fill in
38777192e786SMatthias Ringwald     service->psm = psm;
3878da144af5SMatthias Ringwald     service->mtu = 0;
38797192e786SMatthias Ringwald     service->packet_handler = packet_handler;
38807192e786SMatthias Ringwald     service->required_security_level = security_level;
38817192e786SMatthias Ringwald 
38827192e786SMatthias Ringwald     // add to services list
3883665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
38847192e786SMatthias Ringwald 
38857192e786SMatthias Ringwald     // done
38869dd26175SMilanka Ringwald     return ERROR_CODE_SUCCESS;
38877192e786SMatthias Ringwald }
38887192e786SMatthias Ringwald 
3889da144af5SMatthias Ringwald uint8_t l2cap_le_unregister_service(uint16_t psm) {
38907192e786SMatthias Ringwald     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
38917192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
38929367f9b0SMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3893da144af5SMatthias Ringwald 
3894665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
38957192e786SMatthias Ringwald     btstack_memory_l2cap_service_free(service);
3896c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
38977192e786SMatthias Ringwald }
3898da144af5SMatthias Ringwald 
3899da144af5SMatthias Ringwald uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
3900e7d0c9aaSMatthias Ringwald     // get channel
3901421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3902e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3903e7d0c9aaSMatthias Ringwald 
3904e7d0c9aaSMatthias Ringwald     // validate state
3905e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3906e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
3907e7d0c9aaSMatthias Ringwald     }
3908e7d0c9aaSMatthias Ringwald 
3909efedfb4cSMatthias Ringwald     // set state accept connection
391023017473SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
391123017473SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
391223017473SMatthias Ringwald     channel->local_mtu = mtu;
391385aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
391485aeef60SMatthias Ringwald     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
391585aeef60SMatthias Ringwald 
391685aeef60SMatthias Ringwald     // test
391763f0ac45SMatthias Ringwald     // channel->new_credits_incoming = 1;
3918e7d0c9aaSMatthias Ringwald 
3919e7d0c9aaSMatthias Ringwald     // go
3920e7d0c9aaSMatthias Ringwald     l2cap_run();
3921c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
3922da144af5SMatthias Ringwald }
3923da144af5SMatthias Ringwald 
3924da144af5SMatthias Ringwald /**
3925da144af5SMatthias Ringwald  * @brief Deny incoming LE Data Channel connection due to resource constraints
3926da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3927da144af5SMatthias Ringwald  */
3928da144af5SMatthias Ringwald 
3929da144af5SMatthias Ringwald uint8_t l2cap_le_decline_connection(uint16_t local_cid){
3930e7d0c9aaSMatthias Ringwald     // get channel
3931421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3932e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3933e7d0c9aaSMatthias Ringwald 
3934e7d0c9aaSMatthias Ringwald     // validate state
3935e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3936e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
3937e7d0c9aaSMatthias Ringwald     }
3938e7d0c9aaSMatthias Ringwald 
3939efedfb4cSMatthias Ringwald     // set state decline connection
3940e7d0c9aaSMatthias Ringwald     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
3941e7d0c9aaSMatthias Ringwald     channel->reason = 0x04; // no resources available
3942e7d0c9aaSMatthias Ringwald     l2cap_run();
3943c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
3944da144af5SMatthias Ringwald }
3945da144af5SMatthias Ringwald 
39467dafa750SMatthias Ringwald uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
3947da144af5SMatthias Ringwald     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
3948efedfb4cSMatthias Ringwald     uint16_t * out_local_cid) {
3949efedfb4cSMatthias Ringwald 
39507dafa750SMatthias Ringwald     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
3951da144af5SMatthias Ringwald 
39527dafa750SMatthias Ringwald 
39537dafa750SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
39547dafa750SMatthias Ringwald     if (!connection) {
39557dafa750SMatthias Ringwald         log_error("no hci_connection for handle 0x%04x", con_handle);
39567dafa750SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
39577dafa750SMatthias Ringwald     }
39587dafa750SMatthias Ringwald 
39595d18f623SMatthias 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);
3960da144af5SMatthias Ringwald     if (!channel) {
3961da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
3962da144af5SMatthias Ringwald     }
3963e7d0c9aaSMatthias Ringwald     log_info("l2cap_le_create_channel %p", channel);
3964da144af5SMatthias Ringwald 
3965da144af5SMatthias Ringwald     // store local_cid
3966da144af5SMatthias Ringwald     if (out_local_cid){
3967da144af5SMatthias Ringwald        *out_local_cid = channel->local_cid;
3968da144af5SMatthias Ringwald     }
3969da144af5SMatthias Ringwald 
39707dafa750SMatthias Ringwald     // provide buffer
39717dafa750SMatthias Ringwald     channel->con_handle = con_handle;
3972cd529728SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
39737dafa750SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
397485aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
397585aeef60SMatthias Ringwald     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
397685aeef60SMatthias Ringwald 
3977efedfb4cSMatthias Ringwald     // add to connections list
3978421cb104SMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
3979efedfb4cSMatthias Ringwald 
39807dafa750SMatthias Ringwald     // go
398163f0ac45SMatthias Ringwald     l2cap_run();
3982c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
3983da144af5SMatthias Ringwald }
3984da144af5SMatthias Ringwald 
3985da144af5SMatthias Ringwald /**
3986da144af5SMatthias Ringwald  * @brief Provide credtis for LE Data Channel
3987da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3988da144af5SMatthias Ringwald  * @param credits               Number additional credits for peer
3989da144af5SMatthias Ringwald  */
399064e11ca9SMatthias Ringwald uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
399163f0ac45SMatthias Ringwald 
3992421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
399363f0ac45SMatthias Ringwald     if (!channel) {
399463f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
399563f0ac45SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
399663f0ac45SMatthias Ringwald     }
399763f0ac45SMatthias Ringwald 
3998efedfb4cSMatthias Ringwald     // check state
399963f0ac45SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN){
400063f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
400163f0ac45SMatthias Ringwald     }
400263f0ac45SMatthias Ringwald 
400363f0ac45SMatthias Ringwald     // assert incoming credits + credits <= 0xffff
400463f0ac45SMatthias Ringwald     uint32_t total_credits = channel->credits_incoming;
400563f0ac45SMatthias Ringwald     total_credits += channel->new_credits_incoming;
400663f0ac45SMatthias Ringwald     total_credits += credits;
400763f0ac45SMatthias Ringwald     if (total_credits > 0xffff){
400863f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
400963f0ac45SMatthias Ringwald             channel->new_credits_incoming, credits);
401063f0ac45SMatthias Ringwald     }
401163f0ac45SMatthias Ringwald 
4012efedfb4cSMatthias Ringwald     // set credits_granted
401363f0ac45SMatthias Ringwald     channel->new_credits_incoming += credits;
401463f0ac45SMatthias Ringwald 
401563f0ac45SMatthias Ringwald     // go
401663f0ac45SMatthias Ringwald     l2cap_run();
40179dd26175SMilanka Ringwald     return ERROR_CODE_SUCCESS;
4018da144af5SMatthias Ringwald }
4019da144af5SMatthias Ringwald 
4020da144af5SMatthias Ringwald /**
4021da144af5SMatthias Ringwald  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
4022da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
4023da144af5SMatthias Ringwald  */
402464e11ca9SMatthias Ringwald int l2cap_le_can_send_now(uint16_t local_cid){
4025421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
402644276248SMatthias Ringwald     if (!channel) {
402744276248SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
4028da144af5SMatthias Ringwald         return 0;
4029da144af5SMatthias Ringwald     }
4030da144af5SMatthias Ringwald 
403144276248SMatthias Ringwald     // check state
403244276248SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN) return 0;
403344276248SMatthias Ringwald 
403444276248SMatthias Ringwald     // check queue
403544276248SMatthias Ringwald     if (channel->send_sdu_buffer) return 0;
403644276248SMatthias Ringwald 
403744276248SMatthias Ringwald     // fine, go ahead
403844276248SMatthias Ringwald     return 1;
403944276248SMatthias Ringwald }
404044276248SMatthias Ringwald 
4041da144af5SMatthias Ringwald /**
4042da144af5SMatthias Ringwald  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
4043da144af5SMatthias Ringwald  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
4044da144af5SMatthias Ringwald  *       so packet handler should be ready to handle it
4045da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
4046da144af5SMatthias Ringwald  */
404764e11ca9SMatthias Ringwald uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
4048421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
404944276248SMatthias Ringwald     if (!channel) {
405044276248SMatthias Ringwald         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
4051c8b2b785SMilanka Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
405244276248SMatthias Ringwald     }
405344276248SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
405444276248SMatthias Ringwald     l2cap_le_notify_channel_can_send(channel);
4055c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
4056da144af5SMatthias Ringwald }
4057da144af5SMatthias Ringwald 
4058da144af5SMatthias Ringwald /**
4059da144af5SMatthias Ringwald  * @brief Send data via LE Data Channel
4060da144af5SMatthias Ringwald  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
4061da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
4062da144af5SMatthias Ringwald  * @param data                  data to send
4063da144af5SMatthias Ringwald  * @param size                  data size
4064da144af5SMatthias Ringwald  */
406564e11ca9SMatthias Ringwald uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
406664e11ca9SMatthias Ringwald 
4067421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
406864e11ca9SMatthias Ringwald     if (!channel) {
406964e11ca9SMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4070828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
407164e11ca9SMatthias Ringwald     }
407264e11ca9SMatthias Ringwald 
407364e11ca9SMatthias Ringwald     if (len > channel->remote_mtu){
407464e11ca9SMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
407564e11ca9SMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
407664e11ca9SMatthias Ringwald     }
407764e11ca9SMatthias Ringwald 
40787f107edaSMatthias Ringwald     if (channel->send_sdu_buffer){
407964e11ca9SMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
408064e11ca9SMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
408164e11ca9SMatthias Ringwald     }
408264e11ca9SMatthias Ringwald 
40837f107edaSMatthias Ringwald     channel->send_sdu_buffer = data;
40847f107edaSMatthias Ringwald     channel->send_sdu_len    = len;
40857f107edaSMatthias Ringwald     channel->send_sdu_pos    = 0;
408664e11ca9SMatthias Ringwald 
40876774d5c9SMatthias Ringwald     l2cap_notify_channel_can_send();
4088c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
4089da144af5SMatthias Ringwald }
4090da144af5SMatthias Ringwald 
4091da144af5SMatthias Ringwald /**
4092da144af5SMatthias Ringwald  * @brief Disconnect from LE Data Channel
4093da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
4094da144af5SMatthias Ringwald  */
4095828a7f7aSMatthias Ringwald uint8_t l2cap_le_disconnect(uint16_t local_cid)
4096da144af5SMatthias Ringwald {
4097421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4098828a7f7aSMatthias Ringwald     if (!channel) {
4099828a7f7aSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4100828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4101828a7f7aSMatthias Ringwald     }
4102828a7f7aSMatthias Ringwald 
4103828a7f7aSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4104828a7f7aSMatthias Ringwald     l2cap_run();
4105c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
4106da144af5SMatthias Ringwald }
4107da144af5SMatthias Ringwald 
41087f02f414SMatthias Ringwald #endif
4109