xref: /btstack/src/l2cap.c (revision 0b667d4199c6940b0001ce92a4d9519d6e4fe9b4)
143625864Smatthias.ringwald /*
2a0c35809S[email protected]  * Copyright (C) 2014 BlueKitchen GmbH
31713bceaSmatthias.ringwald  *
41713bceaSmatthias.ringwald  * Redistribution and use in source and binary forms, with or without
51713bceaSmatthias.ringwald  * modification, are permitted provided that the following conditions
61713bceaSmatthias.ringwald  * are met:
71713bceaSmatthias.ringwald  *
81713bceaSmatthias.ringwald  * 1. Redistributions of source code must retain the above copyright
91713bceaSmatthias.ringwald  *    notice, this list of conditions and the following disclaimer.
101713bceaSmatthias.ringwald  * 2. Redistributions in binary form must reproduce the above copyright
111713bceaSmatthias.ringwald  *    notice, this list of conditions and the following disclaimer in the
121713bceaSmatthias.ringwald  *    documentation and/or other materials provided with the distribution.
131713bceaSmatthias.ringwald  * 3. Neither the name of the copyright holders nor the names of
141713bceaSmatthias.ringwald  *    contributors may be used to endorse or promote products derived
151713bceaSmatthias.ringwald  *    from this software without specific prior written permission.
166b64433eSmatthias.ringwald  * 4. Any redistribution, use, or modification is done solely for
176b64433eSmatthias.ringwald  *    personal benefit and not for any commercial purpose or for
186b64433eSmatthias.ringwald  *    monetary gain.
191713bceaSmatthias.ringwald  *
20a0c35809S[email protected]  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
211713bceaSmatthias.ringwald  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
221713bceaSmatthias.ringwald  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
231713bceaSmatthias.ringwald  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
241713bceaSmatthias.ringwald  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
251713bceaSmatthias.ringwald  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
261713bceaSmatthias.ringwald  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
271713bceaSmatthias.ringwald  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
281713bceaSmatthias.ringwald  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
291713bceaSmatthias.ringwald  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
301713bceaSmatthias.ringwald  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
311713bceaSmatthias.ringwald  * SUCH DAMAGE.
321713bceaSmatthias.ringwald  *
33a0c35809S[email protected]  * Please inquire about commercial licensing options at
34a0c35809S[email protected]  * [email protected]
356b64433eSmatthias.ringwald  *
361713bceaSmatthias.ringwald  */
371713bceaSmatthias.ringwald 
38e501bae0SMatthias Ringwald #define BTSTACK_FILE__ "l2cap.c"
39ab2c6ae4SMatthias Ringwald 
401713bceaSmatthias.ringwald /*
4143625864Smatthias.ringwald  *  l2cap.c
4243625864Smatthias.ringwald  *
4343625864Smatthias.ringwald  *  Logical Link Control and Adaption Protocl (L2CAP)
4443625864Smatthias.ringwald  *
4543625864Smatthias.ringwald  *  Created by Matthias Ringwald on 5/16/09.
4643625864Smatthias.ringwald  */
4743625864Smatthias.ringwald 
4843625864Smatthias.ringwald #include "l2cap.h"
49645658c9Smatthias.ringwald #include "hci.h"
502b3c6c9bSmatthias.ringwald #include "hci_dump.h"
51235946f1SMatthias Ringwald #include "bluetooth_sdp.h"
5284e3541eSMilanka Ringwald #include "bluetooth_psm.h"
5316ece135SMatthias Ringwald #include "btstack_debug.h"
540e2df43fSMatthias Ringwald #include "btstack_event.h"
55d3a9df87Smatthias.ringwald #include "btstack_memory.h"
5643625864Smatthias.ringwald 
5743625864Smatthias.ringwald #include <stdarg.h>
5843625864Smatthias.ringwald #include <string.h>
5943625864Smatthias.ringwald 
6043625864Smatthias.ringwald #include <stdio.h>
6143625864Smatthias.ringwald 
62a6e314f1SMatthias Ringwald /*
63a6e314f1SMatthias Ringwald  * @brief L2CAP Supervisory function in S-Frames
64a6e314f1SMatthias Ringwald  */
65a6e314f1SMatthias Ringwald typedef enum {
66a6e314f1SMatthias Ringwald     L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY = 0,
67a6e314f1SMatthias Ringwald     L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT,
68a6e314f1SMatthias Ringwald     L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY,
69a6e314f1SMatthias Ringwald     L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT
70a6e314f1SMatthias Ringwald } l2cap_supervisory_function_t;
71a6e314f1SMatthias Ringwald 
72a6e314f1SMatthias Ringwald /**
73a6e314f1SMatthias Ringwald  * @brief L2CAP Information Types used in Information Request & Response
74a6e314f1SMatthias Ringwald  */
75a6e314f1SMatthias Ringwald typedef enum {
76a6e314f1SMatthias Ringwald   L2CAP_INFO_TYPE_CONNECTIONLESS_MTU = 1,
77a6e314f1SMatthias Ringwald   L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED,
78a6e314f1SMatthias Ringwald   L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED,
79a6e314f1SMatthias Ringwald } l2cap_info_type_t;
80a6e314f1SMatthias Ringwald 
81a6e314f1SMatthias Ringwald /**
82a6e314f1SMatthias Ringwald  * @brief L2CAP Configuration Option Types used in Configurateion Request & Response
83a6e314f1SMatthias Ringwald  */
84a6e314f1SMatthias Ringwald typedef enum {
85a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT = 1,
86a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT,
87a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_QUALITY_OF_SERVICE,
88a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL,
89a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE,
90a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_EXTENDED_FLOW_SPECIFICATION,
91a6e314f1SMatthias Ringwald   L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE,
92a6e314f1SMatthias Ringwald } l2cap_config_option_type_t;
93a6e314f1SMatthias Ringwald 
94a6e314f1SMatthias Ringwald 
95a6e314f1SMatthias Ringwald #define L2CAP_SIG_ID_INVALID 0
96a6e314f1SMatthias Ringwald 
97a6e314f1SMatthias Ringwald // size of HCI ACL + L2CAP Header for regular data packets (8)
98a6e314f1SMatthias Ringwald #define COMPLETE_L2CAP_HEADER (HCI_ACL_HEADER_SIZE + L2CAP_HEADER_SIZE)
99a6e314f1SMatthias Ringwald 
100a6e314f1SMatthias Ringwald // L2CAP Configuration Result Codes
101a6e314f1SMatthias Ringwald #define L2CAP_CONF_RESULT_SUCCESS                  0x0000
102a6e314f1SMatthias Ringwald #define L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS  0x0001
103a6e314f1SMatthias Ringwald #define L2CAP_CONF_RESULT_REJECT                   0x0002
104a6e314f1SMatthias Ringwald #define L2CAP_CONF_RESULT_UNKNOWN_OPTIONS          0x0003
105a6e314f1SMatthias Ringwald #define L2CAP_CONF_RESULT_PENDING                  0x0004
106a6e314f1SMatthias Ringwald #define L2CAP_CONF_RESULT_FLOW_SPEC_REJECTED       0x0005
107a6e314f1SMatthias Ringwald 
108a6e314f1SMatthias Ringwald // L2CAP Reject Result Codes
109a6e314f1SMatthias Ringwald #define L2CAP_REJ_CMD_UNKNOWN                      0x0000
110a6e314f1SMatthias Ringwald 
111a6e314f1SMatthias Ringwald // Response Timeout eXpired
112a6e314f1SMatthias Ringwald #define L2CAP_RTX_TIMEOUT_MS   10000
113a6e314f1SMatthias Ringwald 
114a6e314f1SMatthias Ringwald // Extended Response Timeout eXpired
115a6e314f1SMatthias Ringwald #define L2CAP_ERTX_TIMEOUT_MS 120000
116a6e314f1SMatthias Ringwald 
1174c744e21Smatthias.ringwald // nr of buffered acl packets in outgoing queue to get max performance
1184c744e21Smatthias.ringwald #define NR_BUFFERED_ACL_PACKETS 3
1194c744e21Smatthias.ringwald 
12039bda6d5Smatthias.ringwald // used to cache l2cap rejects, echo, and informational requests
121e16a9cacSmatthias.ringwald #define NR_PENDING_SIGNALING_RESPONSES 3
12239bda6d5Smatthias.ringwald 
12385aeef60SMatthias Ringwald // nr of credits provided to remote if credits fall below watermark
12485aeef60SMatthias Ringwald #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK 5
12585aeef60SMatthias Ringwald #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT 5
12685aeef60SMatthias Ringwald 
12700d93d79Smatthias.ringwald // offsets for L2CAP SIGNALING COMMANDS
12800d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
12900d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
13000d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
13100d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
13200d93d79Smatthias.ringwald 
13309e9d05bSMatthias Ringwald #if defined(ENABLE_LE_DATA_CHANNELS) || defined(ENABLE_CLASSIC)
13409e9d05bSMatthias Ringwald #define L2CAP_USES_CHANNELS
13509e9d05bSMatthias Ringwald #endif
13609e9d05bSMatthias Ringwald 
13733c40538SMatthias Ringwald // prototypes
138675e6881SMatthias Ringwald static void l2cap_run(void);
13933c40538SMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
1403d50b4baSMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size );
14130725612SMatthias Ringwald static void l2cap_notify_channel_can_send(void);
14209e9d05bSMatthias Ringwald static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel);
1436ddef68dSMilanka Ringwald static uint8_t  l2cap_next_sig_id(void);
1447740e150SMatthias Ringwald static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid);
14509e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
146474f5c3fSMatthias Ringwald static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel);
147474f5c3fSMatthias Ringwald static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel);
14809e9d05bSMatthias Ringwald static void l2cap_finialize_channel_close(l2cap_channel_t *channel);
14909e9d05bSMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm);
15009e9d05bSMatthias Ringwald static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
15109e9d05bSMatthias Ringwald static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
15209e9d05bSMatthias Ringwald static void l2cap_emit_incoming_connection(l2cap_channel_t *channel);
15309e9d05bSMatthias Ringwald static int  l2cap_channel_ready_for_open(l2cap_channel_t *channel);
15409e9d05bSMatthias Ringwald #endif
155cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
15657be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status);
15787050a0bSMatthias Ringwald static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel);
15857be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel);
15944276248SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel);
160828a7f7aSMatthias Ringwald static void l2cap_le_finialize_channel_close(l2cap_channel_t *channel);
1616774d5c9SMatthias Ringwald static void l2cap_le_send_pdu(l2cap_channel_t *channel);
162e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t psm);
163e7d0c9aaSMatthias Ringwald #endif
164474f5c3fSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
1656a5ffed8SMatthias Ringwald static uint16_t l2cap_next_local_cid(void);
1666a5ffed8SMatthias Ringwald static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid);
167836ae835SMatthias Ringwald static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code);
168474f5c3fSMatthias Ringwald static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size);
169474f5c3fSMatthias Ringwald static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid);
1705d18f623SMatthias Ringwald static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, l2cap_channel_type_t channel_type, bd_addr_t address, bd_addr_type_t address_type,
171474f5c3fSMatthias Ringwald         uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level);
172c45d6b2cSMatthias Ringwald static void l2cap_free_channel_entry(l2cap_channel_t * channel);
173474f5c3fSMatthias Ringwald #endif
174212b6be2SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
17596646001SMatthias Ringwald static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel);
176c9300dcaSMatthias Ringwald static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts);
1778a700052SMatthias Ringwald static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts);
178212b6be2SMatthias Ringwald #endif
17933c40538SMatthias Ringwald 
180fad84cafSMatthias Ringwald // l2cap_fixed_channel_t entries
18124eb964eSMatthias Ringwald #ifdef ENABLE_BLE
182fad84cafSMatthias Ringwald static l2cap_fixed_channel_t l2cap_fixed_channel_att;
183fad84cafSMatthias Ringwald static l2cap_fixed_channel_t l2cap_fixed_channel_sm;
18424eb964eSMatthias Ringwald #endif
18524eb964eSMatthias Ringwald #ifdef ENABLE_CLASSIC
186fad84cafSMatthias Ringwald static l2cap_fixed_channel_t l2cap_fixed_channel_connectionless;
18724eb964eSMatthias Ringwald #endif
1885628cf69SMatthias Ringwald 
18909e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1905628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_services;
19109e9d05bSMatthias Ringwald static uint8_t require_security_level2_for_outgoing_sdp;
192ece97caeSMatthias Ringwald static bd_addr_t l2cap_outgoing_classic_addr;
19309e9d05bSMatthias Ringwald #endif
19457be49d6SMatthias Ringwald 
19557be49d6SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1965628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_le_services;
19757be49d6SMatthias Ringwald #endif
19839bda6d5Smatthias.ringwald 
199fad84cafSMatthias Ringwald // single list of channels for Classic Channels, LE Data Channels, Classic Connectionless, ATT, and SM
200421cb104SMatthias Ringwald static btstack_linked_list_t l2cap_channels;
2016a5ffed8SMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
2026ddef68dSMilanka Ringwald // next channel id for new connections
2036ddef68dSMilanka Ringwald static uint16_t  local_source_cid  = 0x40;
2046a5ffed8SMatthias Ringwald #endif
2056ddef68dSMilanka Ringwald // next signaling sequence number
2066ddef68dSMilanka Ringwald static uint8_t   sig_seq_nr  = 0xff;
207421cb104SMatthias Ringwald 
20839bda6d5Smatthias.ringwald // used to cache l2cap rejects, echo, and informational requests
2092b83fb7dSmatthias.ringwald static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
2102b83fb7dSmatthias.ringwald static int signaling_responses_pending;
211fb37a842SMatthias Ringwald static btstack_packet_callback_registration_t hci_event_callback_registration;
21239bda6d5Smatthias.ringwald 
213d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
214d6ed9f9cSMatthias Ringwald // only used for connection parameter update events
215d6ed9f9cSMatthias Ringwald static btstack_packet_handler_t l2cap_event_packet_handler;
21625818320SMatthias Ringwald static uint16_t l2cap_le_custom_max_mtu;
217d6ed9f9cSMatthias Ringwald #endif
218d6ed9f9cSMatthias Ringwald 
21985ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
22085ddcd84SMatthias Ringwald 
221e288be62SMatthias Ringwald // enable for testing
222e288be62SMatthias Ringwald // #define L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL 16
223e288be62SMatthias Ringwald 
22485ddcd84SMatthias Ringwald /*
22585ddcd84SMatthias Ringwald  * CRC lookup table for generator polynom D^16 + D^15 + D^2 + 1
22685ddcd84SMatthias Ringwald  */
22785ddcd84SMatthias Ringwald static const uint16_t crc16_table[256] = {
22885ddcd84SMatthias Ringwald     0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
22985ddcd84SMatthias Ringwald     0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841,
23085ddcd84SMatthias Ringwald     0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41,
23185ddcd84SMatthias Ringwald     0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040,
23285ddcd84SMatthias Ringwald     0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441,
23385ddcd84SMatthias Ringwald     0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840,
23485ddcd84SMatthias Ringwald     0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40,
23585ddcd84SMatthias Ringwald     0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041,
23685ddcd84SMatthias Ringwald     0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
23785ddcd84SMatthias Ringwald     0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840,
23885ddcd84SMatthias Ringwald     0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
23985ddcd84SMatthias Ringwald     0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041,
24085ddcd84SMatthias Ringwald     0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440,
24185ddcd84SMatthias Ringwald     0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841,
24285ddcd84SMatthias Ringwald     0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41,
24385ddcd84SMatthias Ringwald     0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040,
24485ddcd84SMatthias Ringwald };
24585ddcd84SMatthias Ringwald 
24685ddcd84SMatthias Ringwald static uint16_t crc16_calc(uint8_t * data, uint16_t len){
24785ddcd84SMatthias Ringwald     uint16_t crc = 0;   // initial value = 0
24885ddcd84SMatthias Ringwald     while (len--){
24985ddcd84SMatthias Ringwald         crc = (crc >> 8) ^ crc16_table[ (crc ^ ((uint16_t) *data++)) & 0x00FF ];
25085ddcd84SMatthias Ringwald     }
25185ddcd84SMatthias Ringwald     return crc;
25285ddcd84SMatthias Ringwald }
25385ddcd84SMatthias Ringwald 
254474f5c3fSMatthias Ringwald static inline uint16_t l2cap_encanced_control_field_for_information_frame(uint8_t tx_seq, int final, uint8_t req_seq, l2cap_segmentation_and_reassembly_t sar){
255474f5c3fSMatthias Ringwald     return (((uint16_t) sar) << 14) | (req_seq << 8) | (final << 7) | (tx_seq << 1) | 0;
256474f5c3fSMatthias Ringwald }
257474f5c3fSMatthias Ringwald 
258474f5c3fSMatthias Ringwald static inline uint16_t l2cap_encanced_control_field_for_supevisor_frame(l2cap_supervisory_function_t supervisory_function, int poll, int final, uint8_t req_seq){
259474f5c3fSMatthias Ringwald     return (req_seq << 8) | (final << 7) | (poll << 4) | (((int) supervisory_function) << 2) | 1;
260474f5c3fSMatthias Ringwald }
261474f5c3fSMatthias Ringwald 
262474f5c3fSMatthias Ringwald static int l2cap_next_ertm_seq_nr(int seq_nr){
263474f5c3fSMatthias Ringwald     return (seq_nr + 1) & 0x3f;
264474f5c3fSMatthias Ringwald }
265474f5c3fSMatthias Ringwald 
266474f5c3fSMatthias Ringwald static int l2cap_ertm_can_store_packet_now(l2cap_channel_t * channel){
267474f5c3fSMatthias Ringwald     // get num free tx buffers
268a8409e80SMatthias Ringwald     int num_free_tx_buffers = channel->num_tx_buffers - channel->num_stored_tx_frames;
269474f5c3fSMatthias Ringwald     // calculate num tx buffers for remote MTU
270474f5c3fSMatthias Ringwald     int num_tx_buffers_for_max_remote_mtu;
271b90eac91SMatthias Ringwald     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
272b90eac91SMatthias Ringwald     if (channel->remote_mtu <= effective_mps){
273474f5c3fSMatthias Ringwald         // MTU fits into single packet
274474f5c3fSMatthias Ringwald         num_tx_buffers_for_max_remote_mtu = 1;
275474f5c3fSMatthias Ringwald     } else {
276474f5c3fSMatthias Ringwald         // include SDU Length
277b90eac91SMatthias Ringwald         num_tx_buffers_for_max_remote_mtu = (channel->remote_mtu + 2 + (effective_mps - 1)) / effective_mps;
278474f5c3fSMatthias Ringwald     }
279a8409e80SMatthias Ringwald     log_debug("num_free_tx_buffers %u, num_tx_buffers_for_max_remote_mtu %u", num_free_tx_buffers, num_tx_buffers_for_max_remote_mtu);
280474f5c3fSMatthias Ringwald     return num_tx_buffers_for_max_remote_mtu <= num_free_tx_buffers;
281474f5c3fSMatthias Ringwald }
282474f5c3fSMatthias Ringwald 
283ef2faf56SMatthias Ringwald static void l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel_t * l2cap_channel){
284ef2faf56SMatthias Ringwald     log_info("Retransmit unacknowleged frames");
285ef2faf56SMatthias Ringwald     l2cap_channel->unacked_frames = 0;;
286ef2faf56SMatthias Ringwald     l2cap_channel->tx_send_index  = l2cap_channel->tx_read_index;
287ef2faf56SMatthias Ringwald }
288ef2faf56SMatthias Ringwald 
289474f5c3fSMatthias Ringwald static void l2cap_ertm_next_tx_write_index(l2cap_channel_t * channel){
290474f5c3fSMatthias Ringwald     channel->tx_write_index++;
291474f5c3fSMatthias Ringwald     if (channel->tx_write_index < channel->num_tx_buffers) return;
292474f5c3fSMatthias Ringwald     channel->tx_write_index = 0;
293474f5c3fSMatthias Ringwald }
294474f5c3fSMatthias Ringwald 
295474f5c3fSMatthias Ringwald static void l2cap_ertm_start_monitor_timer(l2cap_channel_t * channel){
296550189ffSMatthias Ringwald     log_info("Start Monitor timer");
297474f5c3fSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->monitor_timer);
298474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->monitor_timer, &l2cap_ertm_monitor_timeout_callback);
299474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer_context(&channel->monitor_timer, channel);
300474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer(&channel->monitor_timer, channel->local_monitor_timeout_ms);
301474f5c3fSMatthias Ringwald     btstack_run_loop_add_timer(&channel->monitor_timer);
302474f5c3fSMatthias Ringwald }
303474f5c3fSMatthias Ringwald 
304550189ffSMatthias Ringwald static void l2cap_ertm_stop_monitor_timer(l2cap_channel_t * channel){
305550189ffSMatthias Ringwald     log_info("Stop Monitor timer");
306550189ffSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->monitor_timer);
307550189ffSMatthias Ringwald }
308474f5c3fSMatthias Ringwald 
309474f5c3fSMatthias Ringwald static void l2cap_ertm_start_retransmission_timer(l2cap_channel_t * channel){
310550189ffSMatthias Ringwald     log_info("Start Retransmission timer");
311474f5c3fSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->retransmission_timer);
312474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->retransmission_timer, &l2cap_ertm_retransmission_timeout_callback);
313474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer_context(&channel->retransmission_timer, channel);
314474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer(&channel->retransmission_timer, channel->local_retransmission_timeout_ms);
315474f5c3fSMatthias Ringwald     btstack_run_loop_add_timer(&channel->retransmission_timer);
316474f5c3fSMatthias Ringwald }
317474f5c3fSMatthias Ringwald 
318474f5c3fSMatthias Ringwald static void l2cap_ertm_stop_retransmission_timer(l2cap_channel_t * l2cap_channel){
319550189ffSMatthias Ringwald     log_info("Stop Retransmission timer");
320474f5c3fSMatthias Ringwald     btstack_run_loop_remove_timer(&l2cap_channel->retransmission_timer);
321474f5c3fSMatthias Ringwald }
322474f5c3fSMatthias Ringwald 
323474f5c3fSMatthias Ringwald static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts){
324550189ffSMatthias Ringwald     log_info("Monitor timeout");
325474f5c3fSMatthias Ringwald     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
326474f5c3fSMatthias Ringwald 
327474f5c3fSMatthias Ringwald     // TODO: we assume that it's the oldest packet
328474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
329474f5c3fSMatthias Ringwald     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
330474f5c3fSMatthias Ringwald 
331474f5c3fSMatthias Ringwald     // check retry count
332474f5c3fSMatthias Ringwald     if (tx_state->retry_count < l2cap_channel->remote_max_transmit){
333474f5c3fSMatthias Ringwald         // increment retry count
334474f5c3fSMatthias Ringwald         tx_state->retry_count++;
335474f5c3fSMatthias Ringwald 
336ef2faf56SMatthias Ringwald         // start retransmit
337ef2faf56SMatthias Ringwald         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
338ef2faf56SMatthias Ringwald 
339ef2faf56SMatthias Ringwald         // start monitor timer
340474f5c3fSMatthias Ringwald         l2cap_ertm_start_monitor_timer(l2cap_channel);
341474f5c3fSMatthias Ringwald 
342474f5c3fSMatthias Ringwald         // send RR/P=1
343474f5c3fSMatthias Ringwald         l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
344474f5c3fSMatthias Ringwald     } else {
345474f5c3fSMatthias Ringwald         log_info("Monitor timer expired & retry count >= max transmit -> disconnect");
346474f5c3fSMatthias Ringwald         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
347474f5c3fSMatthias Ringwald     }
348474f5c3fSMatthias Ringwald     l2cap_run();
349474f5c3fSMatthias Ringwald }
350474f5c3fSMatthias Ringwald 
351474f5c3fSMatthias Ringwald static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts){
352550189ffSMatthias Ringwald     log_info("Retransmission timeout");
353474f5c3fSMatthias Ringwald     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
354474f5c3fSMatthias Ringwald 
355474f5c3fSMatthias Ringwald     // TODO: we assume that it's the oldest packet
356474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
357474f5c3fSMatthias Ringwald     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
358474f5c3fSMatthias Ringwald 
359474f5c3fSMatthias Ringwald     // set retry count = 1
360474f5c3fSMatthias Ringwald     tx_state->retry_count = 1;
361474f5c3fSMatthias Ringwald 
362ef2faf56SMatthias Ringwald     // start retransmit
363ef2faf56SMatthias Ringwald     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
364ef2faf56SMatthias Ringwald 
365474f5c3fSMatthias Ringwald     // start monitor timer
366474f5c3fSMatthias Ringwald     l2cap_ertm_start_monitor_timer(l2cap_channel);
367474f5c3fSMatthias Ringwald 
368474f5c3fSMatthias Ringwald     // send RR/P=1
369474f5c3fSMatthias Ringwald     l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
370474f5c3fSMatthias Ringwald     l2cap_run();
371474f5c3fSMatthias Ringwald }
372474f5c3fSMatthias Ringwald 
373474f5c3fSMatthias Ringwald static int l2cap_ertm_send_information_frame(l2cap_channel_t * channel, int index, int final){
374474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
375474f5c3fSMatthias Ringwald     hci_reserve_packet_buffer();
376474f5c3fSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
377474f5c3fSMatthias Ringwald     uint16_t control = l2cap_encanced_control_field_for_information_frame(tx_state->tx_seq, final, channel->req_seq, tx_state->sar);
378474f5c3fSMatthias Ringwald     log_info("I-Frame: control 0x%04x", control);
379474f5c3fSMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
3806535961aSMatthias Ringwald     (void)memcpy(&acl_buffer[8 + 2],
3816535961aSMatthias Ringwald                  &channel->tx_packets_data[index * channel->local_mps],
3826535961aSMatthias Ringwald                  tx_state->len);
3831e1a46bbSMatthias Ringwald     // (re-)start retransmission timer on
3841e1a46bbSMatthias Ringwald     l2cap_ertm_start_retransmission_timer(channel);
385474f5c3fSMatthias Ringwald     // send
386474f5c3fSMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2 + tx_state->len);
387474f5c3fSMatthias Ringwald }
388474f5c3fSMatthias Ringwald 
389474f5c3fSMatthias Ringwald static void l2cap_ertm_store_fragment(l2cap_channel_t * channel, l2cap_segmentation_and_reassembly_t sar, uint16_t sdu_length, uint8_t * data, uint16_t len){
390474f5c3fSMatthias Ringwald     // get next index for storing packets
391474f5c3fSMatthias Ringwald     int index = channel->tx_write_index;
392474f5c3fSMatthias Ringwald 
393474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
394474f5c3fSMatthias Ringwald     tx_state->tx_seq = channel->next_tx_seq;
395474f5c3fSMatthias Ringwald     tx_state->sar = sar;
396474f5c3fSMatthias Ringwald     tx_state->retry_count = 0;
397474f5c3fSMatthias Ringwald 
3983b81f0d3SMatthias Ringwald     uint8_t * tx_packet = &channel->tx_packets_data[index * channel->local_mps];
399b90eac91SMatthias Ringwald     log_debug("index %u, local mps %u, remote mps %u, packet tx %p, len %u", index, channel->local_mps, channel->remote_mps, tx_packet, len);
400474f5c3fSMatthias Ringwald     int pos = 0;
401474f5c3fSMatthias Ringwald     if (sar == L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU){
402474f5c3fSMatthias Ringwald         little_endian_store_16(tx_packet, 0, sdu_length);
403474f5c3fSMatthias Ringwald         pos += 2;
404474f5c3fSMatthias Ringwald     }
4056535961aSMatthias Ringwald     (void)memcpy(&tx_packet[pos], data, len);
406b90eac91SMatthias Ringwald     tx_state->len = pos + len;
407474f5c3fSMatthias Ringwald 
408474f5c3fSMatthias Ringwald     // update
409a8409e80SMatthias Ringwald     channel->num_stored_tx_frames++;
410474f5c3fSMatthias Ringwald     channel->next_tx_seq = l2cap_next_ertm_seq_nr(channel->next_tx_seq);
411474f5c3fSMatthias Ringwald     l2cap_ertm_next_tx_write_index(channel);
41294301352SMatthias Ringwald 
413a8409e80SMatthias Ringwald     log_info("l2cap_ertm_store_fragment: tx_read_index %u, tx_write_index %u, num stored %u", channel->tx_read_index, channel->tx_write_index, channel->num_stored_tx_frames);
41494301352SMatthias Ringwald 
415474f5c3fSMatthias Ringwald }
416474f5c3fSMatthias Ringwald 
417474f5c3fSMatthias Ringwald static int l2cap_ertm_send(l2cap_channel_t * channel, uint8_t * data, uint16_t len){
418474f5c3fSMatthias Ringwald     if (len > channel->remote_mtu){
419a8409e80SMatthias Ringwald         log_error("l2cap_ertm_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
420474f5c3fSMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
421474f5c3fSMatthias Ringwald     }
422474f5c3fSMatthias Ringwald 
423a8409e80SMatthias Ringwald     if (!l2cap_ertm_can_store_packet_now(channel)){
424a8409e80SMatthias Ringwald         log_error("l2cap_ertm_send cid 0x%02x, fragment store full", channel->local_cid);
425a8409e80SMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
426a8409e80SMatthias Ringwald     }
427a8409e80SMatthias Ringwald 
428474f5c3fSMatthias Ringwald     // check if it needs to get fragmented
429b90eac91SMatthias Ringwald     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
430b90eac91SMatthias Ringwald     if (len > effective_mps){
431474f5c3fSMatthias Ringwald         // fragmentation needed.
432474f5c3fSMatthias Ringwald         l2cap_segmentation_and_reassembly_t sar =  L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU;
433474f5c3fSMatthias Ringwald         int chunk_len;
434474f5c3fSMatthias Ringwald         while (len){
435474f5c3fSMatthias Ringwald             switch (sar){
436474f5c3fSMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
437b90eac91SMatthias Ringwald                     chunk_len = effective_mps - 2;    // sdu_length
438474f5c3fSMatthias Ringwald                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
439474f5c3fSMatthias Ringwald                     len -= chunk_len;
440474f5c3fSMatthias Ringwald                     sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU;
441474f5c3fSMatthias Ringwald                     break;
442474f5c3fSMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
443b90eac91SMatthias Ringwald                     chunk_len = effective_mps;
444474f5c3fSMatthias Ringwald                     if (chunk_len >= len){
445474f5c3fSMatthias Ringwald                         sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU;
446474f5c3fSMatthias Ringwald                         chunk_len = len;
447474f5c3fSMatthias Ringwald                     }
448474f5c3fSMatthias Ringwald                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
449474f5c3fSMatthias Ringwald                     len -= chunk_len;
450474f5c3fSMatthias Ringwald                     break;
451474f5c3fSMatthias Ringwald                 default:
452474f5c3fSMatthias Ringwald                     break;
453474f5c3fSMatthias Ringwald             }
454474f5c3fSMatthias Ringwald         }
455474f5c3fSMatthias Ringwald 
456474f5c3fSMatthias Ringwald     } else {
457474f5c3fSMatthias Ringwald         l2cap_ertm_store_fragment(channel, L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU, 0, data, len);
458474f5c3fSMatthias Ringwald     }
459474f5c3fSMatthias Ringwald 
460474f5c3fSMatthias Ringwald     // try to send
461d89ab698SMatthias Ringwald     l2cap_notify_channel_can_send();
462474f5c3fSMatthias Ringwald     return 0;
463474f5c3fSMatthias Ringwald }
464474f5c3fSMatthias Ringwald 
4657cbe539fSMatthias Ringwald static uint16_t l2cap_setup_options_ertm_request(l2cap_channel_t * channel, uint8_t * config_options){
466fcb125edSMatthias Ringwald     int pos = 0;
467fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
468fcb125edSMatthias Ringwald     config_options[pos++] = 9;      // length
469fcb125edSMatthias Ringwald     config_options[pos++] = (uint8_t) channel->mode;
470fcb125edSMatthias Ringwald     config_options[pos++] = channel->num_rx_buffers;    // == TxWindows size
471fcb125edSMatthias Ringwald     config_options[pos++] = channel->local_max_transmit;
472fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
473fcb125edSMatthias Ringwald     pos += 2;
474fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
475fcb125edSMatthias Ringwald     pos += 2;
476fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_mps);
477fcb125edSMatthias Ringwald     pos += 2;
4786574158aSMatthias Ringwald     //
479fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT;
480fcb125edSMatthias Ringwald     config_options[pos++] = 2;     // length
481fcb125edSMatthias Ringwald     little_endian_store_16(config_options, pos, channel->local_mtu);
482fcb125edSMatthias Ringwald     pos += 2;
483c425ea4aSMatthias Ringwald 
484c425ea4aSMatthias Ringwald     // Issue: iOS (e.g. 10.2) uses "No FCS" as default while Core 5.0 specifies "FCS" as default
485c425ea4aSMatthias Ringwald     // Workaround: try to actively negotiate FCS option
486fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
487fcb125edSMatthias Ringwald     config_options[pos++] = 1;     // length
488fcb125edSMatthias Ringwald     config_options[pos++] = channel->fcs_option;
489f2c70799Sandryblack     return pos; // 11+4+3=18
490474f5c3fSMatthias Ringwald }
491474f5c3fSMatthias Ringwald 
4927cbe539fSMatthias Ringwald static uint16_t l2cap_setup_options_ertm_response(l2cap_channel_t * channel, uint8_t * config_options){
493fcb125edSMatthias Ringwald     int pos = 0;
494fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
495fcb125edSMatthias Ringwald     config_options[pos++] = 9;      // length
496fcb125edSMatthias Ringwald     config_options[pos++] = (uint8_t) channel->mode;
4977cbe539fSMatthias Ringwald     // less or equal to remote tx window size
498fcb125edSMatthias Ringwald     config_options[pos++] = btstack_min(channel->num_tx_buffers, channel->remote_tx_window_size);
4997cbe539fSMatthias Ringwald     // max transmit in response shall be ignored -> use sender values
500fcb125edSMatthias Ringwald     config_options[pos++] = channel->remote_max_transmit;
5017cbe539fSMatthias Ringwald     // A value for the Retransmission time-out shall be sent in a positive Configuration Response
5027cbe539fSMatthias Ringwald     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
503fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
504fcb125edSMatthias Ringwald     pos += 2;
5057cbe539fSMatthias Ringwald     // A value for the Monitor time-out shall be sent in a positive Configuration Response
5067cbe539fSMatthias Ringwald     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
507fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
508fcb125edSMatthias Ringwald     pos += 2;
5097cbe539fSMatthias Ringwald     // less or equal to remote mps
510b90eac91SMatthias Ringwald     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
511b90eac91SMatthias Ringwald     little_endian_store_16( config_options, pos, effective_mps);
512fcb125edSMatthias Ringwald     pos += 2;
5136574158aSMatthias Ringwald     //
514fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
515fcb125edSMatthias Ringwald     config_options[pos++] = 2;     // length
516fcb125edSMatthias Ringwald     little_endian_store_16(config_options, pos, channel->remote_mtu);
517fcb125edSMatthias Ringwald     pos += 2;
518fcb125edSMatthias Ringwald #if 0
519d64e9771SMatthias Ringwald     //
520fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
521fcb125edSMatthias Ringwald     config_options[pos++] = 1;     // length
522fcb125edSMatthias Ringwald     config_options[pos++] = channel->fcs_option;
523fcb125edSMatthias Ringwald #endif
524f2c70799Sandryblack     return pos; // 11+4=15
5257cbe539fSMatthias Ringwald }
5267cbe539fSMatthias Ringwald 
527474f5c3fSMatthias Ringwald static int l2cap_ertm_send_supervisor_frame(l2cap_channel_t * channel, uint16_t control){
528474f5c3fSMatthias Ringwald     hci_reserve_packet_buffer();
529474f5c3fSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
530474f5c3fSMatthias Ringwald     log_info("S-Frame: control 0x%04x", control);
531474f5c3fSMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
532474f5c3fSMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2);
533474f5c3fSMatthias Ringwald }
534474f5c3fSMatthias Ringwald 
5355774a392SMatthias Ringwald static uint8_t l2cap_ertm_validate_local_config(l2cap_ertm_config_t * ertm_config){
536474f5c3fSMatthias Ringwald 
537474f5c3fSMatthias Ringwald     uint8_t result = ERROR_CODE_SUCCESS;
5389c0e62d3SMatthias Ringwald     if (ertm_config->max_transmit < 1){
539474f5c3fSMatthias Ringwald         log_error("max_transmit must be >= 1");
540474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
541474f5c3fSMatthias Ringwald     }
5429c0e62d3SMatthias Ringwald     if (ertm_config->retransmission_timeout_ms < 2000){
543474f5c3fSMatthias Ringwald         log_error("retransmission_timeout_ms must be >= 2000 ms");
544474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
545474f5c3fSMatthias Ringwald     }
5469c0e62d3SMatthias Ringwald     if (ertm_config->monitor_timeout_ms < 12000){
547474f5c3fSMatthias Ringwald         log_error("monitor_timeout_ms must be >= 12000 ms");
548474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
549474f5c3fSMatthias Ringwald     }
5509c0e62d3SMatthias Ringwald     if (ertm_config->local_mtu < 48){
551474f5c3fSMatthias Ringwald         log_error("local_mtu must be >= 48");
552474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
553474f5c3fSMatthias Ringwald     }
5549c0e62d3SMatthias Ringwald     if (ertm_config->num_rx_buffers < 1){
555474f5c3fSMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
556474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
557474f5c3fSMatthias Ringwald     }
5589c0e62d3SMatthias Ringwald     if (ertm_config->num_tx_buffers < 1){
559474f5c3fSMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
560474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
561474f5c3fSMatthias Ringwald     }
562474f5c3fSMatthias Ringwald     return result;
563474f5c3fSMatthias Ringwald }
564474f5c3fSMatthias Ringwald 
5659c0e62d3SMatthias Ringwald static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
566474f5c3fSMatthias Ringwald 
567474f5c3fSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
5689c0e62d3SMatthias Ringwald     channel->ertm_mandatory = ertm_config->ertm_mandatory;
5699c0e62d3SMatthias Ringwald     channel->local_max_transmit = ertm_config->max_transmit;
5709c0e62d3SMatthias Ringwald     channel->local_retransmission_timeout_ms = ertm_config->retransmission_timeout_ms;
5719c0e62d3SMatthias Ringwald     channel->local_monitor_timeout_ms = ertm_config->monitor_timeout_ms;
5729c0e62d3SMatthias Ringwald     channel->local_mtu = ertm_config->local_mtu;
5739c0e62d3SMatthias Ringwald     channel->num_rx_buffers = ertm_config->num_rx_buffers;
5749c0e62d3SMatthias Ringwald     channel->num_tx_buffers = ertm_config->num_tx_buffers;
575474f5c3fSMatthias Ringwald 
576c342091bSMatthias Ringwald     // align buffer to 16-byte boundary to assert l2cap_ertm_rx_packet_state_t is aligned
577474f5c3fSMatthias Ringwald     int bytes_till_alignment = 16 - (((uintptr_t) buffer) & 0x0f);
578474f5c3fSMatthias Ringwald     buffer += bytes_till_alignment;
579474f5c3fSMatthias Ringwald     size   -= bytes_till_alignment;
580474f5c3fSMatthias Ringwald 
581c342091bSMatthias Ringwald     // setup state buffers - use void cast to avoid -Wcast-align warning
582474f5c3fSMatthias Ringwald     uint32_t pos = 0;
583c342091bSMatthias Ringwald     channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) (void *) &buffer[pos];
5849c0e62d3SMatthias Ringwald     pos += ertm_config->num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
585c342091bSMatthias Ringwald     channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) (void *) &buffer[pos];
5869c0e62d3SMatthias Ringwald     pos += ertm_config->num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
587474f5c3fSMatthias Ringwald 
588474f5c3fSMatthias Ringwald     // setup reassembly buffer
589474f5c3fSMatthias Ringwald     channel->reassembly_buffer = &buffer[pos];
5909c0e62d3SMatthias Ringwald     pos += ertm_config->local_mtu;
591474f5c3fSMatthias Ringwald 
592474f5c3fSMatthias Ringwald     // divide rest of data equally
5939c0e62d3SMatthias Ringwald     channel->local_mps = (size - pos) / (ertm_config->num_rx_buffers + ertm_config->num_tx_buffers);
5940d3ee2efSMatthias Ringwald     log_info("Local MPS: %u", channel->local_mps);
595474f5c3fSMatthias Ringwald     channel->rx_packets_data = &buffer[pos];
5960d3ee2efSMatthias Ringwald     pos += ertm_config->num_rx_buffers * channel->local_mps;
597474f5c3fSMatthias Ringwald     channel->tx_packets_data = &buffer[pos];
5986574158aSMatthias Ringwald 
599c425ea4aSMatthias Ringwald     channel->fcs_option = ertm_config->fcs_option;
600474f5c3fSMatthias Ringwald }
601474f5c3fSMatthias Ringwald 
602474f5c3fSMatthias Ringwald uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
6039c0e62d3SMatthias Ringwald     l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
604474f5c3fSMatthias Ringwald 
6059c0e62d3SMatthias Ringwald     log_info("L2CAP_CREATE_ERTM_CHANNEL addr %s, psm 0x%x, local mtu %u", bd_addr_to_str(address), psm, ertm_config->local_mtu);
606474f5c3fSMatthias Ringwald 
607474f5c3fSMatthias Ringwald     // validate local config
6085774a392SMatthias Ringwald     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
609474f5c3fSMatthias Ringwald     if (result) return result;
610474f5c3fSMatthias Ringwald 
611f16129ceSMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, address, BD_ADDR_TYPE_ACL, psm, ertm_config->local_mtu, LEVEL_0);
612474f5c3fSMatthias Ringwald     if (!channel) {
613474f5c3fSMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
614474f5c3fSMatthias Ringwald     }
615474f5c3fSMatthias Ringwald 
616474f5c3fSMatthias Ringwald     // configure ERTM
6179c0e62d3SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
618474f5c3fSMatthias Ringwald 
619474f5c3fSMatthias Ringwald     // add to connections list
620474f5c3fSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
621474f5c3fSMatthias Ringwald 
622474f5c3fSMatthias Ringwald     // store local_cid
623474f5c3fSMatthias Ringwald     if (out_local_cid){
624474f5c3fSMatthias Ringwald        *out_local_cid = channel->local_cid;
625474f5c3fSMatthias Ringwald     }
626474f5c3fSMatthias Ringwald 
627474f5c3fSMatthias Ringwald     // check if hci connection is already usable
628f16129ceSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
629474f5c3fSMatthias Ringwald     if (conn){
630474f5c3fSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
631474f5c3fSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
632474f5c3fSMatthias Ringwald         // check if remote supported fearures are already received
633474f5c3fSMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
634474f5c3fSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
635474f5c3fSMatthias Ringwald         }
636474f5c3fSMatthias Ringwald     }
637474f5c3fSMatthias Ringwald 
638474f5c3fSMatthias Ringwald     l2cap_run();
639474f5c3fSMatthias Ringwald 
640474f5c3fSMatthias Ringwald     return 0;
641474f5c3fSMatthias Ringwald }
642474f5c3fSMatthias Ringwald 
643474f5c3fSMatthias Ringwald static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel){
644474f5c3fSMatthias Ringwald     if (l2cap_ertm_can_store_packet_now(channel)){
645474f5c3fSMatthias Ringwald         channel->waiting_for_can_send_now = 0;
646474f5c3fSMatthias Ringwald         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
647474f5c3fSMatthias Ringwald     }
648474f5c3fSMatthias Ringwald }
649474f5c3fSMatthias Ringwald 
6509c0e62d3SMatthias Ringwald uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
651474f5c3fSMatthias Ringwald 
652474f5c3fSMatthias Ringwald     log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
653f68b21d7SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
654474f5c3fSMatthias Ringwald     if (!channel) {
655474f5c3fSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
656474f5c3fSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
657474f5c3fSMatthias Ringwald     }
658474f5c3fSMatthias Ringwald 
659474f5c3fSMatthias Ringwald     // validate local config
6605774a392SMatthias Ringwald     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
661474f5c3fSMatthias Ringwald     if (result) return result;
662474f5c3fSMatthias Ringwald 
663474f5c3fSMatthias Ringwald     // configure L2CAP ERTM
6649c0e62d3SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
665474f5c3fSMatthias Ringwald 
666836ae835SMatthias Ringwald     // default: continue
667474f5c3fSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
668474f5c3fSMatthias Ringwald 
6698b7155e0SMatthias Ringwald     // verify remote ERTM support
670836ae835SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
671836ae835SMatthias Ringwald     if (connection == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
672836ae835SMatthias Ringwald 
673836ae835SMatthias Ringwald     if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
6748b7155e0SMatthias Ringwald         // ERTM not possible, select basic mode and release buffer
6758b7155e0SMatthias Ringwald         channel->mode = L2CAP_CHANNEL_MODE_BASIC;
6768b7155e0SMatthias Ringwald         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
677836ae835SMatthias Ringwald 
6788b7155e0SMatthias Ringwald         // bail if ERTM is mandatory
679836ae835SMatthias Ringwald         if (channel->ertm_mandatory){
680836ae835SMatthias Ringwald             // We chose 'no resources available' for "ERTM mandatory but you don't even know ERTM exists"
6818b7155e0SMatthias Ringwald             log_info("ERTM mandatory -> reject connection");
682836ae835SMatthias Ringwald             channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
683836ae835SMatthias Ringwald             channel->reason = 0x04; // no resources available
6848b7155e0SMatthias Ringwald         }  else {
6858b7155e0SMatthias Ringwald             log_info("ERTM not supported by remote -> use Basic mode");
686836ae835SMatthias Ringwald         }
687836ae835SMatthias Ringwald     }
688836ae835SMatthias Ringwald 
689474f5c3fSMatthias Ringwald     // process
690474f5c3fSMatthias Ringwald     l2cap_run();
691474f5c3fSMatthias Ringwald 
692474f5c3fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
693474f5c3fSMatthias Ringwald }
694474f5c3fSMatthias Ringwald 
695474f5c3fSMatthias Ringwald uint8_t l2cap_ertm_set_busy(uint16_t local_cid){
696f68b21d7SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
697474f5c3fSMatthias Ringwald     if (!channel) {
698474f5c3fSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
699474f5c3fSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
700474f5c3fSMatthias Ringwald     }
701474f5c3fSMatthias Ringwald     if (!channel->local_busy){
702474f5c3fSMatthias Ringwald         channel->local_busy = 1;
703474f5c3fSMatthias Ringwald         channel->send_supervisor_frame_receiver_not_ready = 1;
704474f5c3fSMatthias Ringwald         l2cap_run();
705474f5c3fSMatthias Ringwald     }
706474f5c3fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
707474f5c3fSMatthias Ringwald }
708474f5c3fSMatthias Ringwald 
709474f5c3fSMatthias Ringwald uint8_t l2cap_ertm_set_ready(uint16_t local_cid){
710f68b21d7SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
711474f5c3fSMatthias Ringwald     if (!channel) {
712474f5c3fSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
713474f5c3fSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
714474f5c3fSMatthias Ringwald     }
715474f5c3fSMatthias Ringwald     if (channel->local_busy){
716474f5c3fSMatthias Ringwald         channel->local_busy = 0;
717474f5c3fSMatthias Ringwald         channel->send_supervisor_frame_receiver_ready_poll = 1;
718474f5c3fSMatthias Ringwald         l2cap_run();
719474f5c3fSMatthias Ringwald     }
720474f5c3fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
721474f5c3fSMatthias Ringwald }
722474f5c3fSMatthias Ringwald 
7231e1a46bbSMatthias Ringwald // Process-ReqSeq
7241e1a46bbSMatthias Ringwald static void l2cap_ertm_process_req_seq(l2cap_channel_t * l2cap_channel, uint8_t req_seq){
725474f5c3fSMatthias Ringwald     int num_buffers_acked = 0;
726474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
72794301352SMatthias Ringwald     log_info("l2cap_ertm_process_req_seq: tx_read_index %u, tx_write_index %u, req_seq %u", l2cap_channel->tx_read_index, l2cap_channel->tx_write_index, req_seq);
728ff3cc4a5SMatthias Ringwald     while (true){
7291e1a46bbSMatthias Ringwald 
73094301352SMatthias Ringwald         // no unack packets left
73194301352SMatthias Ringwald         if (l2cap_channel->unacked_frames == 0) {
7321e1a46bbSMatthias Ringwald             // stop retransmission timer
7331e1a46bbSMatthias Ringwald             l2cap_ertm_stop_retransmission_timer(l2cap_channel);
7341e1a46bbSMatthias Ringwald             break;
7351e1a46bbSMatthias Ringwald         }
7361e1a46bbSMatthias Ringwald 
737474f5c3fSMatthias Ringwald         tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
738474f5c3fSMatthias Ringwald         // calc delta
739474f5c3fSMatthias Ringwald         int delta = (req_seq - tx_state->tx_seq) & 0x03f;
740474f5c3fSMatthias Ringwald         if (delta == 0) break;  // all packets acknowledged
741474f5c3fSMatthias Ringwald         if (delta > l2cap_channel->remote_tx_window_size) break;
742474f5c3fSMatthias Ringwald 
743474f5c3fSMatthias Ringwald         num_buffers_acked++;
744a8409e80SMatthias Ringwald         l2cap_channel->num_stored_tx_frames--;
74594301352SMatthias Ringwald         l2cap_channel->unacked_frames--;
746474f5c3fSMatthias Ringwald         log_info("RR seq %u => packet with tx_seq %u done", req_seq, tx_state->tx_seq);
747474f5c3fSMatthias Ringwald 
748474f5c3fSMatthias Ringwald         l2cap_channel->tx_read_index++;
749474f5c3fSMatthias Ringwald         if (l2cap_channel->tx_read_index >= l2cap_channel->num_rx_buffers){
750474f5c3fSMatthias Ringwald             l2cap_channel->tx_read_index = 0;
751474f5c3fSMatthias Ringwald         }
752474f5c3fSMatthias Ringwald     }
753474f5c3fSMatthias Ringwald     if (num_buffers_acked){
754a8409e80SMatthias Ringwald         log_info("num_buffers_acked %u", num_buffers_acked);
755474f5c3fSMatthias Ringwald     l2cap_ertm_notify_channel_can_send(l2cap_channel);
756474f5c3fSMatthias Ringwald }
757474f5c3fSMatthias Ringwald }
758474f5c3fSMatthias Ringwald 
759474f5c3fSMatthias Ringwald static l2cap_ertm_tx_packet_state_t * l2cap_ertm_get_tx_state(l2cap_channel_t * l2cap_channel, uint8_t tx_seq){
760474f5c3fSMatthias Ringwald     int i;
761474f5c3fSMatthias Ringwald     for (i=0;i<l2cap_channel->num_tx_buffers;i++){
762474f5c3fSMatthias Ringwald         l2cap_ertm_tx_packet_state_t * tx_state = &l2cap_channel->tx_packets_state[i];
763474f5c3fSMatthias Ringwald         if (tx_state->tx_seq == tx_seq) return tx_state;
764474f5c3fSMatthias Ringwald     }
765474f5c3fSMatthias Ringwald     return NULL;
766474f5c3fSMatthias Ringwald }
767474f5c3fSMatthias Ringwald 
768474f5c3fSMatthias Ringwald // @param delta number of frames in the future, >= 1
769122c2b05SMatthias Ringwald // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
7703d244bfaSMatthias Ringwald static void l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel_t * l2cap_channel, l2cap_segmentation_and_reassembly_t sar, int delta, const uint8_t * payload, uint16_t size){
771474f5c3fSMatthias Ringwald     log_info("Store SDU with delta %u", delta);
772474f5c3fSMatthias Ringwald     // get rx state for packet to store
773474f5c3fSMatthias Ringwald     int index = l2cap_channel->rx_store_index + delta - 1;
774474f5c3fSMatthias Ringwald     if (index > l2cap_channel->num_rx_buffers){
775474f5c3fSMatthias Ringwald         index -= l2cap_channel->num_rx_buffers;
776474f5c3fSMatthias Ringwald     }
777474f5c3fSMatthias Ringwald     log_info("Index of packet to store %u", index);
778474f5c3fSMatthias Ringwald     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
779474f5c3fSMatthias Ringwald     // check if buffer is free
780474f5c3fSMatthias Ringwald     if (rx_state->valid){
781474f5c3fSMatthias Ringwald         log_error("Packet buffer already used");
782474f5c3fSMatthias Ringwald         return;
783474f5c3fSMatthias Ringwald     }
784474f5c3fSMatthias Ringwald     rx_state->valid = 1;
785474f5c3fSMatthias Ringwald     rx_state->sar = sar;
786474f5c3fSMatthias Ringwald     rx_state->len = size;
787474f5c3fSMatthias Ringwald     uint8_t * rx_buffer = &l2cap_channel->rx_packets_data[index];
7886535961aSMatthias Ringwald     (void)memcpy(rx_buffer, payload, size);
789474f5c3fSMatthias Ringwald }
790474f5c3fSMatthias Ringwald 
791122c2b05SMatthias Ringwald // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
7923d244bfaSMatthias Ringwald static void l2cap_ertm_handle_in_sequence_sdu(l2cap_channel_t * l2cap_channel, l2cap_segmentation_and_reassembly_t sar, const uint8_t * payload, uint16_t size){
793122c2b05SMatthias Ringwald     uint16_t reassembly_sdu_length;
794474f5c3fSMatthias Ringwald     switch (sar){
795474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
796122c2b05SMatthias Ringwald             // assert total packet size <= our mtu
797122c2b05SMatthias Ringwald             if (size > l2cap_channel->local_mtu) break;
798474f5c3fSMatthias Ringwald             // packet complete -> disapatch
7993d244bfaSMatthias Ringwald             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, (uint8_t*) payload, size);
800474f5c3fSMatthias Ringwald             break;
801474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
802122c2b05SMatthias Ringwald             // read SDU len
803122c2b05SMatthias Ringwald             reassembly_sdu_length = little_endian_read_16(payload, 0);
804474f5c3fSMatthias Ringwald             payload += 2;
805474f5c3fSMatthias Ringwald             size    -= 2;
806122c2b05SMatthias Ringwald             // assert reassembled size <= our mtu
807122c2b05SMatthias Ringwald             if (reassembly_sdu_length > l2cap_channel->local_mtu) break;
808122c2b05SMatthias Ringwald             // store start segment
809122c2b05SMatthias Ringwald             l2cap_channel->reassembly_sdu_length = reassembly_sdu_length;
8106535961aSMatthias Ringwald             (void)memcpy(&l2cap_channel->reassembly_buffer[0], payload, size);
811474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos = size;
812474f5c3fSMatthias Ringwald             break;
813474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
814122c2b05SMatthias Ringwald             // assert size of reassembled data <= our mtu
815122c2b05SMatthias Ringwald             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
816122c2b05SMatthias Ringwald             // store continuation segment
8176535961aSMatthias Ringwald             (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
8186535961aSMatthias Ringwald                          payload, size);
819474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos += size;
820474f5c3fSMatthias Ringwald             break;
821474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
822122c2b05SMatthias Ringwald             // assert size of reassembled data <= our mtu
823122c2b05SMatthias Ringwald             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
824122c2b05SMatthias Ringwald             // store continuation segment
8256535961aSMatthias Ringwald             (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
8266535961aSMatthias Ringwald                          payload, size);
827474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos += size;
828122c2b05SMatthias Ringwald             // assert size of reassembled data matches announced sdu length
829122c2b05SMatthias Ringwald             if (l2cap_channel->reassembly_pos != l2cap_channel->reassembly_sdu_length) break;
830474f5c3fSMatthias Ringwald             // packet complete -> disapatch
831474f5c3fSMatthias Ringwald             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->reassembly_buffer, l2cap_channel->reassembly_pos);
832474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos = 0;
833474f5c3fSMatthias Ringwald             break;
834474f5c3fSMatthias Ringwald     }
835474f5c3fSMatthias Ringwald }
836474f5c3fSMatthias Ringwald 
837d89ab698SMatthias Ringwald static void l2cap_ertm_channel_send_information_frame(l2cap_channel_t * channel){
838d89ab698SMatthias Ringwald     channel->unacked_frames++;
839d89ab698SMatthias Ringwald     int index = channel->tx_send_index;
840d89ab698SMatthias Ringwald     channel->tx_send_index++;
841d89ab698SMatthias Ringwald     if (channel->tx_send_index >= channel->num_tx_buffers){
842d89ab698SMatthias Ringwald         channel->tx_send_index = 0;
843d89ab698SMatthias Ringwald     }
844d89ab698SMatthias Ringwald     l2cap_ertm_send_information_frame(channel, index, 0);   // final = 0
845d89ab698SMatthias Ringwald }
846d89ab698SMatthias Ringwald 
84785ddcd84SMatthias Ringwald #endif
84885ddcd84SMatthias Ringwald 
8496a5ffed8SMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
8506ddef68dSMilanka Ringwald static uint16_t l2cap_next_local_cid(void){
8516268fbfeSMilanka Ringwald     do {
8526268fbfeSMilanka Ringwald         if (local_source_cid == 0xffff) {
8536268fbfeSMilanka Ringwald             local_source_cid = 0x40;
8546268fbfeSMilanka Ringwald         } else {
8556268fbfeSMilanka Ringwald             local_source_cid++;
8566268fbfeSMilanka Ringwald         }
8576268fbfeSMilanka Ringwald     } while (l2cap_get_channel_for_local_cid(local_source_cid) != NULL);
8586268fbfeSMilanka Ringwald     return local_source_cid;
8596ddef68dSMilanka Ringwald }
8606a5ffed8SMatthias Ringwald #endif
8616ddef68dSMilanka Ringwald 
8626ddef68dSMilanka Ringwald static uint8_t l2cap_next_sig_id(void){
8636ddef68dSMilanka Ringwald     if (sig_seq_nr == 0xff) {
8646ddef68dSMilanka Ringwald         sig_seq_nr = 1;
8656ddef68dSMilanka Ringwald     } else {
8666ddef68dSMilanka Ringwald         sig_seq_nr++;
8676ddef68dSMilanka Ringwald     }
8686ddef68dSMilanka Ringwald     return sig_seq_nr;
8696ddef68dSMilanka Ringwald }
8706ddef68dSMilanka Ringwald 
87171de195eSMatthias Ringwald void l2cap_init(void){
8722b83fb7dSmatthias.ringwald     signaling_responses_pending = 0;
873808a48abSmatthias.ringwald 
874f5454fc6Smatthias.ringwald     l2cap_channels = NULL;
875fad84cafSMatthias Ringwald 
876fad84cafSMatthias Ringwald #ifdef ENABLE_CLASSIC
877f5454fc6Smatthias.ringwald     l2cap_services = NULL;
87809e9d05bSMatthias Ringwald     require_security_level2_for_outgoing_sdp = 0;
879fad84cafSMatthias Ringwald 
880fad84cafSMatthias Ringwald     // Setup Connectionless Channel
881fad84cafSMatthias Ringwald     l2cap_fixed_channel_connectionless.local_cid     = L2CAP_CID_CONNECTIONLESS_CHANNEL;
8827740e150SMatthias Ringwald     l2cap_fixed_channel_connectionless.channel_type  = L2CAP_CHANNEL_TYPE_CONNECTIONLESS;
883fad84cafSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_connectionless);
88409e9d05bSMatthias Ringwald #endif
885a3dc965aSMatthias Ringwald 
886a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
8877192e786SMatthias Ringwald     l2cap_le_services = NULL;
888a3dc965aSMatthias Ringwald #endif
889f5454fc6Smatthias.ringwald 
890d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
89133c40538SMatthias Ringwald     l2cap_event_packet_handler = NULL;
89225818320SMatthias Ringwald     l2cap_le_custom_max_mtu = 0;
893fad84cafSMatthias Ringwald 
894fad84cafSMatthias Ringwald     // Setup fixed ATT Channel
895fad84cafSMatthias Ringwald     l2cap_fixed_channel_att.local_cid    = L2CAP_CID_ATTRIBUTE_PROTOCOL;
8967740e150SMatthias Ringwald     l2cap_fixed_channel_att.channel_type = L2CAP_CHANNEL_TYPE_LE_FIXED;
897fad84cafSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_att);
898fad84cafSMatthias Ringwald 
899fad84cafSMatthias Ringwald     // Setup fixed SM Channel
900fad84cafSMatthias Ringwald     l2cap_fixed_channel_sm.local_cid     = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
9017740e150SMatthias Ringwald     l2cap_fixed_channel_sm.channel_type  = L2CAP_CHANNEL_TYPE_LE_FIXED;
902fad84cafSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_sm);
903d6ed9f9cSMatthias Ringwald #endif
904f5454fc6Smatthias.ringwald 
905fcadd0caSmatthias.ringwald     //
9062718e2e7Smatthias.ringwald     // register callback with HCI
907fcadd0caSmatthias.ringwald     //
908d9a7306aSMatthias Ringwald     hci_event_callback_registration.callback = &l2cap_hci_event_handler;
909fb37a842SMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
910fb37a842SMatthias Ringwald 
911d9a7306aSMatthias Ringwald     hci_register_acl_packet_handler(&l2cap_acl_handler);
912fb37a842SMatthias Ringwald 
913be005ed6SMatthias Ringwald #ifdef ENABLE_CLASSIC
91415a95bd5SMatthias Ringwald     gap_connectable_control(0); // no services yet
915be005ed6SMatthias Ringwald #endif
916fcadd0caSmatthias.ringwald }
917fcadd0caSmatthias.ringwald 
918ffbf8201SMatthias Ringwald void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
919d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
92033c40538SMatthias Ringwald     l2cap_event_packet_handler = handler;
921d6ed9f9cSMatthias Ringwald #else
9225774a392SMatthias Ringwald     UNUSED(handler);    // ok: no code
923d6ed9f9cSMatthias Ringwald #endif
9241e6aba47Smatthias.ringwald }
9251e6aba47Smatthias.ringwald 
92609e9d05bSMatthias Ringwald void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
927fad84cafSMatthias Ringwald     UNUSED(con_handle);  // ok: there is no con handle
9289ec2630cSMatthias Ringwald 
929f68b21d7SMatthias Ringwald     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
930fad84cafSMatthias Ringwald     if (!channel) return;
931fad84cafSMatthias Ringwald     channel->waiting_for_can_send_now = 1;
93209e9d05bSMatthias Ringwald     l2cap_notify_channel_can_send();
93309e9d05bSMatthias Ringwald }
93409e9d05bSMatthias Ringwald 
93509e9d05bSMatthias Ringwald int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
9365774a392SMatthias Ringwald     UNUSED(channel_id); // ok: only depends on Controller LE buffers
9379ec2630cSMatthias Ringwald 
93809e9d05bSMatthias Ringwald     return hci_can_send_acl_packet_now(con_handle);
93909e9d05bSMatthias Ringwald }
94009e9d05bSMatthias Ringwald 
94109e9d05bSMatthias Ringwald uint8_t *l2cap_get_outgoing_buffer(void){
94209e9d05bSMatthias Ringwald     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
94309e9d05bSMatthias Ringwald }
94409e9d05bSMatthias Ringwald 
9454e6fa3a2SMatthias Ringwald // only for L2CAP Basic Channels
94609e9d05bSMatthias Ringwald int l2cap_reserve_packet_buffer(void){
94709e9d05bSMatthias Ringwald     return hci_reserve_packet_buffer();
94809e9d05bSMatthias Ringwald }
94909e9d05bSMatthias Ringwald 
9504e6fa3a2SMatthias Ringwald // only for L2CAP Basic Channels
95109e9d05bSMatthias Ringwald void l2cap_release_packet_buffer(void){
95209e9d05bSMatthias Ringwald     hci_release_packet_buffer();
95309e9d05bSMatthias Ringwald }
95409e9d05bSMatthias Ringwald 
955f511cefaSMatthias Ringwald static void l2cap_setup_header(uint8_t * acl_buffer, hci_con_handle_t con_handle, uint8_t packet_boundary, uint16_t remote_cid, uint16_t len){
95609e9d05bSMatthias Ringwald     // 0 - Connection handle : PB=pb : BC=00
957f511cefaSMatthias Ringwald     little_endian_store_16(acl_buffer, 0, con_handle | (packet_boundary << 12) | (0 << 14));
95809e9d05bSMatthias Ringwald     // 2 - ACL length
95909e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 2,  len + 4);
96009e9d05bSMatthias Ringwald     // 4 - L2CAP packet length
96109e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 4,  len + 0);
96209e9d05bSMatthias Ringwald     // 6 - L2CAP channel DEST
96309e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 6,  remote_cid);
96409e9d05bSMatthias Ringwald }
96509e9d05bSMatthias Ringwald 
966f511cefaSMatthias Ringwald // assumption - only on LE connections
96709e9d05bSMatthias Ringwald int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
96809e9d05bSMatthias Ringwald 
96909e9d05bSMatthias Ringwald     if (!hci_is_packet_buffer_reserved()){
97009e9d05bSMatthias Ringwald         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
97109e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
97209e9d05bSMatthias Ringwald     }
97309e9d05bSMatthias Ringwald 
97409e9d05bSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
97509e9d05bSMatthias Ringwald         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
97609e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
97709e9d05bSMatthias Ringwald     }
97809e9d05bSMatthias Ringwald 
97909e9d05bSMatthias Ringwald     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
98009e9d05bSMatthias Ringwald 
98109e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
982f511cefaSMatthias Ringwald     l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
98309e9d05bSMatthias Ringwald     // send
98409e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len+8);
98509e9d05bSMatthias Ringwald }
98609e9d05bSMatthias Ringwald 
987f511cefaSMatthias Ringwald // assumption - only on LE connections
98809e9d05bSMatthias Ringwald int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
98909e9d05bSMatthias Ringwald 
99009e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(con_handle)){
99109e9d05bSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", cid);
99209e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
99309e9d05bSMatthias Ringwald     }
99409e9d05bSMatthias Ringwald 
99509e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
99609e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
99709e9d05bSMatthias Ringwald 
9986535961aSMatthias Ringwald     (void)memcpy(&acl_buffer[8], data, len);
99909e9d05bSMatthias Ringwald 
100009e9d05bSMatthias Ringwald     return l2cap_send_prepared_connectionless(con_handle, cid, len);
100109e9d05bSMatthias Ringwald }
100209e9d05bSMatthias Ringwald 
100309e9d05bSMatthias Ringwald static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
1004d9d23054SMatthias Ringwald     log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
100509e9d05bSMatthias Ringwald     uint8_t event[4];
100609e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
100709e9d05bSMatthias Ringwald     event[1] = sizeof(event) - 2;
100809e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, channel);
100909e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
101009e9d05bSMatthias Ringwald     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
101109e9d05bSMatthias Ringwald }
101209e9d05bSMatthias Ringwald 
101309e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
101417a9b554SMatthias Ringwald static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
101558de5610Smatthias.ringwald     (* (channel->packet_handler))(type, channel->local_cid, data, size);
101658de5610Smatthias.ringwald }
101758de5610Smatthias.ringwald 
101844276248SMatthias Ringwald static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
101944276248SMatthias Ringwald     uint8_t event[4];
102044276248SMatthias Ringwald     event[0] = event_code;
102144276248SMatthias Ringwald     event[1] = sizeof(event) - 2;
102244276248SMatthias Ringwald     little_endian_store_16(event, 2, channel->local_cid);
102344276248SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
102444276248SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
102544276248SMatthias Ringwald }
102609e9d05bSMatthias Ringwald #endif
102744276248SMatthias Ringwald 
102809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
102958de5610Smatthias.ringwald void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
1030c9dc710bS[email protected]     log_info("L2CAP_EVENT_CHANNEL_OPENED status 0x%x addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x local_mtu %u, remote_mtu %u, flush_timeout %u",
1031fc64f94aSMatthias Ringwald              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
1032c9dc710bS[email protected]              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
10337f1690cfSMatthias Ringwald     uint8_t event[26];
103458de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
103558de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
103658de5610Smatthias.ringwald     event[2] = status;
1037724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
1038fc64f94aSMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
1039f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
1040f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
1041f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
1042f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 17, channel->local_mtu);
1043f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 19, channel->remote_mtu);
1044f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 21, channel->flush_timeout);
1045c1ab6cc1SMatthias Ringwald     event[23] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
10467f1690cfSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
10477f1690cfSMatthias Ringwald     log_info("ERTM mode %u, fcs enabled %u", channel->mode, channel->fcs_option);
10487f1690cfSMatthias Ringwald     event[24] = channel->mode;
10497f1690cfSMatthias Ringwald     event[25] = channel->fcs_option;
10507f1690cfSMatthias Ringwald 
10517f1690cfSMatthias Ringwald #else
10527f1690cfSMatthias Ringwald     event[24] = L2CAP_CHANNEL_MODE_BASIC;
10537f1690cfSMatthias Ringwald     event[25] = 0;
10547f1690cfSMatthias Ringwald #endif
105558de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
105617a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
105758de5610Smatthias.ringwald }
105858de5610Smatthias.ringwald 
105944276248SMatthias Ringwald static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
1060e0abb8e7S[email protected]     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
106144276248SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
106258de5610Smatthias.ringwald }
106358de5610Smatthias.ringwald 
106444276248SMatthias Ringwald static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
1065e0abb8e7S[email protected]     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
1066fc64f94aSMatthias Ringwald              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
106758de5610Smatthias.ringwald     uint8_t event[16];
106858de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
106958de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
1070724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[2]);
1071fc64f94aSMatthias Ringwald     little_endian_store_16(event,  8, channel->con_handle);
1072f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 10, channel->psm);
1073f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 12, channel->local_cid);
1074f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 14, channel->remote_cid);
107558de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
107617a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
10770af41d30Smatthias.ringwald }
1078f62db1e3Smatthias.ringwald 
107966a72640SMatthias Ringwald static void l2cap_handle_channel_open_failed(l2cap_channel_t * channel, uint8_t status){
108066a72640SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
108166a72640SMatthias Ringwald     // emit ertm buffer released, as it's not needed. if in basic mode, it was either not allocated or already released
108266a72640SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
108366a72640SMatthias Ringwald         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
108466a72640SMatthias Ringwald     }
108566a72640SMatthias Ringwald #endif
1086624873c3SMatthias Ringwald     l2cap_emit_channel_opened(channel, status);
1087624873c3SMatthias Ringwald }
1088624873c3SMatthias Ringwald 
108966a72640SMatthias Ringwald static void l2cap_handle_channel_closed(l2cap_channel_t * channel){
109066a72640SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
109166a72640SMatthias Ringwald     // emit ertm buffer released, as it's not needed anymore. if in basic mode, it was either not allocated or already released
109266a72640SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
109366a72640SMatthias Ringwald         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
109466a72640SMatthias Ringwald     }
109566a72640SMatthias Ringwald #endif
109666a72640SMatthias Ringwald     l2cap_emit_channel_closed(channel);
109766a72640SMatthias Ringwald }
1098dd3bf36fSMatthias Ringwald #endif
1099dd3bf36fSMatthias Ringwald 
1100dd3bf36fSMatthias Ringwald static l2cap_fixed_channel_t * l2cap_channel_item_by_cid(uint16_t cid){
1101dd3bf36fSMatthias Ringwald     btstack_linked_list_iterator_t it;
1102dd3bf36fSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1103dd3bf36fSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1104dd3bf36fSMatthias Ringwald         l2cap_fixed_channel_t * channel = (l2cap_fixed_channel_t*) btstack_linked_list_iterator_next(&it);
1105dd3bf36fSMatthias Ringwald         if (channel->local_cid == cid) {
1106dd3bf36fSMatthias Ringwald             return channel;
1107dd3bf36fSMatthias Ringwald         }
1108dd3bf36fSMatthias Ringwald     }
1109dd3bf36fSMatthias Ringwald     return NULL;
1110dd3bf36fSMatthias Ringwald }
111166a72640SMatthias Ringwald 
1112fad84cafSMatthias Ringwald // used for fixed channels in LE (ATT/SM) and Classic (Connectionless Channel). CID < 0x04
1113fad84cafSMatthias Ringwald static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid){
1114fad84cafSMatthias Ringwald     if (local_cid >= 0x40) return NULL;
1115fad84cafSMatthias Ringwald     return (l2cap_fixed_channel_t*) l2cap_channel_item_by_cid(local_cid);
1116fad84cafSMatthias Ringwald }
111724eb964eSMatthias Ringwald 
111824eb964eSMatthias Ringwald // used for Classic Channels + LE Data Channels. local_cid >= 0x40
111924eb964eSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
112024eb964eSMatthias Ringwald static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
112124eb964eSMatthias Ringwald     if (local_cid < 0x40) return NULL;
112224eb964eSMatthias Ringwald     return (l2cap_channel_t*) l2cap_channel_item_by_cid(local_cid);
112324eb964eSMatthias Ringwald }
11240b9d7e78SMatthias Ringwald 
112530725612SMatthias Ringwald void l2cap_request_can_send_now_event(uint16_t local_cid){
112630725612SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
112730725612SMatthias Ringwald     if (!channel) return;
112830725612SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
112996646001SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
113096646001SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
113196646001SMatthias Ringwald         l2cap_ertm_notify_channel_can_send(channel);
113296646001SMatthias Ringwald         return;
113396646001SMatthias Ringwald     }
113496646001SMatthias Ringwald #endif
113530725612SMatthias Ringwald     l2cap_notify_channel_can_send();
113630725612SMatthias Ringwald }
113730725612SMatthias Ringwald 
113896646001SMatthias Ringwald int  l2cap_can_send_packet_now(uint16_t local_cid){
113996646001SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
114096646001SMatthias Ringwald     if (!channel) return 0;
114196646001SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
114296646001SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
114396646001SMatthias Ringwald         return l2cap_ertm_can_store_packet_now(channel);
114496646001SMatthias Ringwald     }
114596646001SMatthias Ringwald #endif
11460b9d7e78SMatthias Ringwald     return hci_can_send_acl_packet_now(channel->con_handle);
11477856fb31S[email protected] }
11487856fb31S[email protected] 
114983e7cdd9SMatthias Ringwald int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
115083e7cdd9SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
115183e7cdd9SMatthias Ringwald     if (!channel) return 0;
11520b20b13bSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
11530b20b13bSMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
11540b20b13bSMatthias Ringwald         return 0;
11550b20b13bSMatthias Ringwald     }
11560b20b13bSMatthias Ringwald #endif
11570b9d7e78SMatthias Ringwald     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
115883e7cdd9SMatthias Ringwald }
11590b20b13bSMatthias Ringwald 
116096cbd662Smatthias.ringwald uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
116196cbd662Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
116296cbd662Smatthias.ringwald     if (channel) {
116396cbd662Smatthias.ringwald         return channel->remote_mtu;
116496cbd662Smatthias.ringwald     }
116596cbd662Smatthias.ringwald     return 0;
116696cbd662Smatthias.ringwald }
116724eb964eSMatthias Ringwald #endif
116896cbd662Smatthias.ringwald 
116924eb964eSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
1170fad84cafSMatthias Ringwald static int l2cap_is_dynamic_channel_type(l2cap_channel_type_t channel_type){
1171fad84cafSMatthias Ringwald     switch (channel_type){
1172fad84cafSMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CLASSIC:
1173fad84cafSMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
1174fad84cafSMatthias Ringwald             return 1;
1175fad84cafSMatthias Ringwald         default:
1176fad84cafSMatthias Ringwald             return 0;
1177fad84cafSMatthias Ringwald     }
1178fad84cafSMatthias Ringwald }
117924eb964eSMatthias Ringwald #endif
1180fad84cafSMatthias Ringwald 
118124eb964eSMatthias Ringwald #ifdef ENABLE_CLASSIC
1182fad84cafSMatthias Ringwald // RTX Timer only exist for dynamic channels
1183ec820d77SMatthias Ringwald static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
1184665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1185665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1186665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1187665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1188fad84cafSMatthias Ringwald         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
11895932bd7cS[email protected]         if (&channel->rtx == ts) {
11905932bd7cS[email protected]             return channel;
11915932bd7cS[email protected]         }
11925932bd7cS[email protected]     }
11935932bd7cS[email protected]     return NULL;
11945932bd7cS[email protected] }
11955932bd7cS[email protected] 
1196ec820d77SMatthias Ringwald static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
11975932bd7cS[email protected]     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
119895d2c8f4SMatthias Ringwald     if (!channel) return;
11995932bd7cS[email protected] 
12005932bd7cS[email protected]     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
12015932bd7cS[email protected] 
12025932bd7cS[email protected]     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
12035932bd7cS[email protected]     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
12045932bd7cS[email protected]     // notify client
120566a72640SMatthias Ringwald     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
12065932bd7cS[email protected] 
12075932bd7cS[email protected]     // discard channel
1208665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1209c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
12105932bd7cS[email protected] }
12115932bd7cS[email protected] 
121213aa3e4bSMatthias Ringwald #endif
121313aa3e4bSMatthias Ringwald 
121413aa3e4bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
12155932bd7cS[email protected] static void l2cap_stop_rtx(l2cap_channel_t * channel){
12165932bd7cS[email protected]     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
1217528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->rtx);
12185932bd7cS[email protected] }
121913aa3e4bSMatthias Ringwald #endif
122013aa3e4bSMatthias Ringwald 
122113aa3e4bSMatthias Ringwald #ifdef ENABLE_CLASSIC
12225932bd7cS[email protected] 
12235932bd7cS[email protected] static void l2cap_start_rtx(l2cap_channel_t * channel){
12245932bd7cS[email protected]     l2cap_stop_rtx(channel);
1225cb0ff06bS[email protected]     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
1226528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1227528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
1228528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
12295932bd7cS[email protected] }
12305932bd7cS[email protected] 
12315932bd7cS[email protected] static void l2cap_start_ertx(l2cap_channel_t * channel){
12325932bd7cS[email protected]     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
12335932bd7cS[email protected]     l2cap_stop_rtx(channel);
1234528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1235528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
1236528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
12375932bd7cS[email protected] }
12385932bd7cS[email protected] 
123971de195eSMatthias Ringwald void l2cap_require_security_level_2_for_outgoing_sdp(void){
1240ac301f95S[email protected]     require_security_level2_for_outgoing_sdp = 1;
1241ac301f95S[email protected] }
1242ac301f95S[email protected] 
1243df3354fcS[email protected] static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
124484e3541eSMilanka Ringwald     return (psm == BLUETOOTH_PSM_SDP) && (!require_security_level2_for_outgoing_sdp);
1245df3354fcS[email protected] }
12465932bd7cS[email protected] 
124763854e74SMatthias Ringwald static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1248a35252c8S[email protected]     if (!hci_can_send_acl_packet_now(handle)){
12499da54300S[email protected]         log_info("l2cap_send_signaling_packet, cannot send");
1250b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
1251b1d43497Smatthias.ringwald     }
1252b1d43497Smatthias.ringwald 
12539da54300S[email protected]     // log_info("l2cap_send_signaling_packet type %u", cmd);
12542a373862S[email protected]     hci_reserve_packet_buffer();
1255facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
125658de5610Smatthias.ringwald     va_list argptr;
125758de5610Smatthias.ringwald     va_start(argptr, identifier);
125870efece1S[email protected]     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
125958de5610Smatthias.ringwald     va_end(argptr);
12609da54300S[email protected]     // log_info("l2cap_send_signaling_packet con %u!", handle);
1261826f7347S[email protected]     return hci_send_acl_packet_buffer(len);
126258de5610Smatthias.ringwald }
126358de5610Smatthias.ringwald 
1264f511cefaSMatthias Ringwald // assumption - only on Classic connections
12654e6fa3a2SMatthias Ringwald // cannot be used for L2CAP ERTM
1266b1d43497Smatthias.ringwald int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
1267b1d43497Smatthias.ringwald 
1268c8b9416aS[email protected]     if (!hci_is_packet_buffer_reserved()){
1269c8b9416aS[email protected]         log_error("l2cap_send_prepared called without reserving packet first");
1270c8b9416aS[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
1271c8b9416aS[email protected]     }
1272c8b9416aS[email protected] 
127358de5610Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1274b1d43497Smatthias.ringwald     if (!channel) {
12759da54300S[email protected]         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
1276b1d43497Smatthias.ringwald         return -1;   // TODO: define error
12776218e6f1Smatthias.ringwald     }
12786218e6f1Smatthias.ringwald 
1279fc64f94aSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
12809da54300S[email protected]         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
1281a35252c8S[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
1282a35252c8S[email protected]     }
1283a35252c8S[email protected] 
1284fc64f94aSMatthias Ringwald     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
1285b1d43497Smatthias.ringwald 
128685ddcd84SMatthias Ringwald     int fcs_size = 0;
128785ddcd84SMatthias Ringwald 
128885ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
12896574158aSMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->fcs_option){
129085ddcd84SMatthias Ringwald         fcs_size = 2;
129185ddcd84SMatthias Ringwald     }
129285ddcd84SMatthias Ringwald #endif
129385ddcd84SMatthias Ringwald 
1294f511cefaSMatthias Ringwald     // set non-flushable packet boundary flag if supported on Controller
1295facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1296f511cefaSMatthias Ringwald     uint8_t packet_boundary_flag = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
129785ddcd84SMatthias Ringwald     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
129885ddcd84SMatthias Ringwald 
129985ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1300b72f6906SMatthias Ringwald     if (fcs_size){
130185ddcd84SMatthias Ringwald         // calculate FCS over l2cap data
130285ddcd84SMatthias Ringwald         uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
130385ddcd84SMatthias Ringwald         log_info("I-Frame: fcs 0x%04x", fcs);
130485ddcd84SMatthias Ringwald         little_endian_store_16(acl_buffer, 8 + len, fcs);
130558de5610Smatthias.ringwald     }
130685ddcd84SMatthias Ringwald #endif
130785ddcd84SMatthias Ringwald 
130885ddcd84SMatthias Ringwald     // send
130985ddcd84SMatthias Ringwald     return hci_send_acl_packet_buffer(len+8+fcs_size);
131085ddcd84SMatthias Ringwald }
131185ddcd84SMatthias Ringwald 
1312f511cefaSMatthias Ringwald // assumption - only on Classic connections
1313ce8f182eSMatthias Ringwald int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
1314a35252c8S[email protected]     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1315a35252c8S[email protected]     if (!channel) {
1316ce8f182eSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
1317a35252c8S[email protected]         return -1;   // TODO: define error
1318a35252c8S[email protected]     }
1319a35252c8S[email protected] 
1320f0fb4cd7SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1321f0fb4cd7SMatthias Ringwald     // send in ERTM
1322f0fb4cd7SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1323f0fb4cd7SMatthias Ringwald         return l2cap_ertm_send(channel, data, len);
1324f0fb4cd7SMatthias Ringwald     }
1325f0fb4cd7SMatthias Ringwald #endif
1326f0fb4cd7SMatthias Ringwald 
1327f0efaa57S[email protected]     if (len > channel->remote_mtu){
1328ce8f182eSMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
1329f0efaa57S[email protected]         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
1330f0efaa57S[email protected]     }
1331f0efaa57S[email protected] 
1332fc64f94aSMatthias Ringwald     if (!hci_can_send_acl_packet_now(channel->con_handle)){
1333ce8f182eSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
1334b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
1335b1d43497Smatthias.ringwald     }
1336b1d43497Smatthias.ringwald 
13372a373862S[email protected]     hci_reserve_packet_buffer();
1338facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
13396535961aSMatthias Ringwald     (void)memcpy(&acl_buffer[8], data, len);
1340f0fb4cd7SMatthias Ringwald     return l2cap_send_prepared(local_cid, len);
1341b1d43497Smatthias.ringwald }
1342b1d43497Smatthias.ringwald 
1343fc64f94aSMatthias Ringwald int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
1344fc64f94aSMatthias Ringwald     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
13450e37e417S[email protected] }
13460e37e417S[email protected] 
134728ca2b46S[email protected] static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
134828ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
134928ca2b46S[email protected] }
135028ca2b46S[email protected] 
135128ca2b46S[email protected] static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
135228ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
135328ca2b46S[email protected] }
135409e9d05bSMatthias Ringwald #endif
135528ca2b46S[email protected] 
135628ca2b46S[email protected] 
135709e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
135863854e74SMatthias Ringwald static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
135909e9d05bSMatthias Ringwald 
136009e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(handle)){
136109e9d05bSMatthias Ringwald         log_info("l2cap_send_le_signaling_packet, cannot send");
136209e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
136309e9d05bSMatthias Ringwald     }
136409e9d05bSMatthias Ringwald 
136509e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
136609e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
136709e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
136809e9d05bSMatthias Ringwald     va_list argptr;
136909e9d05bSMatthias Ringwald     va_start(argptr, identifier);
137009e9d05bSMatthias Ringwald     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
137109e9d05bSMatthias Ringwald     va_end(argptr);
137209e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
137309e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len);
137409e9d05bSMatthias Ringwald }
137509e9d05bSMatthias Ringwald #endif
137609e9d05bSMatthias Ringwald 
137709e9d05bSMatthias Ringwald uint16_t l2cap_max_mtu(void){
137809e9d05bSMatthias Ringwald     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
137909e9d05bSMatthias Ringwald }
138009e9d05bSMatthias Ringwald 
13813e329ddfSandryblack #ifdef ENABLE_BLE
138209e9d05bSMatthias Ringwald uint16_t l2cap_max_le_mtu(void){
138325818320SMatthias Ringwald     if (l2cap_le_custom_max_mtu != 0) return l2cap_le_custom_max_mtu;
138409e9d05bSMatthias Ringwald     return l2cap_max_mtu();
138509e9d05bSMatthias Ringwald }
1386b1d43497Smatthias.ringwald 
138725818320SMatthias Ringwald void l2cap_set_max_le_mtu(uint16_t max_mtu){
138825818320SMatthias Ringwald     if (max_mtu < l2cap_max_mtu()){
138925818320SMatthias Ringwald         l2cap_le_custom_max_mtu = max_mtu;
139025818320SMatthias Ringwald     }
139125818320SMatthias Ringwald }
13923e329ddfSandryblack #endif
139325818320SMatthias Ringwald 
1394d2afdd38SMatthias Ringwald #ifdef ENABLE_CLASSIC
1395d2afdd38SMatthias Ringwald 
13966b99230fSMatthias Ringwald static uint16_t l2cap_setup_options_mtu(uint8_t * config_options, uint16_t mtu){
1397d64e9771SMatthias Ringwald     config_options[0] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
1398d2afdd38SMatthias Ringwald     config_options[1] = 2; // len param
13996b99230fSMatthias Ringwald     little_endian_store_16(config_options, 2, mtu);
1400d2afdd38SMatthias Ringwald     return 4;
1401d2afdd38SMatthias Ringwald }
1402d2afdd38SMatthias Ringwald 
1403450ad7ecSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
14046b99230fSMatthias Ringwald static int l2cap_ertm_mode(l2cap_channel_t * channel){
1405450ad7ecSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
14066b99230fSMatthias Ringwald     return ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE)
14076b99230fSMatthias Ringwald         &&  (connection->l2cap_state.extended_feature_mask & 0x08));
1408450ad7ecSMatthias Ringwald }
1409450ad7ecSMatthias Ringwald #endif
14106b99230fSMatthias Ringwald 
14116b99230fSMatthias Ringwald static uint16_t l2cap_setup_options_request(l2cap_channel_t * channel, uint8_t * config_options){
14126b99230fSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1413313d3a26SMatthias Ringwald     // use ERTM options if supported by remote and channel ready to use it
1414313d3a26SMatthias Ringwald     if (l2cap_ertm_mode(channel) && channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
14157cbe539fSMatthias Ringwald         return l2cap_setup_options_ertm_request(channel, config_options);
14166b99230fSMatthias Ringwald     }
14176b99230fSMatthias Ringwald #endif
14186b99230fSMatthias Ringwald     uint16_t mtu = channel->local_mtu;
14196b99230fSMatthias Ringwald     return l2cap_setup_options_mtu(config_options, mtu);
14206b99230fSMatthias Ringwald }
14216b99230fSMatthias Ringwald 
1422b8134563SMatthias Ringwald static uint16_t l2cap_setup_options_mtu_response(l2cap_channel_t * channel, uint8_t * config_options){
142332717978SMatthias Ringwald     uint16_t mtu = btstack_min(channel->local_mtu, channel->remote_mtu);
14246b99230fSMatthias Ringwald     return l2cap_setup_options_mtu(config_options, mtu);
14256dca2a0cSMatthias Ringwald }
14266dca2a0cSMatthias Ringwald 
14271b9cb13dSMatthias Ringwald static uint32_t l2cap_extended_features_mask(void){
14281b9cb13dSMatthias Ringwald     // extended features request supported, features: fixed channels, unicast connectionless data reception
14291b9cb13dSMatthias Ringwald     uint32_t features = 0x280;
14301b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
143154901195SMatthias Ringwald     features |= 0x0028;
14321b9cb13dSMatthias Ringwald #endif
14331b9cb13dSMatthias Ringwald     return features;
14341b9cb13dSMatthias Ringwald }
1435d2afdd38SMatthias Ringwald #endif
14361b9cb13dSMatthias Ringwald 
14373a600bd4SMatthias Ringwald //
1438b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
14393a600bd4SMatthias Ringwald static void l2cap_run_for_classic_channel(l2cap_channel_t * channel){
144009e9d05bSMatthias Ringwald 
1441f2c70799Sandryblack #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1442f2c70799Sandryblack     uint8_t  config_options[18];
1443f2c70799Sandryblack #else
144443ec931dSMatthias Ringwald     uint8_t  config_options[10];
1445f2c70799Sandryblack #endif
1446baf94f06S[email protected] 
14472cd0be45Smatthias.ringwald     switch (channel->state){
14482cd0be45Smatthias.ringwald 
1449df3354fcS[email protected]         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1450ad671560S[email protected]         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
1451fc64f94aSMatthias Ringwald             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1452a00031e2S[email protected]             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
1453ad671560S[email protected]                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
1454fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
1455ad671560S[email protected]             }
1456ad671560S[email protected]             break;
1457ad671560S[email protected] 
145802b22dc4Smatthias.ringwald         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1459baf94f06S[email protected]             if (!hci_can_send_command_packet_now()) break;
146064472d52Smatthias.ringwald             // send connection request - set state first
146164472d52Smatthias.ringwald             channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
146202b22dc4Smatthias.ringwald             // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
14636535961aSMatthias Ringwald             (void)memcpy(l2cap_outgoing_classic_addr, channel->address, 6);
14648f8108aaSmatthias.ringwald             hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
146502b22dc4Smatthias.ringwald             break;
146602b22dc4Smatthias.ringwald 
1467e7ff783cSmatthias.ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
1468fc64f94aSMatthias Ringwald             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
146922c29ab4SMatthias Ringwald             channel->state = L2CAP_STATE_INVALID;
1470fc64f94aSMatthias Ringwald             l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
1471e7ff783cSmatthias.ringwald             // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1472817374d9SMatthias Ringwald             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1473c45d6b2cSMatthias Ringwald             l2cap_free_channel_entry(channel);
147475e67d8aSMatthias Ringwald             channel = NULL;
1475e7ff783cSmatthias.ringwald             break;
1476e7ff783cSmatthias.ringwald 
1477552d92a1Smatthias.ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
1478fc64f94aSMatthias Ringwald             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1479fa8473a4Smatthias.ringwald             channel->state = L2CAP_STATE_CONFIG;
148028ca2b46S[email protected]             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1481fc64f94aSMatthias Ringwald             l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
1482552d92a1Smatthias.ringwald             break;
1483552d92a1Smatthias.ringwald 
14846fdcc387Smatthias.ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
1485fc64f94aSMatthias Ringwald             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
14866fdcc387Smatthias.ringwald             // success, start l2cap handshake
1487b1988dceSmatthias.ringwald             channel->local_sig_id = l2cap_next_sig_id();
14886fdcc387Smatthias.ringwald             channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
1489fc64f94aSMatthias Ringwald             l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
14905932bd7cS[email protected]             l2cap_start_rtx(channel);
14916fdcc387Smatthias.ringwald             break;
14926fdcc387Smatthias.ringwald 
1493fa8473a4Smatthias.ringwald         case L2CAP_STATE_CONFIG:
1494fc64f94aSMatthias Ringwald             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
149561c3f6deSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
149661c3f6deSMatthias Ringwald             // fallback to basic mode if ERTM requested but not not supported by remote
149761c3f6deSMatthias Ringwald             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
149861c3f6deSMatthias Ringwald                 if (!l2cap_ertm_mode(channel)){
149961c3f6deSMatthias Ringwald                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
150061c3f6deSMatthias Ringwald                     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
150161c3f6deSMatthias Ringwald                 }
150261c3f6deSMatthias Ringwald             }
150361c3f6deSMatthias Ringwald #endif
150473cf2b3dSmatthias.ringwald             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
150563a7246aSmatthias.ringwald                 uint16_t flags = 0;
150628ca2b46S[email protected]                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
150763a7246aSmatthias.ringwald                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
150863a7246aSmatthias.ringwald                     flags = 1;
150963a7246aSmatthias.ringwald                 } else {
151028ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
151163a7246aSmatthias.ringwald                 }
151263a7246aSmatthias.ringwald                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
1513ac8f1300SMatthias Ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1514fc64f94aSMatthias 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);
1515ac8f1300SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1516ac8f1300SMatthias Ringwald                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
1517ac8f1300SMatthias Ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1518ac8f1300SMatthias Ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1519b8134563SMatthias Ringwald                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1520ac8f1300SMatthias 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);
1521b8134563SMatthias Ringwald                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM){
1522b8134563SMatthias Ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
1523b8134563SMatthias Ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1524b8134563SMatthias Ringwald                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1525b8134563SMatthias 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);
1526ac8f1300SMatthias Ringwald #endif
1527ac8f1300SMatthias Ringwald                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
152863a7246aSmatthias.ringwald                     channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1529b8134563SMatthias Ringwald                     uint16_t options_size = l2cap_setup_options_mtu_response(channel, config_options);
1530ac8f1300SMatthias 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);
153163a7246aSmatthias.ringwald                 } else {
1532ac8f1300SMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
153363a7246aSmatthias.ringwald                 }
153463a7246aSmatthias.ringwald                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1535fa8473a4Smatthias.ringwald             }
153673cf2b3dSmatthias.ringwald             else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
153728ca2b46S[email protected]                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
153828ca2b46S[email protected]                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
1539b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
15406b99230fSMatthias Ringwald                 uint16_t options_size = l2cap_setup_options_request(channel, config_options);
15416dca2a0cSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options);
15425932bd7cS[email protected]                 l2cap_start_rtx(channel);
1543fa8473a4Smatthias.ringwald             }
1544fa8473a4Smatthias.ringwald             if (l2cap_channel_ready_for_open(channel)){
1545552d92a1Smatthias.ringwald                 channel->state = L2CAP_STATE_OPEN;
1546552d92a1Smatthias.ringwald                 l2cap_emit_channel_opened(channel, 0);  // success
1547fa8473a4Smatthias.ringwald             }
1548552d92a1Smatthias.ringwald             break;
1549552d92a1Smatthias.ringwald 
1550e7ff783cSmatthias.ringwald         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1551fc64f94aSMatthias Ringwald             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
155222c29ab4SMatthias Ringwald             channel->state = L2CAP_STATE_INVALID;
1553fc64f94aSMatthias Ringwald             l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
15545932bd7cS[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 :)
1555756102d3Smatthias.ringwald             l2cap_finialize_channel_close(channel);  // -- remove from list
155664cb054cSMatthias Ringwald             channel = NULL;
1557e7ff783cSmatthias.ringwald             break;
1558e7ff783cSmatthias.ringwald 
1559e7ff783cSmatthias.ringwald         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1560fc64f94aSMatthias Ringwald             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1561b1988dceSmatthias.ringwald             channel->local_sig_id = l2cap_next_sig_id();
15622cd0be45Smatthias.ringwald             channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1563fc64f94aSMatthias Ringwald             l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
15642cd0be45Smatthias.ringwald             break;
15652cd0be45Smatthias.ringwald         default:
15662cd0be45Smatthias.ringwald             break;
15672cd0be45Smatthias.ringwald     }
156838f62777SMatthias Ringwald 
156938f62777SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
157064cb054cSMatthias Ringwald 
157175e67d8aSMatthias Ringwald     // handle channel finalize on L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE and L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE
15723a600bd4SMatthias Ringwald     if (!channel) return;
15739700d53bSMilanka Ringwald 
15749700d53bSMilanka Ringwald     // ERTM mode
15753a600bd4SMatthias Ringwald     if (channel->mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) return;
15769700d53bSMilanka Ringwald 
15779700d53bSMilanka Ringwald     // check if we can still send
15783a600bd4SMatthias Ringwald     if (channel->con_handle == HCI_CON_HANDLE_INVALID) return;
15793a600bd4SMatthias Ringwald     if (!hci_can_send_acl_packet_now(channel->con_handle)) return;
1580675e6881SMatthias Ringwald 
1581d84e866fSMatthias Ringwald     if (channel->send_supervisor_frame_receiver_ready){
158278cd8a22SMatthias Ringwald         channel->send_supervisor_frame_receiver_ready = 0;
1583d2afdd38SMatthias Ringwald         log_info("Send S-Frame: RR %u, final %u", channel->req_seq, channel->set_final_bit_after_packet_with_poll_bit_set);
1584d2afdd38SMatthias 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);
1585d2afdd38SMatthias Ringwald         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
158638f62777SMatthias Ringwald         l2cap_ertm_send_supervisor_frame(channel, control);
15873a600bd4SMatthias Ringwald         return;
158838f62777SMatthias Ringwald     }
158962041d70SMatthias Ringwald     if (channel->send_supervisor_frame_receiver_ready_poll){
159078cd8a22SMatthias Ringwald         channel->send_supervisor_frame_receiver_ready_poll = 0;
159162041d70SMatthias Ringwald         log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
159262041d70SMatthias Ringwald         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
159362041d70SMatthias Ringwald         l2cap_ertm_send_supervisor_frame(channel, control);
15943a600bd4SMatthias Ringwald         return;
159562041d70SMatthias Ringwald     }
15968f1c9639SMatthias Ringwald     if (channel->send_supervisor_frame_receiver_not_ready){
159778cd8a22SMatthias Ringwald         channel->send_supervisor_frame_receiver_not_ready = 0;
15988f1c9639SMatthias Ringwald         log_info("Send S-Frame: RNR %u", channel->req_seq);
15998f1c9639SMatthias Ringwald         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
16008f1c9639SMatthias Ringwald         l2cap_ertm_send_supervisor_frame(channel, control);
16013a600bd4SMatthias Ringwald         return;
16028f1c9639SMatthias Ringwald     }
1603c7309e8dSMatthias Ringwald     if (channel->send_supervisor_frame_reject){
1604c7309e8dSMatthias Ringwald         channel->send_supervisor_frame_reject = 0;
1605c7309e8dSMatthias Ringwald         log_info("Send S-Frame: REJ %u", channel->req_seq);
1606c7309e8dSMatthias Ringwald         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 0, 0, channel->req_seq);
1607c7309e8dSMatthias Ringwald         l2cap_ertm_send_supervisor_frame(channel, control);
16083a600bd4SMatthias Ringwald         return;
1609c7309e8dSMatthias Ringwald     }
1610df2191a7SMatthias Ringwald     if (channel->send_supervisor_frame_selective_reject){
1611df2191a7SMatthias Ringwald         channel->send_supervisor_frame_selective_reject = 0;
1612df2191a7SMatthias Ringwald         log_info("Send S-Frame: SREJ %u", channel->expected_tx_seq);
1613f85ade6bSMatthias 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);
1614f85ade6bSMatthias Ringwald         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1615df2191a7SMatthias Ringwald         l2cap_ertm_send_supervisor_frame(channel, control);
16163a600bd4SMatthias Ringwald         return;
1617df2191a7SMatthias Ringwald     }
16187b7901d8SMatthias Ringwald 
16197b7901d8SMatthias Ringwald     if (channel->srej_active){
16207b7901d8SMatthias Ringwald         int i;
16217b7901d8SMatthias Ringwald         for (i=0;i<channel->num_tx_buffers;i++){
16227b7901d8SMatthias Ringwald             l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
16237b7901d8SMatthias Ringwald             if (tx_state->retransmission_requested) {
16247b7901d8SMatthias Ringwald                 tx_state->retransmission_requested = 0;
1625d2afdd38SMatthias Ringwald                 uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set;
1626d2afdd38SMatthias Ringwald                 channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1627d2afdd38SMatthias Ringwald                 l2cap_ertm_send_information_frame(channel, i, final);
16287b7901d8SMatthias Ringwald                 break;
16297b7901d8SMatthias Ringwald             }
16307b7901d8SMatthias Ringwald         }
16317b7901d8SMatthias Ringwald         if (i == channel->num_tx_buffers){
16327b7901d8SMatthias Ringwald             // no retransmission request found
16337b7901d8SMatthias Ringwald             channel->srej_active = 0;
16347b7901d8SMatthias Ringwald         } else {
16357b7901d8SMatthias Ringwald             // packet was sent
16363a600bd4SMatthias Ringwald             return;
16373a600bd4SMatthias Ringwald         }
16383a600bd4SMatthias Ringwald     }
16393a600bd4SMatthias Ringwald #endif
16403a600bd4SMatthias Ringwald }
16413a600bd4SMatthias Ringwald #endif
16423a600bd4SMatthias Ringwald 
16433a600bd4SMatthias Ringwald // MARK: L2CAP_RUN
16443a600bd4SMatthias Ringwald // process outstanding signaling tasks
16453a600bd4SMatthias Ringwald static void l2cap_run(void){
16463a600bd4SMatthias Ringwald 
16473a600bd4SMatthias Ringwald     // log_info("l2cap_run: entered");
16483a600bd4SMatthias Ringwald 
16493a600bd4SMatthias Ringwald     // check pending signaling responses
16503a600bd4SMatthias Ringwald     while (signaling_responses_pending){
16513a600bd4SMatthias Ringwald 
16523a600bd4SMatthias Ringwald         hci_con_handle_t handle = signaling_responses[0].handle;
16533a600bd4SMatthias Ringwald 
16543a600bd4SMatthias Ringwald         if (!hci_can_send_acl_packet_now(handle)) break;
16553a600bd4SMatthias Ringwald 
16563a600bd4SMatthias Ringwald         uint8_t  sig_id        = signaling_responses[0].sig_id;
16573a600bd4SMatthias Ringwald         uint8_t  response_code = signaling_responses[0].code;
16583a600bd4SMatthias Ringwald         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
16593a600bd4SMatthias Ringwald #ifdef ENABLE_CLASSIC
16603a600bd4SMatthias Ringwald         uint16_t info_type     = signaling_responses[0].data;  // INFORMATION_REQUEST
16613a600bd4SMatthias Ringwald         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
16623a600bd4SMatthias Ringwald #endif
16633a600bd4SMatthias Ringwald 
16643a600bd4SMatthias Ringwald         // remove first item before sending (to avoid sending response mutliple times)
16653a600bd4SMatthias Ringwald         signaling_responses_pending--;
16663a600bd4SMatthias Ringwald         int i;
16673a600bd4SMatthias Ringwald         for (i=0; i < signaling_responses_pending; i++){
16683a600bd4SMatthias Ringwald             (void)memcpy(&signaling_responses[i],
16693a600bd4SMatthias Ringwald                          &signaling_responses[i + 1],
16703a600bd4SMatthias Ringwald                          sizeof(l2cap_signaling_response_t));
16713a600bd4SMatthias Ringwald         }
16723a600bd4SMatthias Ringwald 
16733a600bd4SMatthias Ringwald         switch (response_code){
16743a600bd4SMatthias Ringwald #ifdef ENABLE_CLASSIC
16753a600bd4SMatthias Ringwald             case CONNECTION_REQUEST:
16763a600bd4SMatthias Ringwald                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
16773a600bd4SMatthias Ringwald                 // also disconnect if result is 0x0003 - security blocked
16783a600bd4SMatthias Ringwald                 if (result == 0x0003){
16793a600bd4SMatthias Ringwald                     hci_disconnect_security_block(handle);
16803a600bd4SMatthias Ringwald                 }
16813a600bd4SMatthias Ringwald                 break;
16823a600bd4SMatthias Ringwald             case ECHO_REQUEST:
16833a600bd4SMatthias Ringwald                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
16843a600bd4SMatthias Ringwald                 break;
16853a600bd4SMatthias Ringwald             case INFORMATION_REQUEST:
16863a600bd4SMatthias Ringwald                 switch (info_type){
16873a600bd4SMatthias Ringwald                     case L2CAP_INFO_TYPE_CONNECTIONLESS_MTU: {
16883a600bd4SMatthias Ringwald                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
16893a600bd4SMatthias Ringwald                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(connectionless_mtu), &connectionless_mtu);
16903a600bd4SMatthias Ringwald                         }
16913a600bd4SMatthias Ringwald                         break;
16923a600bd4SMatthias Ringwald                     case L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED: {
16933a600bd4SMatthias Ringwald                             uint32_t features = l2cap_extended_features_mask();
16943a600bd4SMatthias Ringwald                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(features), &features);
16953a600bd4SMatthias Ringwald                         }
16963a600bd4SMatthias Ringwald                         break;
16973a600bd4SMatthias Ringwald                     case L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED: {
16983a600bd4SMatthias Ringwald                             uint8_t map[8];
16993a600bd4SMatthias Ringwald                             memset(map, 0, 8);
17003a600bd4SMatthias Ringwald                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
17013a600bd4SMatthias Ringwald                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(map), &map);
17023a600bd4SMatthias Ringwald                         }
17033a600bd4SMatthias Ringwald                         break;
17043a600bd4SMatthias Ringwald                     default:
17053a600bd4SMatthias Ringwald                         // all other types are not supported
17063a600bd4SMatthias Ringwald                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 1, 0, NULL);
17073a600bd4SMatthias Ringwald                         break;
17083a600bd4SMatthias Ringwald                 }
17093a600bd4SMatthias Ringwald                 break;
17103a600bd4SMatthias Ringwald             case COMMAND_REJECT:
17113a600bd4SMatthias Ringwald                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
17123a600bd4SMatthias Ringwald                 break;
17133a600bd4SMatthias Ringwald #endif
17143a600bd4SMatthias Ringwald #ifdef ENABLE_BLE
17153a600bd4SMatthias Ringwald             case LE_CREDIT_BASED_CONNECTION_REQUEST:
17163a600bd4SMatthias Ringwald                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
17173a600bd4SMatthias Ringwald                 break;
17183a600bd4SMatthias Ringwald             case COMMAND_REJECT_LE:
17193a600bd4SMatthias Ringwald                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
17203a600bd4SMatthias Ringwald                 break;
17213a600bd4SMatthias Ringwald #endif
17223a600bd4SMatthias Ringwald             default:
17233a600bd4SMatthias Ringwald                 // should not happen
17243a600bd4SMatthias Ringwald                 break;
17253a600bd4SMatthias Ringwald         }
17263a600bd4SMatthias Ringwald     }
17273a600bd4SMatthias Ringwald 
17283a600bd4SMatthias Ringwald #if defined(ENABLE_CLASSIC) || defined(ENABLE_BLE)
17293a600bd4SMatthias Ringwald     btstack_linked_list_iterator_t it;
17303a600bd4SMatthias Ringwald #endif
17313a600bd4SMatthias Ringwald 
17323a600bd4SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
17333a600bd4SMatthias Ringwald     // send l2cap information request if neccessary
17343a600bd4SMatthias Ringwald     hci_connections_get_iterator(&it);
17353a600bd4SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
17363a600bd4SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
17373a600bd4SMatthias Ringwald         if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST){
17383a600bd4SMatthias Ringwald             if (!hci_can_send_acl_packet_now(connection->con_handle)) break;
17393a600bd4SMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
17403a600bd4SMatthias Ringwald             uint8_t sig_id = l2cap_next_sig_id();
17413a600bd4SMatthias Ringwald             uint8_t info_type = L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED;
17423a600bd4SMatthias Ringwald             l2cap_send_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
17433a600bd4SMatthias Ringwald             return;
17447b7901d8SMatthias Ringwald         }
17457b7901d8SMatthias Ringwald     }
174638f62777SMatthias Ringwald #endif
174738f62777SMatthias Ringwald 
17483a600bd4SMatthias Ringwald #ifdef ENABLE_CLASSIC
17493a600bd4SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
17503a600bd4SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
17513a600bd4SMatthias Ringwald 
17523a600bd4SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
17533a600bd4SMatthias Ringwald 
17543a600bd4SMatthias Ringwald         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CLASSIC) continue;
17553a600bd4SMatthias Ringwald 
17563a600bd4SMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
17573a600bd4SMatthias Ringwald         l2cap_run_for_classic_channel(channel);
17582cd0be45Smatthias.ringwald     }
175909e9d05bSMatthias Ringwald #endif
1760da886c03S[email protected] 
1761cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1762421cb104SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1763efedfb4cSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1764b5803aafSMatthias Ringwald         uint16_t mps;
1765efedfb4cSMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1766421cb104SMatthias Ringwald 
1767421cb104SMatthias Ringwald         if (channel->channel_type != L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL) continue;
1768421cb104SMatthias Ringwald 
1769efedfb4cSMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1770efedfb4cSMatthias Ringwald         switch (channel->state){
17715cb87675SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
17725cb87675SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
17735cb87675SMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
17745cb87675SMatthias Ringwald                 // le psm, source cid, mtu, mps, initial credits
17751b8b8d05SMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
177663f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
177763f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
1778b5803aafSMatthias Ringwald                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
1779b5803aafSMatthias 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);
17805cb87675SMatthias Ringwald                 break;
178123017473SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
178223017473SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
178323017473SMatthias Ringwald                 // TODO: support larger MPS
178423017473SMatthias Ringwald                 channel->state = L2CAP_STATE_OPEN;
178563f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
178663f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
1787b5803aafSMatthias Ringwald                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
1788b5803aafSMatthias 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);
178964e11ca9SMatthias Ringwald                 // notify client
179044276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0);
179123017473SMatthias Ringwald                 break;
1792e7d0c9aaSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
1793e7d0c9aaSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1794e7d0c9aaSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
179563f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
1796e7d0c9aaSMatthias Ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1797e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1798c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
1799e7d0c9aaSMatthias Ringwald                 break;
18007f107edaSMatthias Ringwald             case L2CAP_STATE_OPEN:
180185aeef60SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
180285aeef60SMatthias Ringwald 
180385aeef60SMatthias Ringwald                 // send credits
180485aeef60SMatthias Ringwald                 if (channel->new_credits_incoming){
180585aeef60SMatthias Ringwald                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
180685aeef60SMatthias Ringwald                     channel->local_sig_id = l2cap_next_sig_id();
180785aeef60SMatthias Ringwald                     uint16_t new_credits = channel->new_credits_incoming;
180885aeef60SMatthias Ringwald                     channel->new_credits_incoming = 0;
180985aeef60SMatthias Ringwald                     channel->credits_incoming += new_credits;
181085aeef60SMatthias Ringwald                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
18116774d5c9SMatthias Ringwald                 }
181285aeef60SMatthias Ringwald                 break;
181385aeef60SMatthias Ringwald 
1814828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1815828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1816828a7f7aSMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
1817828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1818828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1819828a7f7aSMatthias Ringwald                 break;
1820828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1821828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1822828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1823828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1824828a7f7aSMatthias Ringwald                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
1825828a7f7aSMatthias Ringwald                 break;
1826efedfb4cSMatthias Ringwald             default:
1827efedfb4cSMatthias Ringwald                 break;
1828efedfb4cSMatthias Ringwald         }
1829efedfb4cSMatthias Ringwald     }
183009e9d05bSMatthias Ringwald #endif
1831efedfb4cSMatthias Ringwald 
183209e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
1833da886c03S[email protected]     // send l2cap con paramter update if necessary
1834da886c03S[email protected]     hci_connections_get_iterator(&it);
1835665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
1836665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1837c1ab6cc1SMatthias Ringwald         if ((connection->address_type != BD_ADDR_TYPE_LE_PUBLIC) && (connection->address_type != BD_ADDR_TYPE_LE_RANDOM)) continue;
1838b68d7bc3SMatthias Ringwald         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
1839da886c03S[email protected]         switch (connection->le_con_parameter_update_state){
1840b68d7bc3SMatthias Ringwald             case CON_PARAMETER_UPDATE_SEND_REQUEST:
1841b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1842fe8aebe6SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, l2cap_next_sig_id(),
1843b68d7bc3SMatthias Ringwald                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
1844b68d7bc3SMatthias Ringwald                 break;
1845da886c03S[email protected]             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
1846b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
1847b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
1848da886c03S[email protected]                 break;
1849da886c03S[email protected]             case CON_PARAMETER_UPDATE_DENY:
1850b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1851b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
1852da886c03S[email protected]                 break;
1853da886c03S[email protected]             default:
1854da886c03S[email protected]                 break;
1855da886c03S[email protected]         }
1856da886c03S[email protected]     }
18574d7157c3S[email protected] #endif
1858da886c03S[email protected] 
185922c29ab4SMatthias Ringwald     // log_info("l2cap_run: exit");
18602cd0be45Smatthias.ringwald }
18612cd0be45Smatthias.ringwald 
186209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1863fc64f94aSMatthias Ringwald static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
1864505f1c30SMatthias Ringwald     if ((channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE) || (channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION)) {
1865e5ac0afcSMatthias Ringwald         log_info("connection complete con_handle %04x - for channel %p cid 0x%04x", (int) con_handle, channel, channel->local_cid);
18662df5dadcS[email protected]         // success, start l2cap handshake
1867fc64f94aSMatthias Ringwald         channel->con_handle = con_handle;
18682df5dadcS[email protected]         // check remote SSP feature first
18692df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
18702df5dadcS[email protected]     }
18712df5dadcS[email protected] }
18722df5dadcS[email protected] 
18731b9cb13dSMatthias Ringwald static void l2cap_ready_to_connect(l2cap_channel_t * channel){
18741b9cb13dSMatthias Ringwald 
18751b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
187627e0774aSMatthias Ringwald     // assumption: outgoing connection
18771b9cb13dSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
18781b9cb13dSMatthias Ringwald     if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
18791b9cb13dSMatthias Ringwald         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
18801b9cb13dSMatthias Ringwald         channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
18811b9cb13dSMatthias Ringwald         return;
18821b9cb13dSMatthias Ringwald     }
18831b9cb13dSMatthias Ringwald #endif
18841b9cb13dSMatthias Ringwald 
18851b9cb13dSMatthias Ringwald     // fine, go ahead
18861b9cb13dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
18871b9cb13dSMatthias Ringwald }
18881b9cb13dSMatthias Ringwald 
18892df5dadcS[email protected] static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
18902df5dadcS[email protected]     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
18912df5dadcS[email protected] 
18922df5dadcS[email protected]     // we have been waiting for remote supported features, if both support SSP,
1893ac301f95S[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));
1894fc64f94aSMatthias Ringwald     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
18952df5dadcS[email protected]         // request security level 2
18962df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
1897dfce2622SMilanka Ringwald         channel->required_security_level = LEVEL_2;
1898fc64f94aSMatthias Ringwald         gap_request_security_level(channel->con_handle, LEVEL_2);
18992df5dadcS[email protected]         return;
19002df5dadcS[email protected]     }
19011b9cb13dSMatthias Ringwald 
19021b9cb13dSMatthias Ringwald     l2cap_ready_to_connect(channel);
19032df5dadcS[email protected] }
190409e9d05bSMatthias Ringwald #endif
19052df5dadcS[email protected] 
190609e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
19075d18f623SMatthias 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,
1908da144af5SMatthias Ringwald     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
1909da144af5SMatthias Ringwald 
1910da144af5SMatthias Ringwald     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1911da144af5SMatthias Ringwald     if (!channel) {
1912da144af5SMatthias Ringwald         return NULL;
1913da144af5SMatthias Ringwald     }
1914da144af5SMatthias Ringwald 
1915da144af5SMatthias Ringwald     // fill in
1916da144af5SMatthias Ringwald     channel->packet_handler = packet_handler;
19175d18f623SMatthias Ringwald     channel->channel_type   = channel_type;
1918da144af5SMatthias Ringwald     bd_addr_copy(channel->address, address);
1919da144af5SMatthias Ringwald     channel->address_type = address_type;
1920da144af5SMatthias Ringwald     channel->psm = psm;
1921da144af5SMatthias Ringwald     channel->local_mtu  = local_mtu;
1922b37a9357SMatthias Ringwald     channel->remote_mtu = L2CAP_DEFAULT_MTU;
1923da144af5SMatthias Ringwald     channel->required_security_level = security_level;
1924da144af5SMatthias Ringwald 
1925da144af5SMatthias Ringwald     //
1926da144af5SMatthias Ringwald     channel->local_cid = l2cap_next_local_cid();
1927e0780573SMatthias Ringwald     channel->con_handle = HCI_CON_HANDLE_INVALID;
1928da144af5SMatthias Ringwald 
1929da144af5SMatthias Ringwald     // set initial state
1930da144af5SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
1931da144af5SMatthias Ringwald     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
1932da144af5SMatthias Ringwald     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
1933da144af5SMatthias Ringwald     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
193438f62777SMatthias Ringwald 
1935c45d6b2cSMatthias Ringwald     log_info("create channel %p, local_cid 0x%04x", channel, channel->local_cid);
1936e5ac0afcSMatthias Ringwald 
1937da144af5SMatthias Ringwald     return channel;
1938da144af5SMatthias Ringwald }
1939c45d6b2cSMatthias Ringwald 
1940c45d6b2cSMatthias Ringwald static void l2cap_free_channel_entry(l2cap_channel_t * channel){
1941c45d6b2cSMatthias Ringwald     log_info("free channel %p, local_cid 0x%04x", channel, channel->local_cid);
19428f4dd6c1SMatthias Ringwald     // assert all timers are stopped
1943b5bab9c8SMatthias Ringwald     l2cap_stop_rtx(channel);
19448f4dd6c1SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
19458f4dd6c1SMatthias Ringwald     l2cap_ertm_stop_retransmission_timer(channel);
19468f4dd6c1SMatthias Ringwald     l2cap_ertm_stop_monitor_timer(channel);
19478f4dd6c1SMatthias Ringwald #endif
1948b5bab9c8SMatthias Ringwald     // free  memory
1949c45d6b2cSMatthias Ringwald     btstack_memory_l2cap_channel_free(channel);
1950c45d6b2cSMatthias Ringwald }
195109e9d05bSMatthias Ringwald #endif
195209e9d05bSMatthias Ringwald 
195309e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1954da144af5SMatthias Ringwald 
19559077cb15SMatthias Ringwald /**
19569077cb15SMatthias Ringwald  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
19579077cb15SMatthias Ringwald  * @param packet_handler
19589077cb15SMatthias Ringwald  * @param address
19599077cb15SMatthias Ringwald  * @param psm
19609077cb15SMatthias Ringwald  * @param mtu
19619077cb15SMatthias Ringwald  * @param local_cid
19629077cb15SMatthias Ringwald  */
19639077cb15SMatthias Ringwald 
19649d139fbaSMatthias 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){
19659d139fbaSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
19669d139fbaSMatthias Ringwald     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1967da144af5SMatthias Ringwald 
19689d139fbaSMatthias 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);
1969da144af5SMatthias Ringwald 
1970f16129ceSMatthias 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);
1971fc64f94aSMatthias Ringwald     if (!channel) {
19729077cb15SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
19739077cb15SMatthias Ringwald     }
19749077cb15SMatthias Ringwald 
19751b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
19761b9cb13dSMatthias Ringwald     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
19771b9cb13dSMatthias Ringwald #endif
19781b9cb13dSMatthias Ringwald 
19799077cb15SMatthias Ringwald     // add to connections list
1980fc64f94aSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
19819077cb15SMatthias Ringwald 
19829077cb15SMatthias Ringwald     // store local_cid
19839077cb15SMatthias Ringwald     if (out_local_cid){
1984fc64f94aSMatthias Ringwald        *out_local_cid = channel->local_cid;
19859077cb15SMatthias Ringwald     }
19869077cb15SMatthias Ringwald 
19879077cb15SMatthias Ringwald     // check if hci connection is already usable
1988f16129ceSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
198957a9eeaeSMatthias Ringwald     if (conn && conn->con_handle != HCI_CON_HANDLE_INVALID){
1990e5ac0afcSMatthias Ringwald         log_info("l2cap_create_channel, hci connection 0x%04x already exists", conn->con_handle);
1991fc64f94aSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
19929077cb15SMatthias Ringwald         // check if remote supported fearures are already received
19939077cb15SMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
1994fc64f94aSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
19959077cb15SMatthias Ringwald         }
19969077cb15SMatthias Ringwald     }
19979077cb15SMatthias Ringwald 
19989077cb15SMatthias Ringwald     l2cap_run();
19999077cb15SMatthias Ringwald 
2000c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
20019077cb15SMatthias Ringwald }
20029077cb15SMatthias Ringwald 
20031ea99aafSMilanka Ringwald void l2cap_disconnect(uint16_t local_cid, uint8_t reason){
2004e0abb8e7S[email protected]     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
2005b35f641cSmatthias.ringwald     // find channel for local_cid
2006b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2007f62db1e3Smatthias.ringwald     if (channel) {
2008e7ff783cSmatthias.ringwald         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2009f62db1e3Smatthias.ringwald     }
20102cd0be45Smatthias.ringwald     // process
20112cd0be45Smatthias.ringwald     l2cap_run();
201243625864Smatthias.ringwald }
20131e6aba47Smatthias.ringwald 
2014afde0c52Smatthias.ringwald static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
2015ceec418aSMatthias Ringwald     // mark all channels before emitting open events as these could trigger new connetion requests to the same device
2016665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
2017665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2018665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2019665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2020fad84cafSMatthias Ringwald         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2021058e3d6bSMatthias Ringwald         if (bd_addr_cmp( channel->address, address) != 0) continue;
2022c22aecc9S[email protected]         // channel for this address found
2023c22aecc9S[email protected]         switch (channel->state){
2024c22aecc9S[email protected]             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2025c22aecc9S[email protected]             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2026ceec418aSMatthias Ringwald                 channel->state = L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD;
2027c22aecc9S[email protected]                 break;
2028c22aecc9S[email protected]             default:
2029c22aecc9S[email protected]                 break;
2030afde0c52Smatthias.ringwald         }
2031afde0c52Smatthias.ringwald     }
2032ceec418aSMatthias Ringwald     // emit and free marked entries. restart loop to deal with list changes
2033ceec418aSMatthias Ringwald     int done = 0;
2034ceec418aSMatthias Ringwald     while (!done) {
2035ceec418aSMatthias Ringwald         done = 1;
2036ceec418aSMatthias Ringwald         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2037ceec418aSMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
2038ceec418aSMatthias Ringwald             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2039fad84cafSMatthias Ringwald             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2040ceec418aSMatthias Ringwald             if (channel->state == L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD){
2041ceec418aSMatthias Ringwald                 done = 0;
2042ceec418aSMatthias Ringwald                 // failure, forward error code
204366a72640SMatthias Ringwald                 l2cap_handle_channel_open_failed(channel, status);
2044ceec418aSMatthias Ringwald                 // discard channel
2045ceec418aSMatthias Ringwald                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2046c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
2047ceec418aSMatthias Ringwald                 break;
2048ceec418aSMatthias Ringwald             }
2049ceec418aSMatthias Ringwald         }
2050ceec418aSMatthias Ringwald     }
2051ceec418aSMatthias Ringwald 
2052afde0c52Smatthias.ringwald }
2053afde0c52Smatthias.ringwald 
2054afde0c52Smatthias.ringwald static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
2055665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
2056665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2057665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2058665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2059fad84cafSMatthias Ringwald         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2060058e3d6bSMatthias Ringwald         if ( ! bd_addr_cmp( channel->address, address) ){
20612df5dadcS[email protected]             l2cap_handle_connection_complete(handle, channel);
2062afde0c52Smatthias.ringwald         }
2063afde0c52Smatthias.ringwald     }
20646fdcc387Smatthias.ringwald     // process
20656fdcc387Smatthias.ringwald     l2cap_run();
2066afde0c52Smatthias.ringwald }
206709e9d05bSMatthias Ringwald #endif
2068b448a0e7Smatthias.ringwald 
20696774d5c9SMatthias Ringwald static bool l2cap_channel_ready_to_send(l2cap_channel_t * channel){
20706774d5c9SMatthias Ringwald     switch (channel->channel_type){
20716774d5c9SMatthias Ringwald #ifdef ENABLE_CLASSIC
20726774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CLASSIC:
20736774d5c9SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2074d89ab698SMatthias Ringwald             // send if we have more data and remote windows isn't full yet
2075d89ab698SMatthias Ringwald             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2076d89ab698SMatthias Ringwald                 if (channel->unacked_frames >= btstack_min(channel->num_stored_tx_frames, channel->remote_tx_window_size)) return false;
20776774d5c9SMatthias Ringwald                 return hci_can_send_acl_classic_packet_now() != 0;
2078d89ab698SMatthias Ringwald             }
2079d89ab698SMatthias Ringwald #endif
2080d89ab698SMatthias Ringwald             if (!channel->waiting_for_can_send_now) return false;
2081d89ab698SMatthias Ringwald             return (hci_can_send_acl_classic_packet_now() != 0);
20826774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
20836774d5c9SMatthias Ringwald             if (!channel->waiting_for_can_send_now) return false;
20846774d5c9SMatthias Ringwald             return hci_can_send_acl_classic_packet_now() != 0;
20856774d5c9SMatthias Ringwald #endif
20866774d5c9SMatthias Ringwald #ifdef ENABLE_BLE
20876774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_FIXED:
20886774d5c9SMatthias Ringwald             if (!channel->waiting_for_can_send_now) return false;
20896774d5c9SMatthias Ringwald             return hci_can_send_acl_le_packet_now() != 0;
20906774d5c9SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
20916774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
20926774d5c9SMatthias Ringwald             if (channel->send_sdu_buffer == NULL) return false;
20936774d5c9SMatthias Ringwald             if (channel->credits_outgoing == 0) return false;
20946774d5c9SMatthias Ringwald             return hci_can_send_acl_le_packet_now() != 0;
20956774d5c9SMatthias Ringwald #endif
20966774d5c9SMatthias Ringwald #endif
20976774d5c9SMatthias Ringwald         default:
20986774d5c9SMatthias Ringwald             return false;
20996774d5c9SMatthias Ringwald     }
21006774d5c9SMatthias Ringwald }
21016774d5c9SMatthias Ringwald 
21026774d5c9SMatthias Ringwald static void l2cap_channel_trigger_send(l2cap_channel_t * channel){
21036774d5c9SMatthias Ringwald     switch (channel->channel_type){
2104d89ab698SMatthias Ringwald #ifdef ENABLE_CLASSIC
2105d89ab698SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CLASSIC:
2106d89ab698SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2107d89ab698SMatthias Ringwald             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2108d89ab698SMatthias Ringwald                 l2cap_ertm_channel_send_information_frame(channel);
2109d89ab698SMatthias Ringwald                 return;
2110d89ab698SMatthias Ringwald             }
2111d89ab698SMatthias Ringwald #endif
2112d89ab698SMatthias Ringwald             channel->waiting_for_can_send_now = 0;
2113d89ab698SMatthias Ringwald             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2114d89ab698SMatthias Ringwald             break;
2115d89ab698SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2116d89ab698SMatthias Ringwald             channel->waiting_for_can_send_now = 0;
2117d89ab698SMatthias Ringwald             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2118d89ab698SMatthias Ringwald             break;
2119d89ab698SMatthias Ringwald #endif
21206774d5c9SMatthias Ringwald #ifdef ENABLE_BLE
2121d89ab698SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_FIXED:
2122d89ab698SMatthias Ringwald             channel->waiting_for_can_send_now = 0;
2123d89ab698SMatthias Ringwald             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2124d89ab698SMatthias Ringwald             break;
21256774d5c9SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
21266774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
21276774d5c9SMatthias Ringwald             l2cap_le_send_pdu(channel);
21286774d5c9SMatthias Ringwald             break;
21296774d5c9SMatthias Ringwald #endif
21306774d5c9SMatthias Ringwald #endif
21316774d5c9SMatthias Ringwald         default:
21326774d5c9SMatthias Ringwald             break;
21336774d5c9SMatthias Ringwald     }
21346774d5c9SMatthias Ringwald }
21356774d5c9SMatthias Ringwald 
213633c40538SMatthias Ringwald static void l2cap_notify_channel_can_send(void){
21376774d5c9SMatthias Ringwald     bool done = false;
21387740e150SMatthias Ringwald     while (!done){
21396774d5c9SMatthias Ringwald         done = true;
214033c40538SMatthias Ringwald         btstack_linked_list_iterator_t it;
214133c40538SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &l2cap_channels);
214233c40538SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
214333c40538SMatthias Ringwald             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
21446774d5c9SMatthias Ringwald             bool ready = l2cap_channel_ready_to_send(channel);
21456774d5c9SMatthias Ringwald             if (!ready) continue;
21466774d5c9SMatthias Ringwald 
21476774d5c9SMatthias Ringwald             // requeue channel for fairness
21487740e150SMatthias Ringwald             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
21497740e150SMatthias Ringwald             btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
21506774d5c9SMatthias Ringwald 
21516774d5c9SMatthias Ringwald             // trigger sending
21526774d5c9SMatthias Ringwald             l2cap_channel_trigger_send(channel);
21536774d5c9SMatthias Ringwald 
21547740e150SMatthias Ringwald             // exit inner loop as we just broke the iterator, but try again
21556774d5c9SMatthias Ringwald             done = false;
21567740e150SMatthias Ringwald             break;
21577740e150SMatthias Ringwald         }
215833c40538SMatthias Ringwald     }
215933c40538SMatthias Ringwald }
216033c40538SMatthias Ringwald 
21612053036dSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
21622053036dSMatthias Ringwald 
21632053036dSMatthias Ringwald static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){
21642053036dSMatthias Ringwald     // open cannot fail for for incoming connections
21652053036dSMatthias Ringwald     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0;
21662053036dSMatthias Ringwald 
21672053036dSMatthias Ringwald     // check state
21682053036dSMatthias Ringwald     switch (channel->state){
21692053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
21702053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
21712053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES:
21722053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
21732053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
21742053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES:
21752053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
21762053036dSMatthias Ringwald         case L2CAP_STATE_CONFIG:
21772053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
21782053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
21792053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE:
2180ceec418aSMatthias Ringwald         case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD:
21812053036dSMatthias Ringwald             return 1;
21822053036dSMatthias Ringwald 
21832053036dSMatthias Ringwald         case L2CAP_STATE_OPEN:
21842053036dSMatthias Ringwald         case L2CAP_STATE_CLOSED:
21852053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES:
21862053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
21872053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY:
21882053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
21892053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
21902053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
21912053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
21922053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
21932053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
21942053036dSMatthias Ringwald         case L2CAP_STATE_INVALID:
21952053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
21962053036dSMatthias Ringwald             return 0;
21976aa7d794SMatthias Ringwald         // no default here, to get a warning about new states
21982053036dSMatthias Ringwald     }
21996aa7d794SMatthias Ringwald     // still, the compiler insists on a return value
22006aa7d794SMatthias Ringwald     return 0;
22012053036dSMatthias Ringwald }
220213aa3e4bSMatthias Ringwald #endif
22032053036dSMatthias Ringwald 
220413aa3e4bSMatthias Ringwald #ifdef ENABLE_CLASSIC
22052053036dSMatthias Ringwald static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){
22062053036dSMatthias Ringwald     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
220766a72640SMatthias Ringwald         l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
22082053036dSMatthias Ringwald     } else {
220966a72640SMatthias Ringwald         l2cap_handle_channel_closed(channel);
22102053036dSMatthias Ringwald     }
2211c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
22122053036dSMatthias Ringwald }
22132053036dSMatthias Ringwald #endif
22142053036dSMatthias Ringwald 
22152cf36df7SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
22162cf36df7SMatthias Ringwald static void l2cap_handle_hci_le_disconnect_event(l2cap_channel_t * channel){
22172cf36df7SMatthias Ringwald     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
22182cf36df7SMatthias Ringwald         l2cap_emit_le_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
22192cf36df7SMatthias Ringwald     } else {
22202cf36df7SMatthias Ringwald         l2cap_emit_le_channel_closed(channel);
22212cf36df7SMatthias Ringwald     }
2222c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
22232cf36df7SMatthias Ringwald }
22242cf36df7SMatthias Ringwald #endif
22252053036dSMatthias Ringwald 
2226d9a7306aSMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
2227afde0c52Smatthias.ringwald 
22285774a392SMatthias Ringwald     UNUSED(packet_type); // ok: registered with hci_event_callback_registration
22295774a392SMatthias Ringwald     UNUSED(cid);         // ok: there is no channel
22305774a392SMatthias Ringwald     UNUSED(size);        // ok: fixed format events read from HCI buffer
22319ec2630cSMatthias Ringwald 
22325774a392SMatthias Ringwald #ifdef ENABLE_CLASSIC
2233afde0c52Smatthias.ringwald     bd_addr_t address;
22342d00edd4Smatthias.ringwald     int hci_con_used;
22355774a392SMatthias Ringwald #endif
22365774a392SMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
22375774a392SMatthias Ringwald     hci_con_handle_t handle;
223809e9d05bSMatthias Ringwald     btstack_linked_list_iterator_t it;
22395774a392SMatthias Ringwald #endif
2240afde0c52Smatthias.ringwald 
22410e2df43fSMatthias Ringwald     switch(hci_event_packet_get_type(packet)){
2242afde0c52Smatthias.ringwald 
224309e9d05bSMatthias Ringwald         // Notify channel packet handler if they can send now
224409e9d05bSMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
224509e9d05bSMatthias Ringwald         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
2246eea99214SMatthias Ringwald         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
224709e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
224809e9d05bSMatthias Ringwald             l2cap_notify_channel_can_send();
224909e9d05bSMatthias Ringwald             break;
225009e9d05bSMatthias Ringwald 
225109e9d05bSMatthias Ringwald         case HCI_EVENT_COMMAND_STATUS:
2252ece97caeSMatthias Ringwald #ifdef ENABLE_CLASSIC
2253ece97caeSMatthias Ringwald             // check command status for create connection for errors
2254ece97caeSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
2255ece97caeSMatthias Ringwald                 // cache outgoing address and reset
22566535961aSMatthias Ringwald                 (void)memcpy(address, l2cap_outgoing_classic_addr, 6);
2257ece97caeSMatthias Ringwald                 memset(l2cap_outgoing_classic_addr, 0, 6);
2258ece97caeSMatthias Ringwald                 // error => outgoing connection failed
2259ece97caeSMatthias Ringwald                 uint8_t status = hci_event_command_status_get_status(packet);
2260ece97caeSMatthias Ringwald                 if (status){
2261ece97caeSMatthias Ringwald                     l2cap_handle_connection_failed_for_addr(address, status);
2262ece97caeSMatthias Ringwald                 }
2263ece97caeSMatthias Ringwald             }
2264ece97caeSMatthias Ringwald #endif
226509e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
226609e9d05bSMatthias Ringwald             break;
226709e9d05bSMatthias Ringwald 
226809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2269afde0c52Smatthias.ringwald         // handle connection complete events
2270afde0c52Smatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
2271724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], address);
2272afde0c52Smatthias.ringwald             if (packet[2] == 0){
2273f8fbdce0SMatthias Ringwald                 handle = little_endian_read_16(packet, 3);
2274afde0c52Smatthias.ringwald                 l2cap_handle_connection_success_for_addr(address, handle);
2275afde0c52Smatthias.ringwald             } else {
2276afde0c52Smatthias.ringwald                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
2277afde0c52Smatthias.ringwald             }
2278afde0c52Smatthias.ringwald             break;
2279afde0c52Smatthias.ringwald 
2280afde0c52Smatthias.ringwald         // handle successful create connection cancel command
2281afde0c52Smatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
2282073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
2283afde0c52Smatthias.ringwald                 if (packet[5] == 0){
2284724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[6], address);
2285afde0c52Smatthias.ringwald                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
2286afde0c52Smatthias.ringwald                     l2cap_handle_connection_failed_for_addr(address, 0x16);
228703cfbabcSmatthias.ringwald                 }
22881e6aba47Smatthias.ringwald             }
228939d59809Smatthias.ringwald             l2cap_run();    // try sending signaling packets first
229039d59809Smatthias.ringwald             break;
229109e9d05bSMatthias Ringwald #endif
229227a923d0Smatthias.ringwald 
22932053036dSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
22941e6aba47Smatthias.ringwald         // handle disconnection complete events
2295afde0c52Smatthias.ringwald         case HCI_EVENT_DISCONNECTION_COMPLETE:
2296d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
22972053036dSMatthias Ringwald             // send l2cap open failed or closed events for all channels on this handle and free them
2298665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2299665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2300665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2301fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2302fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
2303665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
2304421cb104SMatthias Ringwald                 switch(channel->channel_type){
2305421cb104SMatthias Ringwald #ifdef ENABLE_CLASSIC
2306421cb104SMatthias Ringwald                     case L2CAP_CHANNEL_TYPE_CLASSIC:
23072053036dSMatthias Ringwald                         l2cap_handle_hci_disconnect_event(channel);
2308421cb104SMatthias Ringwald                         break;
230909e9d05bSMatthias Ringwald #endif
2310a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2311421cb104SMatthias Ringwald                     case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
23122cf36df7SMatthias Ringwald                         l2cap_handle_hci_le_disconnect_event(channel);
2313afde0c52Smatthias.ringwald                         break;
23142053036dSMatthias Ringwald #endif
2315421cb104SMatthias Ringwald                     default:
2316421cb104SMatthias Ringwald                         break;
2317421cb104SMatthias Ringwald                 }
2318421cb104SMatthias Ringwald             }
23199909e5e4SMatthias Ringwald             break;
2320421cb104SMatthias Ringwald #endif
2321fcadd0caSmatthias.ringwald 
23229909e5e4SMatthias Ringwald 
2323ee091cf1Smatthias.ringwald         // HCI Connection Timeouts
232409e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2325afde0c52Smatthias.ringwald         case L2CAP_EVENT_TIMEOUT_CHECK:
2326f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
2327bd04d84aSMatthias Ringwald             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
232880ca58a0Smatthias.ringwald             if (hci_authentication_active_for_handle(handle)) break;
23292d00edd4Smatthias.ringwald             hci_con_used = 0;
2330665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2331665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2332665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2333fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2334fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
23352d00edd4Smatthias.ringwald                 hci_con_used = 1;
2336c22aecc9S[email protected]                 break;
2337ee091cf1Smatthias.ringwald             }
23382d00edd4Smatthias.ringwald             if (hci_con_used) break;
2339d94d3cafS[email protected]             if (!hci_can_send_command_packet_now()) break;
23409edc8742Smatthias.ringwald             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
2341afde0c52Smatthias.ringwald             break;
2342ee091cf1Smatthias.ringwald 
2343df3354fcS[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2344f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
2345665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2346665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2347665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2348fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2349fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
2350e5ac0afcSMatthias Ringwald                 log_info("remote supported features, channel %p, cid %04x - state %u", channel, channel->local_cid, channel->state);
23512df5dadcS[email protected]                 l2cap_handle_remote_supported_features_received(channel);
2352df3354fcS[email protected]             }
2353c22aecc9S[email protected]             break;
2354df3354fcS[email protected] 
23555611a760SMatthias Ringwald         case GAP_EVENT_SECURITY_LEVEL:
2356f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
2357e5ac0afcSMatthias Ringwald             log_info("l2cap - security level update for handle 0x%04x", handle);
2358665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2359665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2360665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2361fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2362fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
23635533f01eS[email protected] 
2364e569dfd9SMatthias Ringwald                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
23655533f01eS[email protected]                 gap_security_level_t required_level = channel->required_security_level;
23665533f01eS[email protected] 
2367e5ac0afcSMatthias Ringwald                 log_info("channel %p, cid %04x - state %u: actual %u >= required %u?", channel, channel->local_cid, channel->state, actual_level, required_level);
2368dfce2622SMilanka Ringwald 
2369df3354fcS[email protected]                 switch (channel->state){
2370df3354fcS[email protected]                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
23715533f01eS[email protected]                         if (actual_level >= required_level){
237252606043SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
237352606043SMatthias Ringwald                             // we need to know if ERTM is supported before sending a config response
237452606043SMatthias Ringwald                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
237552606043SMatthias Ringwald                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
237652606043SMatthias Ringwald                             channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
237752606043SMatthias Ringwald #else
2378f85a9399S[email protected]                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
237944276248SMatthias Ringwald                             l2cap_emit_incoming_connection(channel);
238052606043SMatthias Ringwald #endif
23811eb2563eS[email protected]                         } else {
2382775ecc36SMatthias Ringwald                             channel->reason = 0x0003; // security block
23831eb2563eS[email protected]                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
23841eb2563eS[email protected]                         }
2385df3354fcS[email protected]                         break;
2386df3354fcS[email protected] 
2387df3354fcS[email protected]                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
23885533f01eS[email protected]                         if (actual_level >= required_level){
23891b9cb13dSMatthias Ringwald                             l2cap_ready_to_connect(channel);
2390df3354fcS[email protected]                         } else {
2391df3354fcS[email protected]                             // disconnnect, authentication not good enough
2392df3354fcS[email protected]                             hci_disconnect_security_block(handle);
2393df3354fcS[email protected]                         }
2394df3354fcS[email protected]                         break;
2395df3354fcS[email protected] 
2396df3354fcS[email protected]                     default:
2397df3354fcS[email protected]                         break;
2398df3354fcS[email protected]                 }
2399f85a9399S[email protected]             }
2400f85a9399S[email protected]             break;
240109e9d05bSMatthias Ringwald #endif
2402f85a9399S[email protected] 
2403afde0c52Smatthias.ringwald         default:
2404afde0c52Smatthias.ringwald             break;
2405afde0c52Smatthias.ringwald     }
2406afde0c52Smatthias.ringwald 
2407bd63148eS[email protected]     l2cap_run();
24081e6aba47Smatthias.ringwald }
24091e6aba47Smatthias.ringwald 
2410e74c5f58SMatthias 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){
24114cf56b4aSmatthias.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."
24122b360848Smatthias.ringwald     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
24132b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].handle = handle;
24142b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].code = code;
24152b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].sig_id = sig_id;
2416e74c5f58SMatthias Ringwald         signaling_responses[signaling_responses_pending].cid = cid;
24172b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].data = data;
24182b360848Smatthias.ringwald         signaling_responses_pending++;
24192b360848Smatthias.ringwald         l2cap_run();
24202b360848Smatthias.ringwald     }
24212b360848Smatthias.ringwald }
24222b360848Smatthias.ringwald 
242309e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
242409e9d05bSMatthias Ringwald static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
242509e9d05bSMatthias Ringwald     channel->remote_sig_id = identifier;
242609e9d05bSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
242709e9d05bSMatthias Ringwald     l2cap_run();
242809e9d05bSMatthias Ringwald }
242909e9d05bSMatthias Ringwald 
2430b35f641cSmatthias.ringwald static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
2431645658c9Smatthias.ringwald 
24329da54300S[email protected]     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
2433645658c9Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
2434645658c9Smatthias.ringwald     if (!service) {
2435645658c9Smatthias.ringwald         // 0x0002 PSM not supported
2436e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2437645658c9Smatthias.ringwald         return;
2438645658c9Smatthias.ringwald     }
2439645658c9Smatthias.ringwald 
24405061f3afS[email protected]     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
2441645658c9Smatthias.ringwald     if (!hci_connection) {
24422b360848Smatthias.ringwald         //
24439da54300S[email protected]         log_error("no hci_connection for handle %u", handle);
2444645658c9Smatthias.ringwald         return;
2445645658c9Smatthias.ringwald     }
24462bd8b7e7S[email protected] 
2447645658c9Smatthias.ringwald     // alloc structure
24489da54300S[email protected]     // log_info("l2cap_handle_connection_request register channel");
2449f16129ceSMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, hci_connection->address, BD_ADDR_TYPE_ACL,
2450da144af5SMatthias Ringwald     psm, service->mtu, service->required_security_level);
24512b360848Smatthias.ringwald     if (!channel){
24522b360848Smatthias.ringwald         // 0x0004 No resources available
2453e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
24542b360848Smatthias.ringwald         return;
24552b360848Smatthias.ringwald     }
2456da144af5SMatthias Ringwald 
2457fc64f94aSMatthias Ringwald     channel->con_handle = handle;
2458b35f641cSmatthias.ringwald     channel->remote_cid = source_cid;
2459b1988dceSmatthias.ringwald     channel->remote_sig_id = sig_id;
2460645658c9Smatthias.ringwald 
2461f53da564S[email protected]     // limit local mtu to max acl packet length - l2cap header
24622985cb84Smatthias.ringwald     if (channel->local_mtu > l2cap_max_mtu()) {
24632985cb84Smatthias.ringwald         channel->local_mtu = l2cap_max_mtu();
24649775e25bSmatthias.ringwald     }
24659775e25bSmatthias.ringwald 
2466645658c9Smatthias.ringwald     // set initial state
2467df3354fcS[email protected]     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
2468a24785d0SMatthias Ringwald     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
2469e405ae81Smatthias.ringwald 
2470645658c9Smatthias.ringwald     // add to connections list
2471665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
2472645658c9Smatthias.ringwald 
2473f85a9399S[email protected]     // assert security requirements
24741eb2563eS[email protected]     gap_request_security_level(handle, channel->required_security_level);
2475e405ae81Smatthias.ringwald }
2476645658c9Smatthias.ringwald 
2477ce8f182eSMatthias Ringwald void l2cap_accept_connection(uint16_t local_cid){
2478e0abb8e7S[email protected]     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
2479b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2480e405ae81Smatthias.ringwald     if (!channel) {
2481ce8f182eSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
2482e405ae81Smatthias.ringwald         return;
2483e405ae81Smatthias.ringwald     }
2484e405ae81Smatthias.ringwald 
248543ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
248643ec931dSMatthias Ringwald     // configure L2CAP Basic mode
248743ec931dSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
248843ec931dSMatthias Ringwald #endif
248943ec931dSMatthias Ringwald 
2490552d92a1Smatthias.ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
2491e405ae81Smatthias.ringwald 
2492552d92a1Smatthias.ringwald     // process
2493552d92a1Smatthias.ringwald     l2cap_run();
2494e405ae81Smatthias.ringwald }
2495645658c9Smatthias.ringwald 
24967ef6a7bbSMatthias Ringwald void l2cap_decline_connection(uint16_t local_cid){
24977ef6a7bbSMatthias Ringwald     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
2498b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
2499e405ae81Smatthias.ringwald     if (!channel) {
2500ce8f182eSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
2501e405ae81Smatthias.ringwald         return;
2502e405ae81Smatthias.ringwald     }
2503e7ff783cSmatthias.ringwald     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
25047ef6a7bbSMatthias Ringwald     channel->reason = 0x04; // no resources available
2505e7ff783cSmatthias.ringwald     l2cap_run();
2506645658c9Smatthias.ringwald }
2507645658c9Smatthias.ringwald 
2508e9cfb251SMatthias Ringwald // @pre command len is valid, see check in l2cap_signaling_handler_channel
25097f02f414SMatthias Ringwald static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
2510b1988dceSmatthias.ringwald 
2511fcb125edSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2512fcb125edSMatthias Ringwald     uint8_t use_fcs = 1;
2513fcb125edSMatthias Ringwald #endif
2514fcb125edSMatthias Ringwald 
2515b1988dceSmatthias.ringwald     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2516b1988dceSmatthias.ringwald 
2517f8fbdce0SMatthias Ringwald     uint16_t flags = little_endian_read_16(command, 6);
251863a7246aSmatthias.ringwald     if (flags & 1) {
251963a7246aSmatthias.ringwald         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
252063a7246aSmatthias.ringwald     }
252163a7246aSmatthias.ringwald 
25222784b77dSmatthias.ringwald     // accept the other's configuration options
2523f8fbdce0SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
25243de7c0caSmatthias.ringwald     uint16_t pos     = 8;
25253de7c0caSmatthias.ringwald     while (pos < end_pos){
252663a7246aSmatthias.ringwald         uint8_t option_hint = command[pos] >> 7;
252763a7246aSmatthias.ringwald         uint8_t option_type = command[pos] & 0x7f;
25283844aeadSMatthias Ringwald         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
252963a7246aSmatthias.ringwald         pos++;
25301dc511deSmatthias.ringwald         uint8_t length = command[pos++];
25311dc511deSmatthias.ringwald         // MTU { type(8): 1, len(8):2, MTU(16) }
2532c1ab6cc1SMatthias Ringwald         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) && (length == 2)){
2533f8fbdce0SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, pos);
25343844aeadSMatthias Ringwald             log_info("Remote MTU %u", channel->remote_mtu);
25359d139fbaSMatthias Ringwald             if (channel->remote_mtu > l2cap_max_mtu()){
25369d139fbaSMatthias Ringwald                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
25379d139fbaSMatthias Ringwald                 channel->remote_mtu = l2cap_max_mtu();
25389d139fbaSMatthias Ringwald             }
253963a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
254063a7246aSmatthias.ringwald         }
25410fe7a9d0S[email protected]         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
2542e53a3388SMatthias Ringwald         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT) && (length == 2)){
2543f8fbdce0SMatthias Ringwald             channel->flush_timeout = little_endian_read_16(command, pos);
25443844aeadSMatthias Ringwald             log_info("Flush timeout: %u ms", channel->flush_timeout);
25450fe7a9d0S[email protected]         }
2546f2fa388dSMatthias Ringwald 
25476dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
25486dca2a0cSMatthias Ringwald         // Retransmission and Flow Control Option
2549671fb338SMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
25503232a1c6SMatthias Ringwald             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
2551ac8f1300SMatthias Ringwald             switch(channel->mode){
2552ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
255325cd60d3SMatthias Ringwald                     // Store remote config
2554bbc0a9e7SMatthias Ringwald                     channel->remote_tx_window_size = command[pos+1];
2555bbc0a9e7SMatthias Ringwald                     channel->remote_max_transmit   = command[pos+2];
2556bbc0a9e7SMatthias Ringwald                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
2557bbc0a9e7SMatthias Ringwald                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
25583844aeadSMatthias Ringwald                     channel->remote_mps = little_endian_read_16(command, pos + 7);
25593844aeadSMatthias Ringwald                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
2560bbc0a9e7SMatthias Ringwald                         channel->remote_tx_window_size,
2561bbc0a9e7SMatthias Ringwald                         channel->remote_max_transmit,
2562bbc0a9e7SMatthias Ringwald                         channel->remote_retransmission_timeout_ms,
25633844aeadSMatthias Ringwald                         channel->remote_monitor_timeout_ms,
25643844aeadSMatthias Ringwald                         channel->remote_mps);
256525cd60d3SMatthias Ringwald                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
256625cd60d3SMatthias Ringwald                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
256725cd60d3SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2568ac8f1300SMatthias Ringwald                     } else {
2569b8134563SMatthias Ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2570ac8f1300SMatthias Ringwald                     }
2571ac8f1300SMatthias Ringwald                     break;
2572ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
2573ac8f1300SMatthias Ringwald                     switch (mode){
2574ac8f1300SMatthias Ringwald                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2575ac8f1300SMatthias Ringwald                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
2576ac8f1300SMatthias Ringwald                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
2577ac8f1300SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2578ac8f1300SMatthias Ringwald                             }
2579ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
2580ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
2581ac8f1300SMatthias Ringwald                             break;
2582ac8f1300SMatthias Ringwald                         default: // case L2CAP_CHANNEL_MODE_BASIC:
2583ac8f1300SMatthias Ringwald                             // TODO store and evaluate configuration
2584b8134563SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2585ac8f1300SMatthias Ringwald                             break;
2586ac8f1300SMatthias Ringwald                     }
2587ac8f1300SMatthias Ringwald                     break;
2588ac8f1300SMatthias Ringwald                 default:
2589ac8f1300SMatthias Ringwald                     break;
2590ac8f1300SMatthias Ringwald             }
25913232a1c6SMatthias Ringwald         }
25926574158aSMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
2593fcb125edSMatthias Ringwald             use_fcs = command[pos];
25946574158aSMatthias Ringwald         }
25956dca2a0cSMatthias Ringwald #endif
259663a7246aSmatthias.ringwald         // check for unknown options
2597505f1c30SMatthias Ringwald         if ((option_hint == 0) && ((option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) || (option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE))){
2598c177a91cS[email protected]             log_info("l2cap cid %u, unknown options", channel->local_cid);
259963a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
26001dc511deSmatthias.ringwald         }
26011dc511deSmatthias.ringwald         pos += length;
26021dc511deSmatthias.ringwald     }
2603fcb125edSMatthias Ringwald 
2604fcb125edSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2605fcb125edSMatthias Ringwald         // "FCS" has precedence over "No FCS"
2606fcb125edSMatthias Ringwald         uint8_t update = channel->fcs_option || use_fcs;
2607fcb125edSMatthias Ringwald         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
2608fcb125edSMatthias Ringwald         channel->fcs_option = update;
260967f8f607SMatthias Ringwald         // If ERTM mandatory, but remote didn't send Retransmission and Flowcontrol options -> disconnect
261067f8f607SMatthias Ringwald         if (((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM) == 0) & (channel->ertm_mandatory)){
261167f8f607SMatthias Ringwald             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
261267f8f607SMatthias Ringwald         }
2613fcb125edSMatthias Ringwald #endif
26142784b77dSmatthias.ringwald }
26152784b77dSmatthias.ringwald 
2616e9cfb251SMatthias Ringwald // @pre command len is valid, see check in l2cap_signaling_handler_channel
2617f2fa388dSMatthias Ringwald static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
2618f2fa388dSMatthias Ringwald     log_info("l2cap_signaling_handle_configure_response");
26193232a1c6SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
26203232a1c6SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2621f2fa388dSMatthias Ringwald     uint16_t pos     = 10;
26223232a1c6SMatthias Ringwald     while (pos < end_pos){
26233232a1c6SMatthias Ringwald         uint8_t option_hint = command[pos] >> 7;
26243232a1c6SMatthias Ringwald         uint8_t option_type = command[pos] & 0x7f;
2625fcb125edSMatthias Ringwald         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
26263232a1c6SMatthias Ringwald         pos++;
26273232a1c6SMatthias Ringwald         uint8_t length = command[pos++];
26283232a1c6SMatthias Ringwald 
26293232a1c6SMatthias Ringwald         // Retransmission and Flow Control Option
2630671fb338SMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2631ac8f1300SMatthias Ringwald             switch (channel->mode){
2632ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2633f2fa388dSMatthias Ringwald                     if (channel->ertm_mandatory){
2634ac8f1300SMatthias Ringwald                         // ??
2635f2fa388dSMatthias Ringwald                     } else {
2636ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
2637ac8f1300SMatthias Ringwald                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
263866a72640SMatthias Ringwald                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
2639f2fa388dSMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
26403232a1c6SMatthias Ringwald                         }
26413232a1c6SMatthias Ringwald                     }
2642ac8f1300SMatthias Ringwald                     break;
2643ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
2644ac8f1300SMatthias Ringwald                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2645ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
2646ac8f1300SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2647ac8f1300SMatthias Ringwald                     }
2648ac8f1300SMatthias Ringwald                     break;
2649ac8f1300SMatthias Ringwald                 default:
2650ac8f1300SMatthias Ringwald                     break;
26513232a1c6SMatthias Ringwald             }
2652f2fa388dSMatthias Ringwald         }
26533232a1c6SMatthias Ringwald 
26543232a1c6SMatthias Ringwald         // check for unknown options
2655671fb338SMatthias Ringwald         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
26563232a1c6SMatthias Ringwald             log_info("l2cap cid %u, unknown options", channel->local_cid);
26573232a1c6SMatthias Ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
26583232a1c6SMatthias Ringwald         }
26593232a1c6SMatthias Ringwald 
26603232a1c6SMatthias Ringwald         pos += length;
26613232a1c6SMatthias Ringwald     }
2662688f9764SMatthias Ringwald #else
26635774a392SMatthias Ringwald     UNUSED(channel);  // ok: no code
26645774a392SMatthias Ringwald     UNUSED(result);   // ok: no code
26655774a392SMatthias Ringwald     UNUSED(command);  // ok: no code
26663232a1c6SMatthias Ringwald #endif
26673232a1c6SMatthias Ringwald }
26683232a1c6SMatthias Ringwald 
2669fa8473a4Smatthias.ringwald static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
26709da54300S[email protected]     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
267173cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
267273cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
2673019f9b43SMatthias Ringwald     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
2674019f9b43SMatthias Ringwald     if (channel->state == L2CAP_STATE_OPEN) return 0;
2675fa8473a4Smatthias.ringwald     return 1;
2676fa8473a4Smatthias.ringwald }
2677fa8473a4Smatthias.ringwald 
2678fa8473a4Smatthias.ringwald 
2679e9cfb251SMatthias Ringwald // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
26807f02f414SMatthias Ringwald static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
26811e6aba47Smatthias.ringwald 
268200d93d79Smatthias.ringwald     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
268300d93d79Smatthias.ringwald     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2684e9cfb251SMatthias Ringwald     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
268538e5900eSmatthias.ringwald     uint16_t result = 0;
26861e6aba47Smatthias.ringwald 
26879da54300S[email protected]     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
2688b35f641cSmatthias.ringwald 
26899a011532Smatthias.ringwald     // handle DISCONNECT REQUESTS seperately
26909a011532Smatthias.ringwald     if (code == DISCONNECTION_REQUEST){
26919a011532Smatthias.ringwald         switch (channel->state){
2692fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
26939a011532Smatthias.ringwald             case L2CAP_STATE_OPEN:
26942b83fb7dSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
26959a011532Smatthias.ringwald             case L2CAP_STATE_WAIT_DISCONNECT:
26969a011532Smatthias.ringwald                 l2cap_handle_disconnect_request(channel, identifier);
26979a011532Smatthias.ringwald                 break;
26989a011532Smatthias.ringwald 
26999a011532Smatthias.ringwald             default:
27009a011532Smatthias.ringwald                 // ignore in other states
27019a011532Smatthias.ringwald                 break;
27029a011532Smatthias.ringwald         }
27039a011532Smatthias.ringwald         return;
27049a011532Smatthias.ringwald     }
27059a011532Smatthias.ringwald 
270656081214Smatthias.ringwald     // @STATEMACHINE(l2cap)
27071e6aba47Smatthias.ringwald     switch (channel->state) {
27081e6aba47Smatthias.ringwald 
27091e6aba47Smatthias.ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
27101e6aba47Smatthias.ringwald             switch (code){
27111e6aba47Smatthias.ringwald                 case CONNECTION_RESPONSE:
2712e9cfb251SMatthias Ringwald                     if (cmd_len < 8){
2713e9cfb251SMatthias Ringwald                         // command imcomplete
2714e9cfb251SMatthias Ringwald                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2715e9cfb251SMatthias Ringwald                         break;
2716e9cfb251SMatthias Ringwald                     }
27175932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2718f8fbdce0SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
271938e5900eSmatthias.ringwald                     switch (result) {
272038e5900eSmatthias.ringwald                         case 0:
2721169f8b28Smatthias.ringwald                             // successful connection
2722f8fbdce0SMatthias Ringwald                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2723fa8473a4Smatthias.ringwald                             channel->state = L2CAP_STATE_CONFIG;
272428ca2b46S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
272538e5900eSmatthias.ringwald                             break;
272638e5900eSmatthias.ringwald                         case 1:
27275932bd7cS[email protected]                             // connection pending. get some coffee, but start the ERTX
27285932bd7cS[email protected]                             l2cap_start_ertx(channel);
272938e5900eSmatthias.ringwald                             break;
273038e5900eSmatthias.ringwald                         default:
2731eb920dbeSmatthias.ringwald                             // channel closed
2732eb920dbeSmatthias.ringwald                             channel->state = L2CAP_STATE_CLOSED;
2733f32b992eSmatthias.ringwald                             // map l2cap connection response result to BTstack status enumeration
273466a72640SMatthias Ringwald                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
2735eb920dbeSmatthias.ringwald 
2736eb920dbeSmatthias.ringwald                             // drop link key if security block
2737c1ab6cc1SMatthias Ringwald                             if ((L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result) == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
273815a95bd5SMatthias Ringwald                                 gap_drop_link_key_for_bd_addr(channel->address);
2739eb920dbeSmatthias.ringwald                             }
2740eb920dbeSmatthias.ringwald 
2741eb920dbeSmatthias.ringwald                             // discard channel
2742665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2743c45d6b2cSMatthias Ringwald                             l2cap_free_channel_entry(channel);
274438e5900eSmatthias.ringwald                             break;
27451e6aba47Smatthias.ringwald                     }
27461e6aba47Smatthias.ringwald                     break;
274738e5900eSmatthias.ringwald 
274838e5900eSmatthias.ringwald                 default:
27491e6aba47Smatthias.ringwald                     //@TODO: implement other signaling packets
275038e5900eSmatthias.ringwald                     break;
27511e6aba47Smatthias.ringwald             }
27521e6aba47Smatthias.ringwald             break;
27531e6aba47Smatthias.ringwald 
2754fa8473a4Smatthias.ringwald         case L2CAP_STATE_CONFIG:
2755ae280e73Smatthias.ringwald             switch (code) {
2756ae280e73Smatthias.ringwald                 case CONFIGURE_REQUEST:
2757e9cfb251SMatthias Ringwald                     if (cmd_len < 4){
2758e9cfb251SMatthias Ringwald                         // command incomplete
2759e9cfb251SMatthias Ringwald                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2760e9cfb251SMatthias Ringwald                         break;
2761e9cfb251SMatthias Ringwald                     }
276228ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
2763ae280e73Smatthias.ringwald                     l2cap_signaling_handle_configure_request(channel, command);
276463a7246aSmatthias.ringwald                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
276563a7246aSmatthias.ringwald                         // only done if continuation not set
276663a7246aSmatthias.ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
276763a7246aSmatthias.ringwald                     }
2768ae280e73Smatthias.ringwald                     break;
27691e6aba47Smatthias.ringwald                 case CONFIGURE_RESPONSE:
2770e9cfb251SMatthias Ringwald                     if (cmd_len < 6){
2771e9cfb251SMatthias Ringwald                         // command incomplete
2772e9cfb251SMatthias Ringwald                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2773e9cfb251SMatthias Ringwald                         break;
2774e9cfb251SMatthias Ringwald                     }
2775e9cfb251SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
27765932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2777f2fa388dSMatthias Ringwald                     l2cap_signaling_handle_configure_response(channel, result, command);
27785932bd7cS[email protected]                     switch (result){
27795932bd7cS[email protected]                         case 0: // success
27805932bd7cS[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
27815932bd7cS[email protected]                             break;
27825932bd7cS[email protected]                         case 4: // pending
27835932bd7cS[email protected]                             l2cap_start_ertx(channel);
27845932bd7cS[email protected]                             break;
27855932bd7cS[email protected]                         default:
2786a32d6a03SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2787a32d6a03SMatthias Ringwald                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
2788a32d6a03SMatthias Ringwald                                 // remote does not offer ertm but it's required
2789a32d6a03SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2790a32d6a03SMatthias Ringwald                                 break;
2791a32d6a03SMatthias Ringwald                             }
2792a32d6a03SMatthias Ringwald #endif
2793fe9d8984S[email protected]                             // retry on negative result
2794fe9d8984S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2795fe9d8984S[email protected]                             break;
2796fe9d8984S[email protected]                     }
27975a67bd4aSmatthias.ringwald                     break;
27985a67bd4aSmatthias.ringwald                 default:
27995a67bd4aSmatthias.ringwald                     break;
28001e6aba47Smatthias.ringwald             }
2801fa8473a4Smatthias.ringwald             if (l2cap_channel_ready_for_open(channel)){
28022e4c1850SMatthias Ringwald 
28032e4c1850SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
28042e4c1850SMatthias Ringwald                 // assert that packet can be stored in fragment buffers in ertm
28052e4c1850SMatthias Ringwald                 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
28062e4c1850SMatthias Ringwald                     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
28072e4c1850SMatthias Ringwald                     uint16_t usable_mtu = channel->num_tx_buffers == 1 ? effective_mps : channel->num_tx_buffers * effective_mps - 2;
28082e4c1850SMatthias Ringwald                     if (usable_mtu < channel->remote_mtu){
28092e4c1850SMatthias Ringwald                         log_info("Remote MTU %u > max storable ERTM packet, only using MTU = %u", channel->remote_mtu, usable_mtu);
28102e4c1850SMatthias Ringwald                         channel->remote_mtu = usable_mtu;
28112e4c1850SMatthias Ringwald                     }
28122e4c1850SMatthias Ringwald                 }
28132e4c1850SMatthias Ringwald #endif
2814fa8473a4Smatthias.ringwald                 // for open:
28155a67bd4aSmatthias.ringwald                 channel->state = L2CAP_STATE_OPEN;
2816fa8473a4Smatthias.ringwald                 l2cap_emit_channel_opened(channel, 0);
2817c8e4258aSmatthias.ringwald             }
2818c8e4258aSmatthias.ringwald             break;
2819f62db1e3Smatthias.ringwald 
2820f62db1e3Smatthias.ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
2821f62db1e3Smatthias.ringwald             switch (code) {
2822f62db1e3Smatthias.ringwald                 case DISCONNECTION_RESPONSE:
282327a923d0Smatthias.ringwald                     l2cap_finialize_channel_close(channel);
282427a923d0Smatthias.ringwald                     break;
28255a67bd4aSmatthias.ringwald                 default:
28265a67bd4aSmatthias.ringwald                     //@TODO: implement other signaling packets
28275a67bd4aSmatthias.ringwald                     break;
282827a923d0Smatthias.ringwald             }
282927a923d0Smatthias.ringwald             break;
283084836b65Smatthias.ringwald 
283184836b65Smatthias.ringwald         case L2CAP_STATE_CLOSED:
283284836b65Smatthias.ringwald             // @TODO handle incoming requests
283384836b65Smatthias.ringwald             break;
283484836b65Smatthias.ringwald 
283584836b65Smatthias.ringwald         case L2CAP_STATE_OPEN:
283684836b65Smatthias.ringwald             //@TODO: implement other signaling packets, e.g. re-configure
283784836b65Smatthias.ringwald             break;
283810642e45Smatthias.ringwald         default:
283910642e45Smatthias.ringwald             break;
284027a923d0Smatthias.ringwald     }
28419da54300S[email protected]     // log_info("new state %u", channel->state);
284227a923d0Smatthias.ringwald }
284327a923d0Smatthias.ringwald 
284400d93d79Smatthias.ringwald 
2845ed2ed8e1SMatthias Ringwald // @pre command len is valid, see check in l2cap_acl_classic_handler
28467f02f414SMatthias Ringwald static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
284700d93d79Smatthias.ringwald 
28481b9cb13dSMatthias Ringwald     btstack_linked_list_iterator_t it;
28491b9cb13dSMatthias Ringwald 
285000d93d79Smatthias.ringwald     // get code, signalind identifier and command len
285100d93d79Smatthias.ringwald     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
285200d93d79Smatthias.ringwald     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
28530493bf3aSMatthias Ringwald     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
285400d93d79Smatthias.ringwald 
28551b9cb13dSMatthias Ringwald     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
2856505f1c30SMatthias Ringwald     if ((code < 1) || (code == ECHO_RESPONSE) || (code > INFORMATION_RESPONSE)){
2857e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
285800d93d79Smatthias.ringwald         return;
285900d93d79Smatthias.ringwald     }
286000d93d79Smatthias.ringwald 
286100d93d79Smatthias.ringwald     // general commands without an assigned channel
286200d93d79Smatthias.ringwald     switch(code) {
286300d93d79Smatthias.ringwald 
28640493bf3aSMatthias Ringwald         case CONNECTION_REQUEST:
28650493bf3aSMatthias Ringwald             if (cmd_len == 4){
2866f8fbdce0SMatthias Ringwald                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2867f8fbdce0SMatthias Ringwald                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
286800d93d79Smatthias.ringwald                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
28690493bf3aSMatthias Ringwald             } else {
28700493bf3aSMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
287100d93d79Smatthias.ringwald             }
28720493bf3aSMatthias Ringwald             return;
287300d93d79Smatthias.ringwald 
28742b360848Smatthias.ringwald         case ECHO_REQUEST:
2875e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
28762b83fb7dSmatthias.ringwald             return;
287700d93d79Smatthias.ringwald 
28780493bf3aSMatthias Ringwald         case INFORMATION_REQUEST:
28790493bf3aSMatthias Ringwald             if (cmd_len == 2) {
28803e64cb44SMatthias Ringwald                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
28813e64cb44SMatthias Ringwald                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
28820493bf3aSMatthias Ringwald             } else {
28830493bf3aSMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
288400d93d79Smatthias.ringwald             }
28850493bf3aSMatthias Ringwald             return;
288600d93d79Smatthias.ringwald 
28871b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
28881b9cb13dSMatthias Ringwald         case INFORMATION_RESPONSE: {
28891b9cb13dSMatthias Ringwald             hci_connection_t * connection = hci_connection_for_handle(handle);
28901b9cb13dSMatthias Ringwald             if (!connection) return;
28910defadfbSMatthias Ringwald             if (connection->l2cap_state.information_state != L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE) return;
28920defadfbSMatthias Ringwald 
28930defadfbSMatthias Ringwald             // get extended features from response if valid
28940defadfbSMatthias Ringwald             connection->l2cap_state.extended_feature_mask = 0;
28950defadfbSMatthias Ringwald             if (cmd_len >= 6) {
28961b9cb13dSMatthias Ringwald                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
28971b9cb13dSMatthias Ringwald                 uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
28980defadfbSMatthias Ringwald                 if (result == 0 && info_type == L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) {
28991b9cb13dSMatthias Ringwald                     connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
29000defadfbSMatthias Ringwald                 }
29010defadfbSMatthias Ringwald             }
29020defadfbSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
2903543b84e4SMatthias Ringwald             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
29040defadfbSMatthias Ringwald 
29051b9cb13dSMatthias Ringwald             // trigger connection request
29061b9cb13dSMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
29071b9cb13dSMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
29081b9cb13dSMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2909fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2910543b84e4SMatthias Ringwald                 if (channel->con_handle != handle) continue;
2911f8ecb114SMatthias Ringwald 
2912f8ecb114SMatthias Ringwald                 // incoming connection: ask user for channel configuration, esp. if ertm will be mandatory
2913f8ecb114SMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
2914f8ecb114SMatthias Ringwald                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2915f8ecb114SMatthias Ringwald                     l2cap_emit_incoming_connection(channel);
2916f8ecb114SMatthias Ringwald                     continue;
2917f8ecb114SMatthias Ringwald                 }
2918f8ecb114SMatthias Ringwald 
2919f8ecb114SMatthias Ringwald                 // outgoing connection
2920f8ecb114SMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
2921f8ecb114SMatthias Ringwald 
2922dae3b2abSMatthias Ringwald                     // if ERTM was requested, but is not listed in extended feature mask:
2923543b84e4SMatthias Ringwald                     if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2924dae3b2abSMatthias Ringwald 
2925f073f086SMatthias Ringwald                         if (channel->ertm_mandatory){
2926dae3b2abSMatthias Ringwald                             // bail if ERTM is mandatory
2927543b84e4SMatthias Ringwald                             channel->state = L2CAP_STATE_CLOSED;
2928543b84e4SMatthias Ringwald                             // map l2cap connection response result to BTstack status enumeration
292966a72640SMatthias Ringwald                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
2930543b84e4SMatthias Ringwald                             // discard channel
2931543b84e4SMatthias Ringwald                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2932c45d6b2cSMatthias Ringwald                             l2cap_free_channel_entry(channel);
2933543b84e4SMatthias Ringwald                             continue;
2934dae3b2abSMatthias Ringwald 
2935f073f086SMatthias Ringwald                         } else {
2936f073f086SMatthias Ringwald                             // fallback to Basic mode
293766a72640SMatthias Ringwald                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
2938f073f086SMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2939f073f086SMatthias Ringwald                         }
2940dae3b2abSMatthias Ringwald                     }
2941f8ecb114SMatthias Ringwald 
294252606043SMatthias Ringwald                     // respond to connection request
2943f8ecb114SMatthias Ringwald                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
2944f8ecb114SMatthias Ringwald                     continue;
294552606043SMatthias Ringwald                 }
29461b9cb13dSMatthias Ringwald             }
29471b9cb13dSMatthias Ringwald             return;
29481b9cb13dSMatthias Ringwald         }
29491b9cb13dSMatthias Ringwald #endif
29501b9cb13dSMatthias Ringwald 
295100d93d79Smatthias.ringwald         default:
295200d93d79Smatthias.ringwald             break;
295300d93d79Smatthias.ringwald     }
295400d93d79Smatthias.ringwald 
295500d93d79Smatthias.ringwald     // Get potential destination CID
2956f8fbdce0SMatthias Ringwald     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
295700d93d79Smatthias.ringwald 
295800d93d79Smatthias.ringwald     // Find channel for this sig_id and connection handle
2959665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2960665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2961665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2962fad84cafSMatthias Ringwald         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2963fc64f94aSMatthias Ringwald         if (channel->con_handle != handle) continue;
296400d93d79Smatthias.ringwald         if (code & 1) {
2965b1988dceSmatthias.ringwald             // match odd commands (responses) by previous signaling identifier
2966b1988dceSmatthias.ringwald             if (channel->local_sig_id == sig_id) {
296700d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
29684e32727eSmatthias.ringwald                 break;
296900d93d79Smatthias.ringwald             }
297000d93d79Smatthias.ringwald         } else {
2971b1988dceSmatthias.ringwald             // match even commands (requests) by local channel id
297200d93d79Smatthias.ringwald             if (channel->local_cid == dest_cid) {
297300d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
29744e32727eSmatthias.ringwald                 break;
297500d93d79Smatthias.ringwald             }
297600d93d79Smatthias.ringwald         }
297700d93d79Smatthias.ringwald     }
297800d93d79Smatthias.ringwald }
297909e9d05bSMatthias Ringwald #endif
298000d93d79Smatthias.ringwald 
2981e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
298209e9d05bSMatthias Ringwald 
298309e9d05bSMatthias Ringwald static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
298409e9d05bSMatthias Ringwald     uint8_t event[6];
298509e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
298609e9d05bSMatthias Ringwald     event[1] = 4;
298709e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
298809e9d05bSMatthias Ringwald     little_endian_store_16(event, 4, result);
298909e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
299009e9d05bSMatthias Ringwald     if (!l2cap_event_packet_handler) return;
299109e9d05bSMatthias Ringwald     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
299209e9d05bSMatthias Ringwald }
299309e9d05bSMatthias Ringwald 
2994c48b2a2cSMatthias Ringwald // @returns valid
2995c48b2a2cSMatthias Ringwald static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
2996e7d0c9aaSMatthias Ringwald     hci_connection_t * connection;
2997c48b2a2cSMatthias Ringwald     uint16_t result;
2998f299206dSMatthias Ringwald     uint8_t  event[12];
299983fd9c76SMatthias Ringwald 
3000cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
3001a3dc965aSMatthias Ringwald     btstack_linked_list_iterator_t it;
3002a3dc965aSMatthias Ringwald     l2cap_channel_t * channel;
3003a3dc965aSMatthias Ringwald     uint16_t local_cid;
300483fd9c76SMatthias Ringwald     uint16_t le_psm;
300563f0ac45SMatthias Ringwald     uint16_t new_credits;
300663f0ac45SMatthias Ringwald     uint16_t credits_before;
3007e7d0c9aaSMatthias Ringwald     l2cap_service_t * service;
300811cae19eSMilanka Ringwald     uint16_t source_cid;
300983fd9c76SMatthias Ringwald #endif
301000d93d79Smatthias.ringwald 
30111b8b8d05SMatthias Ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3012adcfabadSMatthias Ringwald     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
30131fcd10b7SMatthias Ringwald     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
30141b8b8d05SMatthias Ringwald 
30151b8b8d05SMatthias Ringwald     switch (code){
301600d93d79Smatthias.ringwald 
3017c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_REQUEST:
3018adcfabadSMatthias Ringwald             // check size
30191fcd10b7SMatthias Ringwald             if (len < 8) return 0;
3020e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
3021da886c03S[email protected]             if (connection){
30226d91fb6cSMatthias Ringwald                 if (connection->role != HCI_ROLE_MASTER){
30236d91fb6cSMatthias Ringwald                     // reject command without notifying upper layer when not in master role
3024c48b2a2cSMatthias Ringwald                     return 0;
30256d91fb6cSMatthias Ringwald                 }
3026a4c06b28SMatthias Ringwald                 le_connection_parameter_range_t existing_range;
30274ced4e8cSMatthias Ringwald                 gap_get_connection_parameter_range(&existing_range);
3028d5e694a3SMatthias Ringwald                 uint16_t le_conn_interval_min   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3029d5e694a3SMatthias Ringwald                 uint16_t le_conn_interval_max   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3030d5e694a3SMatthias Ringwald                 uint16_t le_conn_latency        = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3031d5e694a3SMatthias Ringwald                 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
3032da886c03S[email protected] 
303373cd8a2aSMatthias 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);
3034da886c03S[email protected]                 if (update_parameter){
3035da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
3036da886c03S[email protected]                     connection->le_conn_interval_min = le_conn_interval_min;
3037da886c03S[email protected]                     connection->le_conn_interval_max = le_conn_interval_max;
3038da886c03S[email protected]                     connection->le_conn_latency = le_conn_latency;
3039da886c03S[email protected]                     connection->le_supervision_timeout = le_supervision_timeout;
3040da886c03S[email protected]                 } else {
3041da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
3042da886c03S[email protected]                 }
3043c48b2a2cSMatthias Ringwald                 connection->le_con_param_update_identifier = sig_id;
3044da886c03S[email protected]             }
3045da886c03S[email protected] 
304633c40538SMatthias Ringwald             if (!l2cap_event_packet_handler) break;
3047c48b2a2cSMatthias Ringwald 
3048c48b2a2cSMatthias Ringwald             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
3049c48b2a2cSMatthias Ringwald             event[1] = 8;
3050f299206dSMatthias Ringwald             little_endian_store_16(event, 2, handle);
30516535961aSMatthias Ringwald             (void)memcpy(&event[4], &command[4], 8);
3052c48b2a2cSMatthias Ringwald             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
305333c40538SMatthias Ringwald             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
3054ccf076adS[email protected]             break;
3055c48b2a2cSMatthias Ringwald 
30561fcd10b7SMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
30571fcd10b7SMatthias Ringwald             // check size
30581fcd10b7SMatthias Ringwald             if (len < 2) return 0;
30591fcd10b7SMatthias Ringwald             result = little_endian_read_16(command, 4);
30601fcd10b7SMatthias Ringwald             l2cap_emit_connection_parameter_update_response(handle, result);
30611fcd10b7SMatthias Ringwald             break;
30621fcd10b7SMatthias Ringwald 
3063a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
3064a3dc965aSMatthias Ringwald 
306563f0ac45SMatthias Ringwald         case COMMAND_REJECT:
306663f0ac45SMatthias Ringwald             // Find channel for this sig_id and connection handle
306763f0ac45SMatthias Ringwald             channel = NULL;
3068421cb104SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
306963f0ac45SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
307063f0ac45SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3071fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
307263f0ac45SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
307363f0ac45SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
307463f0ac45SMatthias Ringwald                 channel = a_channel;
307563f0ac45SMatthias Ringwald                 break;
307663f0ac45SMatthias Ringwald             }
307763f0ac45SMatthias Ringwald             if (!channel) break;
307863f0ac45SMatthias Ringwald 
307963f0ac45SMatthias Ringwald             // if received while waiting for le connection response, assume legacy device
308063f0ac45SMatthias Ringwald             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
308163f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
308263f0ac45SMatthias Ringwald                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
308344276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0x0002);
308463f0ac45SMatthias Ringwald 
308563f0ac45SMatthias Ringwald                 // discard channel
3086421cb104SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3087c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
308863f0ac45SMatthias Ringwald                 break;
308963f0ac45SMatthias Ringwald             }
309063f0ac45SMatthias Ringwald             break;
309163f0ac45SMatthias Ringwald 
3092e7d0c9aaSMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_REQUEST:
3093adcfabadSMatthias Ringwald             // check size
3094adcfabadSMatthias Ringwald             if (len < 10) return 0;
3095e7d0c9aaSMatthias Ringwald 
3096e7d0c9aaSMatthias Ringwald             // get hci connection, bail if not found (must not happen)
3097e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
3098e7d0c9aaSMatthias Ringwald             if (!connection) return 0;
3099e7d0c9aaSMatthias Ringwald 
3100e7d0c9aaSMatthias Ringwald             // check if service registered
3101e7d0c9aaSMatthias Ringwald             le_psm  = little_endian_read_16(command, 4);
3102e7d0c9aaSMatthias Ringwald             service = l2cap_le_get_service(le_psm);
310311cae19eSMilanka Ringwald             source_cid = little_endian_read_16(command, 6);
3104e7d0c9aaSMatthias Ringwald 
3105e7d0c9aaSMatthias Ringwald             if (service){
3106e7d0c9aaSMatthias Ringwald                 if (source_cid < 0x40){
3107e7d0c9aaSMatthias Ringwald                     // 0x0009 Connection refused - Invalid Source CID
3108e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
3109e7d0c9aaSMatthias Ringwald                     return 1;
3110e7d0c9aaSMatthias Ringwald                 }
3111e7d0c9aaSMatthias Ringwald 
3112e7d0c9aaSMatthias Ringwald                 // go through list of channels for this ACL connection and check if we get a match
3113421cb104SMatthias Ringwald                 btstack_linked_list_iterator_init(&it, &l2cap_channels);
3114e7d0c9aaSMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&it)){
31151b8b8d05SMatthias Ringwald                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3116fad84cafSMatthias Ringwald                     if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
31171b8b8d05SMatthias Ringwald                     if (a_channel->con_handle != handle) continue;
31181b8b8d05SMatthias Ringwald                     if (a_channel->remote_cid != source_cid) continue;
3119e7d0c9aaSMatthias Ringwald                     // 0x000a Connection refused - Source CID already allocated
3120e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
3121e7d0c9aaSMatthias Ringwald                     return 1;
3122e7d0c9aaSMatthias Ringwald                 }
3123e7d0c9aaSMatthias Ringwald 
312483fd9c76SMatthias Ringwald                 // security: check encryption
312583fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_2){
31269c6e867eSMatthias Ringwald                     if (gap_encryption_key_size(handle) == 0){
312783fd9c76SMatthias Ringwald                         // 0x0008 Connection refused - insufficient encryption
3128e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
312983fd9c76SMatthias Ringwald                         return 1;
313083fd9c76SMatthias Ringwald                     }
313183fd9c76SMatthias Ringwald                     // anything less than 16 byte key size is insufficient
31329c6e867eSMatthias Ringwald                     if (gap_encryption_key_size(handle) < 16){
313383fd9c76SMatthias Ringwald                         // 0x0007 Connection refused – insufficient encryption key size
3134e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
313583fd9c76SMatthias Ringwald                         return 1;
313683fd9c76SMatthias Ringwald                     }
313783fd9c76SMatthias Ringwald                 }
313883fd9c76SMatthias Ringwald 
313983fd9c76SMatthias Ringwald                 // security: check authencation
314083fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_3){
31419c6e867eSMatthias Ringwald                     if (!gap_authenticated(handle)){
314283fd9c76SMatthias Ringwald                         // 0x0005 Connection refused – insufficient authentication
3143e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
314483fd9c76SMatthias Ringwald                         return 1;
314583fd9c76SMatthias Ringwald                     }
314683fd9c76SMatthias Ringwald                 }
314783fd9c76SMatthias Ringwald 
314883fd9c76SMatthias Ringwald                 // security: check authorization
314983fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_4){
31509c6e867eSMatthias Ringwald                     if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
315183fd9c76SMatthias Ringwald                         // 0x0006 Connection refused – insufficient authorization
3152e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
315383fd9c76SMatthias Ringwald                         return 1;
315483fd9c76SMatthias Ringwald                     }
315583fd9c76SMatthias Ringwald                 }
3156e7d0c9aaSMatthias Ringwald 
3157e7d0c9aaSMatthias Ringwald                 // allocate channel
31585d18f623SMatthias Ringwald                 channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL, connection->address,
3159e7d0c9aaSMatthias Ringwald                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
3160e7d0c9aaSMatthias Ringwald                 if (!channel){
3161e7d0c9aaSMatthias Ringwald                     // 0x0004 Connection refused – no resources available
3162e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
3163e7d0c9aaSMatthias Ringwald                     return 1;
3164e7d0c9aaSMatthias Ringwald                 }
3165e7d0c9aaSMatthias Ringwald 
3166e7d0c9aaSMatthias Ringwald                 channel->con_handle = handle;
3167e7d0c9aaSMatthias Ringwald                 channel->remote_cid = source_cid;
3168e7d0c9aaSMatthias Ringwald                 channel->remote_sig_id = sig_id;
31697f107edaSMatthias Ringwald                 channel->remote_mtu = little_endian_read_16(command, 8);
31707f107edaSMatthias Ringwald                 channel->remote_mps = little_endian_read_16(command, 10);
31717f107edaSMatthias Ringwald                 channel->credits_outgoing = little_endian_read_16(command, 12);
3172e7d0c9aaSMatthias Ringwald 
3173e7d0c9aaSMatthias Ringwald                 // set initial state
3174e7d0c9aaSMatthias Ringwald                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
3175c99bb618SMatthias Ringwald                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
3176e7d0c9aaSMatthias Ringwald 
3177e7d0c9aaSMatthias Ringwald                 // add to connections list
3178421cb104SMatthias Ringwald                 btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
3179e7d0c9aaSMatthias Ringwald 
3180e7d0c9aaSMatthias Ringwald                 // post connection request event
318144276248SMatthias Ringwald                 l2cap_emit_le_incoming_connection(channel);
3182e7d0c9aaSMatthias Ringwald 
3183e7d0c9aaSMatthias Ringwald             } else {
3184e7d0c9aaSMatthias Ringwald                 // Connection refused – LE_PSM not supported
3185e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
3186e7d0c9aaSMatthias Ringwald             }
3187e7d0c9aaSMatthias Ringwald             break;
31881b8b8d05SMatthias Ringwald 
31891b8b8d05SMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
3190adcfabadSMatthias Ringwald             // check size
3191adcfabadSMatthias Ringwald             if (len < 10) return 0;
3192adcfabadSMatthias Ringwald 
31931b8b8d05SMatthias Ringwald             // Find channel for this sig_id and connection handle
31941b8b8d05SMatthias Ringwald             channel = NULL;
3195421cb104SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
31961b8b8d05SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
31971b8b8d05SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3198fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
31991b8b8d05SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
32001b8b8d05SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
32011b8b8d05SMatthias Ringwald                 channel = a_channel;
32021b8b8d05SMatthias Ringwald                 break;
32031b8b8d05SMatthias Ringwald             }
32041b8b8d05SMatthias Ringwald             if (!channel) break;
32051b8b8d05SMatthias Ringwald 
32061b8b8d05SMatthias Ringwald             // cid + 0
32071b8b8d05SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
32081b8b8d05SMatthias Ringwald             if (result){
32091b8b8d05SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
32101b8b8d05SMatthias Ringwald                 // map l2cap connection response result to BTstack status enumeration
321144276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, result);
32121b8b8d05SMatthias Ringwald 
32131b8b8d05SMatthias Ringwald                 // discard channel
3214421cb104SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3215c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
32161b8b8d05SMatthias Ringwald                 break;
32171b8b8d05SMatthias Ringwald             }
32181b8b8d05SMatthias Ringwald 
32191b8b8d05SMatthias Ringwald             // success
32201b8b8d05SMatthias Ringwald             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
32211b8b8d05SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
32221b8b8d05SMatthias Ringwald             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
32231b8b8d05SMatthias Ringwald             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
32241b8b8d05SMatthias Ringwald             channel->state = L2CAP_STATE_OPEN;
322544276248SMatthias Ringwald             l2cap_emit_le_channel_opened(channel, result);
32261b8b8d05SMatthias Ringwald             break;
32271b8b8d05SMatthias Ringwald 
322885aeef60SMatthias Ringwald         case LE_FLOW_CONTROL_CREDIT:
3229adcfabadSMatthias Ringwald             // check size
3230adcfabadSMatthias Ringwald             if (len < 4) return 0;
3231adcfabadSMatthias Ringwald 
323285aeef60SMatthias Ringwald             // find channel
323385aeef60SMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3234421cb104SMatthias Ringwald             channel = l2cap_get_channel_for_local_cid(local_cid);
323563f0ac45SMatthias Ringwald             if (!channel) {
323663f0ac45SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
323763f0ac45SMatthias Ringwald                 break;
323863f0ac45SMatthias Ringwald             }
323963f0ac45SMatthias Ringwald             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
324063f0ac45SMatthias Ringwald             credits_before = channel->credits_outgoing;
324163f0ac45SMatthias Ringwald             channel->credits_outgoing += new_credits;
324263f0ac45SMatthias Ringwald             // check for credit overrun
324363f0ac45SMatthias Ringwald             if (credits_before > channel->credits_outgoing){
324463f0ac45SMatthias Ringwald                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
324563f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
324663f0ac45SMatthias Ringwald                 break;
324763f0ac45SMatthias Ringwald             }
324863f0ac45SMatthias Ringwald             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
324985aeef60SMatthias Ringwald             break;
325085aeef60SMatthias Ringwald 
3251828a7f7aSMatthias Ringwald         case DISCONNECTION_REQUEST:
3252adcfabadSMatthias Ringwald 
3253adcfabadSMatthias Ringwald             // check size
3254adcfabadSMatthias Ringwald             if (len < 4) return 0;
3255adcfabadSMatthias Ringwald 
3256828a7f7aSMatthias Ringwald             // find channel
3257828a7f7aSMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3258421cb104SMatthias Ringwald             channel = l2cap_get_channel_for_local_cid(local_cid);
325963f34e00SMatthias Ringwald             if (!channel) {
326063f34e00SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
326163f34e00SMatthias Ringwald                 break;
326263f34e00SMatthias Ringwald             }
3263828a7f7aSMatthias Ringwald             channel->remote_sig_id = sig_id;
3264828a7f7aSMatthias Ringwald             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
3265828a7f7aSMatthias Ringwald             break;
3266828a7f7aSMatthias Ringwald 
3267a3dc965aSMatthias Ringwald #endif
3268a3dc965aSMatthias Ringwald 
326963f0ac45SMatthias Ringwald         case DISCONNECTION_RESPONSE:
327063f0ac45SMatthias Ringwald             break;
327163f0ac45SMatthias Ringwald 
3272c48b2a2cSMatthias Ringwald         default:
3273c48b2a2cSMatthias Ringwald             // command unknown -> reject command
3274c48b2a2cSMatthias Ringwald             return 0;
3275ccf076adS[email protected]     }
3276c48b2a2cSMatthias Ringwald     return 1;
3277c48b2a2cSMatthias Ringwald }
3278e7d0c9aaSMatthias Ringwald #endif
3279c48b2a2cSMatthias Ringwald 
3280bb0a72a6SMatthias Ringwald #ifdef ENABLE_CLASSIC
3281*0b667d41SMatthias Ringwald static void l2cap_acl_classic_handler_for_channel(l2cap_channel_t * l2cap_channel, uint8_t * packet, uint16_t size){
328227e0774aSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
328327e0774aSMatthias Ringwald     if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
328427e0774aSMatthias Ringwald 
32856574158aSMatthias Ringwald         int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
328607c7de86SMatthias Ringwald 
32876574158aSMatthias Ringwald         // assert control + FCS fields are inside
3288*0b667d41SMatthias Ringwald         if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) return;
32896574158aSMatthias Ringwald 
32906574158aSMatthias Ringwald         if (l2cap_channel->fcs_option){
3291fcb125edSMatthias Ringwald             // verify FCS (required if one side requested it)
329227e0774aSMatthias Ringwald             uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
329327e0774aSMatthias Ringwald             uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
3294e288be62SMatthias Ringwald 
3295e288be62SMatthias Ringwald #ifdef L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL
3296e288be62SMatthias Ringwald             // simulate fcs error
3297e288be62SMatthias Ringwald                         static int counter = 0;
3298e288be62SMatthias Ringwald                         if (++counter == L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL) {
3299e288be62SMatthias Ringwald                             log_info("Simulate fcs error");
3300e288be62SMatthias Ringwald                             fcs_calculated++;
3301e288be62SMatthias Ringwald                             counter = 0;
3302e288be62SMatthias Ringwald                         }
3303e288be62SMatthias Ringwald #endif
3304e288be62SMatthias Ringwald 
33056574158aSMatthias Ringwald             if (fcs_calculated == fcs_packet){
33066574158aSMatthias Ringwald                 log_info("Packet FCS 0x%04x verified", fcs_packet);
33076574158aSMatthias Ringwald             } else {
330827e0774aSMatthias Ringwald                 log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
3309ef2faf56SMatthias Ringwald                 // ERTM State Machine in Bluetooth Spec does not handle 'I-Frame with invalid FCS'
3310*0b667d41SMatthias Ringwald                 return;
331127e0774aSMatthias Ringwald             }
33126574158aSMatthias Ringwald         }
331327e0774aSMatthias Ringwald 
331427e0774aSMatthias Ringwald         // switch on packet type
331527e0774aSMatthias Ringwald         uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
331638f62777SMatthias Ringwald         uint8_t  req_seq = (control >> 8) & 0x3f;
33172bea1b8dSMatthias Ringwald         int final = (control >> 7) & 0x01;
331827e0774aSMatthias Ringwald         if (control & 1){
331927e0774aSMatthias Ringwald             // S-Frame
332078cd8a22SMatthias Ringwald             int poll  = (control >> 4) & 0x01;
3321bdbe2e49SMatthias Ringwald             l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
33229ffcbce4SMatthias Ringwald             log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
33237b7901d8SMatthias Ringwald             l2cap_ertm_tx_packet_state_t * tx_state;
3324bdbe2e49SMatthias Ringwald             switch (s){
3325bdbe2e49SMatthias Ringwald                 case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
33269ffcbce4SMatthias Ringwald                     log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
33271e1a46bbSMatthias Ringwald                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
33283233d8abSMatthias Ringwald                     if (poll && final){
33293233d8abSMatthias Ringwald                         // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
33303233d8abSMatthias Ringwald                         log_error("P=F=1 in S-Frame");
33313233d8abSMatthias Ringwald                         break;
33323233d8abSMatthias Ringwald                     }
333378cd8a22SMatthias Ringwald                     if (poll){
3334f85ade6bSMatthias Ringwald                         // check if we did request selective retransmission before <==> we have stored SDU segments
3335f85ade6bSMatthias Ringwald                         int i;
3336f85ade6bSMatthias Ringwald                         int num_stored_out_of_order_packets = 0;
3337f85ade6bSMatthias Ringwald                         for (i=0;i<l2cap_channel->num_rx_buffers;i++){
3338f85ade6bSMatthias Ringwald                             int index = l2cap_channel->rx_store_index + i;
3339f85ade6bSMatthias Ringwald                             if (index >= l2cap_channel->num_rx_buffers){
3340f85ade6bSMatthias Ringwald                                 index -= l2cap_channel->num_rx_buffers;
3341f85ade6bSMatthias Ringwald                             }
3342f85ade6bSMatthias Ringwald                             l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3343f85ade6bSMatthias Ringwald                             if (!rx_state->valid) continue;
3344f85ade6bSMatthias Ringwald                             num_stored_out_of_order_packets++;
3345f85ade6bSMatthias Ringwald                         }
3346f85ade6bSMatthias Ringwald                         if (num_stored_out_of_order_packets){
3347f85ade6bSMatthias Ringwald                             l2cap_channel->send_supervisor_frame_selective_reject = 1;
3348f85ade6bSMatthias Ringwald                         } else {
3349d2afdd38SMatthias Ringwald                             l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
335078cd8a22SMatthias Ringwald                         }
3351f85ade6bSMatthias Ringwald                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
3352f85ade6bSMatthias Ringwald                     }
33533233d8abSMatthias Ringwald                     if (final){
3354550189ffSMatthias Ringwald                         // Stop-MonitorTimer
3355550189ffSMatthias Ringwald                         l2cap_ertm_stop_monitor_timer(l2cap_channel);
3356550189ffSMatthias Ringwald                         // If UnackedFrames > 0 then Start-RetransTimer
335794301352SMatthias Ringwald                         if (l2cap_channel->unacked_frames){
3358550189ffSMatthias Ringwald                             l2cap_ertm_start_retransmission_timer(l2cap_channel);
3359550189ffSMatthias Ringwald                         }
33603233d8abSMatthias Ringwald                         // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3361ef2faf56SMatthias Ringwald                         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
33623233d8abSMatthias Ringwald                     }
3363bdbe2e49SMatthias Ringwald                     break;
33649ffcbce4SMatthias Ringwald                 case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
33659ffcbce4SMatthias Ringwald                     log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
33661e1a46bbSMatthias Ringwald                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3367600cf12dSMatthias Ringwald                     // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
3368ef2faf56SMatthias Ringwald                     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
33699ffcbce4SMatthias Ringwald                     break;
33709ffcbce4SMatthias Ringwald                 case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
33719ffcbce4SMatthias Ringwald                     log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
33729ffcbce4SMatthias Ringwald                     break;
33739ffcbce4SMatthias Ringwald                 case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
33747b7901d8SMatthias Ringwald                     log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
33757b7901d8SMatthias Ringwald                     if (poll){
33761e1a46bbSMatthias Ringwald                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
33777b7901d8SMatthias Ringwald                     }
33787b7901d8SMatthias Ringwald                     // find requested i-frame
33797b7901d8SMatthias Ringwald                     tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
33807b7901d8SMatthias Ringwald                     if (tx_state){
33817b7901d8SMatthias Ringwald                         log_info("Retransmission for tx_seq %u requested", req_seq);
3382d2afdd38SMatthias Ringwald                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
33837b7901d8SMatthias Ringwald                         tx_state->retransmission_requested = 1;
33847b7901d8SMatthias Ringwald                         l2cap_channel->srej_active = 1;
33857b7901d8SMatthias Ringwald                     }
33869ffcbce4SMatthias Ringwald                     break;
3387bdbe2e49SMatthias Ringwald                 default:
3388bdbe2e49SMatthias Ringwald                     break;
3389bdbe2e49SMatthias Ringwald             }
339027e0774aSMatthias Ringwald         } else {
339127e0774aSMatthias Ringwald             // I-Frame
339227e0774aSMatthias Ringwald             // get control
339327e0774aSMatthias Ringwald             l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
339438f62777SMatthias Ringwald             uint8_t tx_seq = (control >> 1) & 0x3f;
339538f62777SMatthias Ringwald             log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
3396e8e9809fSMatthias Ringwald             log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
339738f62777SMatthias Ringwald             log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
33981e1a46bbSMatthias Ringwald             l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
339911b576c5SMatthias Ringwald             if (final){
340011b576c5SMatthias Ringwald                 // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3401ef2faf56SMatthias Ringwald                 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
340211b576c5SMatthias Ringwald             }
340307c7de86SMatthias Ringwald 
340407c7de86SMatthias Ringwald             // get SDU
3405826c39d0SMatthias Ringwald             const uint8_t * payload_data = &packet[COMPLETE_L2CAP_HEADER+2];
3406826c39d0SMatthias Ringwald             uint16_t        payload_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
340707c7de86SMatthias Ringwald 
340807c7de86SMatthias Ringwald             // assert SDU size is smaller or equal to our buffers
3409826c39d0SMatthias Ringwald             uint16_t max_payload_size = 0;
3410826c39d0SMatthias Ringwald             switch (sar){
3411826c39d0SMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
3412826c39d0SMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
3413826c39d0SMatthias Ringwald                     // SDU Length + MPS
3414826c39d0SMatthias Ringwald                     max_payload_size = l2cap_channel->local_mps + 2;
3415826c39d0SMatthias Ringwald                     break;
3416826c39d0SMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
3417826c39d0SMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
3418826c39d0SMatthias Ringwald                     max_payload_size = l2cap_channel->local_mps;
3419826c39d0SMatthias Ringwald                     break;
3420826c39d0SMatthias Ringwald             }
3421826c39d0SMatthias Ringwald             if (payload_len > max_payload_size){
3422826c39d0SMatthias Ringwald                 log_info("payload len %u > max payload %u -> drop packet", payload_len, max_payload_size);
3423*0b667d41SMatthias Ringwald                 return;
3424826c39d0SMatthias Ringwald             }
342507c7de86SMatthias Ringwald 
342638f62777SMatthias Ringwald             // check ordering
342738f62777SMatthias Ringwald             if (l2cap_channel->expected_tx_seq == tx_seq){
342838f62777SMatthias Ringwald                 log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
342938f62777SMatthias Ringwald                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3430f85ade6bSMatthias Ringwald                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3431d48432d4SMatthias Ringwald 
3432e32be409SMatthias Ringwald                 // process SDU
3433826c39d0SMatthias Ringwald                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, payload_data, payload_len);
3434d48432d4SMatthias Ringwald 
343570734707SMatthias Ringwald                 // process stored segments
3436ff3cc4a5SMatthias Ringwald                 while (true){
343770734707SMatthias Ringwald                     int index = l2cap_channel->rx_store_index;
343870734707SMatthias Ringwald                     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
343970734707SMatthias Ringwald                     if (!rx_state->valid) break;
3440f85ade6bSMatthias Ringwald 
3441f85ade6bSMatthias Ringwald                     log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
3442f85ade6bSMatthias Ringwald                     l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3443f85ade6bSMatthias Ringwald                     l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3444f85ade6bSMatthias Ringwald 
344570734707SMatthias Ringwald                     rx_state->valid = 0;
344670734707SMatthias Ringwald                     l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
3447f85ade6bSMatthias Ringwald 
3448f85ade6bSMatthias Ringwald                     // update rx store index
344970734707SMatthias Ringwald                     index++;
345070734707SMatthias Ringwald                     if (index >= l2cap_channel->num_rx_buffers){
345170734707SMatthias Ringwald                         index = 0;
345270734707SMatthias Ringwald                     }
345370734707SMatthias Ringwald                     l2cap_channel->rx_store_index = index;
345470734707SMatthias Ringwald                 }
345570734707SMatthias Ringwald 
3456f85ade6bSMatthias Ringwald                 //
3457f85ade6bSMatthias Ringwald                 l2cap_channel->send_supervisor_frame_receiver_ready = 1;
3458f85ade6bSMatthias Ringwald 
3459c7309e8dSMatthias Ringwald             } else {
3460df2191a7SMatthias Ringwald                 int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
3461df2191a7SMatthias Ringwald                 if (delta < 2){
346270734707SMatthias Ringwald                     // store segment
3463826c39d0SMatthias Ringwald                     l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, payload_data, payload_len);
346470734707SMatthias Ringwald 
3465df2191a7SMatthias Ringwald                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
3466df2191a7SMatthias Ringwald                     l2cap_channel->send_supervisor_frame_selective_reject = 1;
3467df2191a7SMatthias Ringwald                 } else {
3468df2191a7SMatthias Ringwald                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
3469c7309e8dSMatthias Ringwald                     l2cap_channel->send_supervisor_frame_reject = 1;
347027e0774aSMatthias Ringwald                 }
347138f62777SMatthias Ringwald             }
3472df2191a7SMatthias Ringwald         }
3473*0b667d41SMatthias Ringwald         return;
347427e0774aSMatthias Ringwald     }
347527e0774aSMatthias Ringwald #endif
34763d50b4baSMatthias Ringwald     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3477*0b667d41SMatthias Ringwald 
3478*0b667d41SMatthias Ringwald }
3479*0b667d41SMatthias Ringwald #endif
3480*0b667d41SMatthias Ringwald 
3481*0b667d41SMatthias Ringwald static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3482*0b667d41SMatthias Ringwald #ifdef ENABLE_CLASSIC
3483*0b667d41SMatthias Ringwald     l2cap_channel_t * l2cap_channel;
3484*0b667d41SMatthias Ringwald     l2cap_fixed_channel_t * l2cap_fixed_channel;
3485*0b667d41SMatthias Ringwald 
3486*0b667d41SMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3487*0b667d41SMatthias Ringwald     switch (channel_id) {
3488*0b667d41SMatthias Ringwald 
3489*0b667d41SMatthias Ringwald         case L2CAP_CID_SIGNALING: {
3490*0b667d41SMatthias Ringwald             uint32_t command_offset = 8;
3491*0b667d41SMatthias Ringwald             while ((command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET) < size) {
3492*0b667d41SMatthias Ringwald                 // assert signaling command is fully inside packet
3493*0b667d41SMatthias Ringwald                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3494*0b667d41SMatthias Ringwald                 uint32_t next_command_offset = command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
3495*0b667d41SMatthias Ringwald                 if (next_command_offset > size){
3496*0b667d41SMatthias Ringwald                     log_error("l2cap signaling command len invalid -> drop");
3497*0b667d41SMatthias Ringwald                     break;
3498*0b667d41SMatthias Ringwald                 }
3499*0b667d41SMatthias Ringwald                 // handle signaling command
3500*0b667d41SMatthias Ringwald                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
3501*0b667d41SMatthias Ringwald                 // go to next command
3502*0b667d41SMatthias Ringwald                 command_offset = next_command_offset;
3503*0b667d41SMatthias Ringwald             }
3504*0b667d41SMatthias Ringwald             break;
3505*0b667d41SMatthias Ringwald         }
3506*0b667d41SMatthias Ringwald         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
3507*0b667d41SMatthias Ringwald             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL);
3508*0b667d41SMatthias Ringwald             if (!l2cap_fixed_channel) break;
3509*0b667d41SMatthias Ringwald             if (!l2cap_fixed_channel->packet_handler) break;
3510*0b667d41SMatthias Ringwald             (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3511*0b667d41SMatthias Ringwald             break;
3512*0b667d41SMatthias Ringwald 
3513*0b667d41SMatthias Ringwald         default:
3514*0b667d41SMatthias Ringwald             // Find channel for this channel_id and connection handle
3515*0b667d41SMatthias Ringwald             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
3516*0b667d41SMatthias Ringwald             if (l2cap_channel) {
3517*0b667d41SMatthias Ringwald                 l2cap_acl_classic_handler_for_channel(l2cap_channel, packet, size);
351800d93d79Smatthias.ringwald             }
3519bb0a72a6SMatthias Ringwald             break;
3520bb0a72a6SMatthias Ringwald     }
3521bb0a72a6SMatthias Ringwald #else
3522bb0a72a6SMatthias Ringwald     UNUSED(handle); // ok: no code
3523bb0a72a6SMatthias Ringwald     UNUSED(packet); // ok: no code
3524bb0a72a6SMatthias Ringwald     UNUSED(size);   // ok: no code
352509e9d05bSMatthias Ringwald #endif
3526bb0a72a6SMatthias Ringwald }
3527bb0a72a6SMatthias Ringwald 
3528bb0a72a6SMatthias Ringwald static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3529bb0a72a6SMatthias Ringwald #ifdef ENABLE_BLE
3530bb0a72a6SMatthias Ringwald 
3531fad84cafSMatthias Ringwald     l2cap_fixed_channel_t * l2cap_fixed_channel;
3532fad84cafSMatthias Ringwald 
3533bb0a72a6SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
3534bb0a72a6SMatthias Ringwald     l2cap_channel_t * l2cap_channel;
3535bb0a72a6SMatthias Ringwald #endif
3536bb0a72a6SMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3537bb0a72a6SMatthias Ringwald     switch (channel_id) {
3538bb0a72a6SMatthias Ringwald 
3539bb0a72a6SMatthias Ringwald         case L2CAP_CID_SIGNALING_LE: {
3540bb0a72a6SMatthias Ringwald             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
3541adcfabadSMatthias Ringwald             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
3542505f1c30SMatthias Ringwald             if ((COMPLETE_L2CAP_HEADER + 4 + len) > size) break;
3543bb0a72a6SMatthias Ringwald             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
3544bb0a72a6SMatthias Ringwald             if (!valid){
3545bb0a72a6SMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3546bb0a72a6SMatthias Ringwald             }
3547bb0a72a6SMatthias Ringwald             break;
3548bb0a72a6SMatthias Ringwald         }
3549bb0a72a6SMatthias Ringwald 
3550bb0a72a6SMatthias Ringwald         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
3551fad84cafSMatthias Ringwald             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL);
3552fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel) break;
3553fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel->packet_handler) break;
3554fad84cafSMatthias Ringwald             (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3555bb0a72a6SMatthias Ringwald             break;
3556bb0a72a6SMatthias Ringwald 
3557bb0a72a6SMatthias Ringwald         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
3558fad84cafSMatthias Ringwald             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
3559fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel) break;
3560fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel->packet_handler) break;
3561fad84cafSMatthias Ringwald             (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3562bb0a72a6SMatthias Ringwald             break;
3563bb0a72a6SMatthias Ringwald 
3564bb0a72a6SMatthias Ringwald         default:
3565bb0a72a6SMatthias Ringwald 
3566a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
3567421cb104SMatthias Ringwald             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
356864e11ca9SMatthias Ringwald             if (l2cap_channel) {
356985aeef60SMatthias Ringwald                 // credit counting
357085aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming == 0){
357185aeef60SMatthias Ringwald                     log_error("LE Data Channel packet received but no incoming credits");
357285aeef60SMatthias Ringwald                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
357385aeef60SMatthias Ringwald                     break;
357485aeef60SMatthias Ringwald                 }
357585aeef60SMatthias Ringwald                 l2cap_channel->credits_incoming--;
357685aeef60SMatthias Ringwald 
357785aeef60SMatthias Ringwald                 // automatic credits
3578c1ab6cc1SMatthias Ringwald                 if ((l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK) && l2cap_channel->automatic_credits){
357985aeef60SMatthias Ringwald                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
358085aeef60SMatthias Ringwald                 }
358185aeef60SMatthias Ringwald 
3582cd529728SMatthias Ringwald                 // first fragment
3583cd529728SMatthias Ringwald                 uint16_t pos = 0;
3584cd529728SMatthias Ringwald                 if (!l2cap_channel->receive_sdu_len){
3585bb98c113SMatthias Ringwald                     uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3586bb98c113SMatthias Ringwald                     if(sdu_len > l2cap_channel->local_mtu) break;   // SDU would be larger than our buffer
3587bb98c113SMatthias Ringwald                     l2cap_channel->receive_sdu_len = sdu_len;
3588cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_pos = 0;
3589cd529728SMatthias Ringwald                     pos  += 2;
3590cd529728SMatthias Ringwald                     size -= 2;
3591cd529728SMatthias Ringwald                 }
3592bb98c113SMatthias Ringwald                 uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
3593bb98c113SMatthias Ringwald                 uint16_t remaining_space = l2cap_channel->local_mtu - l2cap_channel->receive_sdu_pos;
3594bb98c113SMatthias Ringwald                 if (fragment_size > remaining_space) break;         // SDU would cause buffer overrun
35956535961aSMatthias Ringwald                 (void)memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos],
35966535961aSMatthias Ringwald                              &packet[COMPLETE_L2CAP_HEADER + pos],
35976535961aSMatthias Ringwald                              fragment_size);
3598cd529728SMatthias Ringwald                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
3599cd529728SMatthias Ringwald                 // done?
3600895ff4a5SMatthias Ringwald                 log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
3601cd529728SMatthias Ringwald                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
3602cd529728SMatthias Ringwald                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
3603cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = 0;
3604cd529728SMatthias Ringwald                 }
360563f0ac45SMatthias Ringwald             } else {
360663f0ac45SMatthias Ringwald                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
360764e11ca9SMatthias Ringwald             }
360864e11ca9SMatthias Ringwald #endif
36095652b5ffS[email protected]             break;
36105652b5ffS[email protected]     }
3611bb0a72a6SMatthias Ringwald #else
3612bb0a72a6SMatthias Ringwald     UNUSED(handle); // ok: no code
3613bb0a72a6SMatthias Ringwald     UNUSED(packet); // ok: no code
3614bb0a72a6SMatthias Ringwald     UNUSED(size);   // ok: no code
3615bb0a72a6SMatthias Ringwald #endif
3616bb0a72a6SMatthias Ringwald }
3617bb0a72a6SMatthias Ringwald 
3618bb0a72a6SMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
3619bb0a72a6SMatthias Ringwald     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
3620bb0a72a6SMatthias Ringwald     UNUSED(channel);        // ok: there is no channel
3621bb0a72a6SMatthias Ringwald 
3622adcfabadSMatthias Ringwald     // Assert full L2CAP header present
3623adcfabadSMatthias Ringwald     if (size < COMPLETE_L2CAP_HEADER) return;
3624adcfabadSMatthias Ringwald 
3625f16129ceSMatthias Ringwald     // Dispatch to Classic or LE handler (SCO packets are not dispatched to L2CAP)
3626bb0a72a6SMatthias Ringwald     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
3627bb0a72a6SMatthias Ringwald     hci_connection_t *conn = hci_connection_for_handle(handle);
3628bb0a72a6SMatthias Ringwald     if (!conn) return;
3629f16129ceSMatthias Ringwald     if (conn->address_type == BD_ADDR_TYPE_ACL){
3630bb0a72a6SMatthias Ringwald         l2cap_acl_classic_handler(handle, packet, size);
3631bb0a72a6SMatthias Ringwald     } else {
3632bb0a72a6SMatthias Ringwald         l2cap_acl_le_handler(handle, packet, size);
3633bb0a72a6SMatthias Ringwald     }
363400d93d79Smatthias.ringwald 
36351eb2563eS[email protected]     l2cap_run();
36362718e2e7Smatthias.ringwald }
363700d93d79Smatthias.ringwald 
363809e9d05bSMatthias Ringwald // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
363909e9d05bSMatthias Ringwald void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
3640fad84cafSMatthias Ringwald     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
3641fad84cafSMatthias Ringwald     if (!channel) return;
3642fad84cafSMatthias Ringwald     channel->packet_handler = the_packet_handler;
364309e9d05bSMatthias Ringwald }
364409e9d05bSMatthias Ringwald 
364509e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
364615ec09bbSmatthias.ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
364727a923d0Smatthias.ringwald void l2cap_finialize_channel_close(l2cap_channel_t * channel){
3648f62db1e3Smatthias.ringwald     channel->state = L2CAP_STATE_CLOSED;
364966a72640SMatthias Ringwald     l2cap_handle_channel_closed(channel);
3650f62db1e3Smatthias.ringwald     // discard channel
3651665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3652c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
3653c8e4258aSmatthias.ringwald }
365413aa3e4bSMatthias Ringwald #endif
36551e6aba47Smatthias.ringwald 
365613aa3e4bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
36578f2a52f4SMatthias Ringwald static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3658665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
3659665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, services);
3660665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
3661665d90f2SMatthias Ringwald         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
36629d9bbc01Smatthias.ringwald         if ( service->psm == psm){
36639d9bbc01Smatthias.ringwald             return service;
36649d9bbc01Smatthias.ringwald         };
36659d9bbc01Smatthias.ringwald     }
36669d9bbc01Smatthias.ringwald     return NULL;
36679d9bbc01Smatthias.ringwald }
366813aa3e4bSMatthias Ringwald #endif
36699d9bbc01Smatthias.ringwald 
367013aa3e4bSMatthias Ringwald #ifdef ENABLE_CLASSIC
36717192e786SMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
36727192e786SMatthias Ringwald     return l2cap_get_service_internal(&l2cap_services, psm);
36737192e786SMatthias Ringwald }
36747192e786SMatthias Ringwald 
3675be2053a6SMatthias 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){
3676be2053a6SMatthias Ringwald 
3677be2053a6SMatthias Ringwald     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
3678e0abb8e7S[email protected] 
36794bb582b6Smatthias.ringwald     // check for alread registered psm
36809d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
3681277abc2cSmatthias.ringwald     if (service) {
3682be2053a6SMatthias Ringwald         log_error("l2cap_register_service: PSM %u already registered", psm);
3683be2053a6SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
3684277abc2cSmatthias.ringwald     }
36859d9bbc01Smatthias.ringwald 
36864bb582b6Smatthias.ringwald     // alloc structure
3687bb69aaaeS[email protected]     service = btstack_memory_l2cap_service_get();
3688277abc2cSmatthias.ringwald     if (!service) {
3689be2053a6SMatthias Ringwald         log_error("l2cap_register_service: no memory for l2cap_service_t");
3690be2053a6SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
3691277abc2cSmatthias.ringwald     }
36929d9bbc01Smatthias.ringwald 
36939d9bbc01Smatthias.ringwald     // fill in
36949d9bbc01Smatthias.ringwald     service->psm = psm;
36959d9bbc01Smatthias.ringwald     service->mtu = mtu;
369605ae8de3SMatthias Ringwald     service->packet_handler = service_packet_handler;
3697df3354fcS[email protected]     service->required_security_level = security_level;
36989d9bbc01Smatthias.ringwald 
36999d9bbc01Smatthias.ringwald     // add to services list
3700665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
3701c0e866bfSmatthias.ringwald 
3702c0e866bfSmatthias.ringwald     // enable page scan
370315a95bd5SMatthias Ringwald     gap_connectable_control(1);
37045842b6d9Smatthias.ringwald 
3705c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
37069d9bbc01Smatthias.ringwald }
37079d9bbc01Smatthias.ringwald 
37087e8856ebSMatthias Ringwald uint8_t l2cap_unregister_service(uint16_t psm){
3709e0abb8e7S[email protected] 
3710e0abb8e7S[email protected]     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
3711e0abb8e7S[email protected] 
37129d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
37137e8856ebSMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3714665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
3715d3a9df87Smatthias.ringwald     btstack_memory_l2cap_service_free(service);
3716c0e866bfSmatthias.ringwald 
3717c0e866bfSmatthias.ringwald     // disable page scan when no services registered
37187e8856ebSMatthias Ringwald     if (btstack_linked_list_empty(&l2cap_services)) {
371915a95bd5SMatthias Ringwald         gap_connectable_control(0);
37209d9bbc01Smatthias.ringwald     }
3721c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
37227e8856ebSMatthias Ringwald }
372309e9d05bSMatthias Ringwald #endif
37249d9bbc01Smatthias.ringwald 
37257192e786SMatthias Ringwald 
3726cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
372783fd9c76SMatthias Ringwald 
372857be49d6SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
372957be49d6SMatthias Ringwald     if (!channel->waiting_for_can_send_now) return;
373057be49d6SMatthias Ringwald     if (channel->send_sdu_buffer) return;
373157be49d6SMatthias Ringwald     channel->waiting_for_can_send_now = 0;
3732895ff4a5SMatthias Ringwald     log_debug("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
373357be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
373457be49d6SMatthias Ringwald }
373557be49d6SMatthias Ringwald 
373657be49d6SMatthias Ringwald // 1BH2222
373757be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
373857be49d6SMatthias 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",
373957be49d6SMatthias Ringwald              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
374057be49d6SMatthias Ringwald     uint8_t event[19];
374157be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
374257be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
374357be49d6SMatthias Ringwald     event[2] = channel->address_type;
374457be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
374557be49d6SMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
374657be49d6SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
374757be49d6SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
374857be49d6SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
374957be49d6SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_mtu);
375057be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
375157be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
375257be49d6SMatthias Ringwald }
375357be49d6SMatthias Ringwald // 11BH22222
375457be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
375557be49d6SMatthias 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",
375657be49d6SMatthias Ringwald              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
375757be49d6SMatthias Ringwald              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
3758c99bb618SMatthias Ringwald     uint8_t event[23];
375957be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
376057be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
376157be49d6SMatthias Ringwald     event[2] = status;
376257be49d6SMatthias Ringwald     event[3] = channel->address_type;
376357be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[4]);
376457be49d6SMatthias Ringwald     little_endian_store_16(event, 10, channel->con_handle);
3765c1ab6cc1SMatthias Ringwald     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
3766c99bb618SMatthias Ringwald     little_endian_store_16(event, 13, channel->psm);
3767c99bb618SMatthias Ringwald     little_endian_store_16(event, 15, channel->local_cid);
3768c99bb618SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_cid);
3769c99bb618SMatthias Ringwald     little_endian_store_16(event, 19, channel->local_mtu);
3770c99bb618SMatthias Ringwald     little_endian_store_16(event, 21, channel->remote_mtu);
377157be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
377257be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
377357be49d6SMatthias Ringwald }
377487050a0bSMatthias Ringwald // 2
377587050a0bSMatthias Ringwald static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel){
377687050a0bSMatthias Ringwald     log_info("L2CAP_EVENT_LE_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
377787050a0bSMatthias Ringwald     uint8_t event[4];
377887050a0bSMatthias Ringwald     event[0] = L2CAP_EVENT_LE_CHANNEL_CLOSED;
377987050a0bSMatthias Ringwald     event[1] = sizeof(event) - 2;
378087050a0bSMatthias Ringwald     little_endian_store_16(event, 2, channel->local_cid);
378187050a0bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
378287050a0bSMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
378387050a0bSMatthias Ringwald }
378487050a0bSMatthias Ringwald 
37856774d5c9SMatthias Ringwald static void l2cap_le_send_pdu(l2cap_channel_t *channel){
37866774d5c9SMatthias Ringwald     btstack_assert(channel != NULL);
37876774d5c9SMatthias Ringwald     btstack_assert(channel->send_pdu_buffer != NULL);
37886774d5c9SMatthias Ringwald     btstack_assert(channel->credits_outgoing > 0);
37896774d5c9SMatthias Ringwald 
37906774d5c9SMatthias Ringwald     // send part of SDU
37916774d5c9SMatthias Ringwald     hci_reserve_packet_buffer();
37926774d5c9SMatthias Ringwald     uint8_t * acl_buffer = hci_get_outgoing_packet_buffer();
37936774d5c9SMatthias Ringwald     uint8_t * l2cap_payload = acl_buffer + 8;
37946774d5c9SMatthias Ringwald     uint16_t pos = 0;
37956774d5c9SMatthias Ringwald     if (!channel->send_sdu_pos){
37966774d5c9SMatthias Ringwald         // store SDU len
37976774d5c9SMatthias Ringwald         channel->send_sdu_pos += 2;
37986774d5c9SMatthias Ringwald         little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
37996774d5c9SMatthias Ringwald         pos += 2;
38006774d5c9SMatthias Ringwald     }
38016774d5c9SMatthias Ringwald     uint16_t payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
38026774d5c9SMatthias Ringwald     log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
38036535961aSMatthias Ringwald     (void)memcpy(&l2cap_payload[pos],
38046535961aSMatthias Ringwald                  &channel->send_sdu_buffer[channel->send_sdu_pos - 2],
38056535961aSMatthias Ringwald                  payload_size); // -2 for virtual SDU len
38066774d5c9SMatthias Ringwald     pos += payload_size;
38076774d5c9SMatthias Ringwald     channel->send_sdu_pos += payload_size;
38086774d5c9SMatthias Ringwald     l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
38096774d5c9SMatthias Ringwald 
38106774d5c9SMatthias Ringwald     channel->credits_outgoing--;
38116774d5c9SMatthias Ringwald 
38126774d5c9SMatthias Ringwald     hci_send_acl_packet_buffer(8 + pos);
38136774d5c9SMatthias Ringwald 
3814c1ab6cc1SMatthias Ringwald     if (channel->send_sdu_pos >= (channel->send_sdu_len + 2)){
38156774d5c9SMatthias Ringwald         channel->send_sdu_buffer = NULL;
38166774d5c9SMatthias Ringwald         // send done event
38176774d5c9SMatthias Ringwald         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
38186774d5c9SMatthias Ringwald         // inform about can send now
38196774d5c9SMatthias Ringwald         l2cap_le_notify_channel_can_send(channel);
38206774d5c9SMatthias Ringwald     }
38216774d5c9SMatthias Ringwald }
38226774d5c9SMatthias Ringwald 
382357be49d6SMatthias Ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
382457be49d6SMatthias Ringwald void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
382557be49d6SMatthias Ringwald     channel->state = L2CAP_STATE_CLOSED;
382657be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
382757be49d6SMatthias Ringwald     // discard channel
3828421cb104SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3829c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
383057be49d6SMatthias Ringwald }
383157be49d6SMatthias Ringwald 
3832e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
3833e7d0c9aaSMatthias Ringwald     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
38347192e786SMatthias Ringwald }
3835efedfb4cSMatthias Ringwald 
3836da144af5SMatthias Ringwald uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
38377192e786SMatthias Ringwald 
3838da144af5SMatthias Ringwald     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
38397192e786SMatthias Ringwald 
38407192e786SMatthias Ringwald     // check for alread registered psm
38417192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
38427192e786SMatthias Ringwald     if (service) {
3843da144af5SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
38447192e786SMatthias Ringwald     }
38457192e786SMatthias Ringwald 
38467192e786SMatthias Ringwald     // alloc structure
38477192e786SMatthias Ringwald     service = btstack_memory_l2cap_service_get();
38487192e786SMatthias Ringwald     if (!service) {
38497192e786SMatthias Ringwald         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
3850da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
38517192e786SMatthias Ringwald     }
38527192e786SMatthias Ringwald 
38537192e786SMatthias Ringwald     // fill in
38547192e786SMatthias Ringwald     service->psm = psm;
3855da144af5SMatthias Ringwald     service->mtu = 0;
38567192e786SMatthias Ringwald     service->packet_handler = packet_handler;
38577192e786SMatthias Ringwald     service->required_security_level = security_level;
38587192e786SMatthias Ringwald 
38597192e786SMatthias Ringwald     // add to services list
3860665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
38617192e786SMatthias Ringwald 
38627192e786SMatthias Ringwald     // done
38639dd26175SMilanka Ringwald     return ERROR_CODE_SUCCESS;
38647192e786SMatthias Ringwald }
38657192e786SMatthias Ringwald 
3866da144af5SMatthias Ringwald uint8_t l2cap_le_unregister_service(uint16_t psm) {
38677192e786SMatthias Ringwald     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
38687192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
38699367f9b0SMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3870da144af5SMatthias Ringwald 
3871665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
38727192e786SMatthias Ringwald     btstack_memory_l2cap_service_free(service);
3873c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
38747192e786SMatthias Ringwald }
3875da144af5SMatthias Ringwald 
3876da144af5SMatthias Ringwald uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
3877e7d0c9aaSMatthias Ringwald     // get channel
3878421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3879e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3880e7d0c9aaSMatthias Ringwald 
3881e7d0c9aaSMatthias Ringwald     // validate state
3882e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3883e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
3884e7d0c9aaSMatthias Ringwald     }
3885e7d0c9aaSMatthias Ringwald 
3886efedfb4cSMatthias Ringwald     // set state accept connection
388723017473SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
388823017473SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
388923017473SMatthias Ringwald     channel->local_mtu = mtu;
389085aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
389185aeef60SMatthias Ringwald     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
389285aeef60SMatthias Ringwald 
389385aeef60SMatthias Ringwald     // test
389463f0ac45SMatthias Ringwald     // channel->new_credits_incoming = 1;
3895e7d0c9aaSMatthias Ringwald 
3896e7d0c9aaSMatthias Ringwald     // go
3897e7d0c9aaSMatthias Ringwald     l2cap_run();
3898c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
3899da144af5SMatthias Ringwald }
3900da144af5SMatthias Ringwald 
3901da144af5SMatthias Ringwald /**
3902da144af5SMatthias Ringwald  * @brief Deny incoming LE Data Channel connection due to resource constraints
3903da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3904da144af5SMatthias Ringwald  */
3905da144af5SMatthias Ringwald 
3906da144af5SMatthias Ringwald uint8_t l2cap_le_decline_connection(uint16_t local_cid){
3907e7d0c9aaSMatthias Ringwald     // get channel
3908421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3909e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3910e7d0c9aaSMatthias Ringwald 
3911e7d0c9aaSMatthias Ringwald     // validate state
3912e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3913e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
3914e7d0c9aaSMatthias Ringwald     }
3915e7d0c9aaSMatthias Ringwald 
3916efedfb4cSMatthias Ringwald     // set state decline connection
3917e7d0c9aaSMatthias Ringwald     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
3918e7d0c9aaSMatthias Ringwald     channel->reason = 0x04; // no resources available
3919e7d0c9aaSMatthias Ringwald     l2cap_run();
3920c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
3921da144af5SMatthias Ringwald }
3922da144af5SMatthias Ringwald 
39237dafa750SMatthias Ringwald uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
3924da144af5SMatthias Ringwald     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
3925efedfb4cSMatthias Ringwald     uint16_t * out_local_cid) {
3926efedfb4cSMatthias Ringwald 
39277dafa750SMatthias Ringwald     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
3928da144af5SMatthias Ringwald 
39297dafa750SMatthias Ringwald 
39307dafa750SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
39317dafa750SMatthias Ringwald     if (!connection) {
39327dafa750SMatthias Ringwald         log_error("no hci_connection for handle 0x%04x", con_handle);
39337dafa750SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
39347dafa750SMatthias Ringwald     }
39357dafa750SMatthias Ringwald 
39365d18f623SMatthias 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);
3937da144af5SMatthias Ringwald     if (!channel) {
3938da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
3939da144af5SMatthias Ringwald     }
3940e7d0c9aaSMatthias Ringwald     log_info("l2cap_le_create_channel %p", channel);
3941da144af5SMatthias Ringwald 
3942da144af5SMatthias Ringwald     // store local_cid
3943da144af5SMatthias Ringwald     if (out_local_cid){
3944da144af5SMatthias Ringwald        *out_local_cid = channel->local_cid;
3945da144af5SMatthias Ringwald     }
3946da144af5SMatthias Ringwald 
39477dafa750SMatthias Ringwald     // provide buffer
39487dafa750SMatthias Ringwald     channel->con_handle = con_handle;
3949cd529728SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
39507dafa750SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
395185aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
395285aeef60SMatthias Ringwald     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
395385aeef60SMatthias Ringwald 
3954efedfb4cSMatthias Ringwald     // add to connections list
3955421cb104SMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
3956efedfb4cSMatthias Ringwald 
39577dafa750SMatthias Ringwald     // go
395863f0ac45SMatthias Ringwald     l2cap_run();
3959c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
3960da144af5SMatthias Ringwald }
3961da144af5SMatthias Ringwald 
3962da144af5SMatthias Ringwald /**
3963da144af5SMatthias Ringwald  * @brief Provide credtis for LE Data Channel
3964da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3965da144af5SMatthias Ringwald  * @param credits               Number additional credits for peer
3966da144af5SMatthias Ringwald  */
396764e11ca9SMatthias Ringwald uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
396863f0ac45SMatthias Ringwald 
3969421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
397063f0ac45SMatthias Ringwald     if (!channel) {
397163f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
397263f0ac45SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
397363f0ac45SMatthias Ringwald     }
397463f0ac45SMatthias Ringwald 
3975efedfb4cSMatthias Ringwald     // check state
397663f0ac45SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN){
397763f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
397863f0ac45SMatthias Ringwald     }
397963f0ac45SMatthias Ringwald 
398063f0ac45SMatthias Ringwald     // assert incoming credits + credits <= 0xffff
398163f0ac45SMatthias Ringwald     uint32_t total_credits = channel->credits_incoming;
398263f0ac45SMatthias Ringwald     total_credits += channel->new_credits_incoming;
398363f0ac45SMatthias Ringwald     total_credits += credits;
398463f0ac45SMatthias Ringwald     if (total_credits > 0xffff){
398563f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
398663f0ac45SMatthias Ringwald             channel->new_credits_incoming, credits);
398763f0ac45SMatthias Ringwald     }
398863f0ac45SMatthias Ringwald 
3989efedfb4cSMatthias Ringwald     // set credits_granted
399063f0ac45SMatthias Ringwald     channel->new_credits_incoming += credits;
399163f0ac45SMatthias Ringwald 
399263f0ac45SMatthias Ringwald     // go
399363f0ac45SMatthias Ringwald     l2cap_run();
39949dd26175SMilanka Ringwald     return ERROR_CODE_SUCCESS;
3995da144af5SMatthias Ringwald }
3996da144af5SMatthias Ringwald 
3997da144af5SMatthias Ringwald /**
3998da144af5SMatthias Ringwald  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
3999da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
4000da144af5SMatthias Ringwald  */
400164e11ca9SMatthias Ringwald int l2cap_le_can_send_now(uint16_t local_cid){
4002421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
400344276248SMatthias Ringwald     if (!channel) {
400444276248SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
4005da144af5SMatthias Ringwald         return 0;
4006da144af5SMatthias Ringwald     }
4007da144af5SMatthias Ringwald 
400844276248SMatthias Ringwald     // check state
400944276248SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN) return 0;
401044276248SMatthias Ringwald 
401144276248SMatthias Ringwald     // check queue
401244276248SMatthias Ringwald     if (channel->send_sdu_buffer) return 0;
401344276248SMatthias Ringwald 
401444276248SMatthias Ringwald     // fine, go ahead
401544276248SMatthias Ringwald     return 1;
401644276248SMatthias Ringwald }
401744276248SMatthias Ringwald 
4018da144af5SMatthias Ringwald /**
4019da144af5SMatthias Ringwald  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
4020da144af5SMatthias Ringwald  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
4021da144af5SMatthias Ringwald  *       so packet handler should be ready to handle it
4022da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
4023da144af5SMatthias Ringwald  */
402464e11ca9SMatthias Ringwald uint8_t l2cap_le_request_can_send_now_event(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_request_can_send_now_event no channel for cid 0x%02x", local_cid);
4028c8b2b785SMilanka Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
402944276248SMatthias Ringwald     }
403044276248SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
403144276248SMatthias Ringwald     l2cap_le_notify_channel_can_send(channel);
4032c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
4033da144af5SMatthias Ringwald }
4034da144af5SMatthias Ringwald 
4035da144af5SMatthias Ringwald /**
4036da144af5SMatthias Ringwald  * @brief Send data via LE Data Channel
4037da144af5SMatthias Ringwald  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
4038da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
4039da144af5SMatthias Ringwald  * @param data                  data to send
4040da144af5SMatthias Ringwald  * @param size                  data size
4041da144af5SMatthias Ringwald  */
404264e11ca9SMatthias Ringwald uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
404364e11ca9SMatthias Ringwald 
4044421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
404564e11ca9SMatthias Ringwald     if (!channel) {
404664e11ca9SMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4047828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
404864e11ca9SMatthias Ringwald     }
404964e11ca9SMatthias Ringwald 
405064e11ca9SMatthias Ringwald     if (len > channel->remote_mtu){
405164e11ca9SMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
405264e11ca9SMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
405364e11ca9SMatthias Ringwald     }
405464e11ca9SMatthias Ringwald 
40557f107edaSMatthias Ringwald     if (channel->send_sdu_buffer){
405664e11ca9SMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
405764e11ca9SMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
405864e11ca9SMatthias Ringwald     }
405964e11ca9SMatthias Ringwald 
40607f107edaSMatthias Ringwald     channel->send_sdu_buffer = data;
40617f107edaSMatthias Ringwald     channel->send_sdu_len    = len;
40627f107edaSMatthias Ringwald     channel->send_sdu_pos    = 0;
406364e11ca9SMatthias Ringwald 
40646774d5c9SMatthias Ringwald     l2cap_notify_channel_can_send();
4065c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
4066da144af5SMatthias Ringwald }
4067da144af5SMatthias Ringwald 
4068da144af5SMatthias Ringwald /**
4069da144af5SMatthias Ringwald  * @brief Disconnect from LE Data Channel
4070da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
4071da144af5SMatthias Ringwald  */
4072828a7f7aSMatthias Ringwald uint8_t l2cap_le_disconnect(uint16_t local_cid)
4073da144af5SMatthias Ringwald {
4074421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4075828a7f7aSMatthias Ringwald     if (!channel) {
4076828a7f7aSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4077828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4078828a7f7aSMatthias Ringwald     }
4079828a7f7aSMatthias Ringwald 
4080828a7f7aSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4081828a7f7aSMatthias Ringwald     l2cap_run();
4082c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
4083da144af5SMatthias Ringwald }
4084da144af5SMatthias Ringwald 
40857f02f414SMatthias Ringwald #endif
4086