xref: /btstack/src/l2cap.c (revision c1ab6cc1beb14b16b46e74a3723644016d8c3cc7)
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);
3803b81f0d3SMatthias Ringwald     memcpy(&acl_buffer[8+2], &channel->tx_packets_data[index * channel->local_mps], tx_state->len);
3811e1a46bbSMatthias Ringwald     // (re-)start retransmission timer on
3821e1a46bbSMatthias Ringwald     l2cap_ertm_start_retransmission_timer(channel);
383474f5c3fSMatthias Ringwald     // send
384474f5c3fSMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2 + tx_state->len);
385474f5c3fSMatthias Ringwald }
386474f5c3fSMatthias Ringwald 
387474f5c3fSMatthias 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){
388474f5c3fSMatthias Ringwald     // get next index for storing packets
389474f5c3fSMatthias Ringwald     int index = channel->tx_write_index;
390474f5c3fSMatthias Ringwald 
391474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
392474f5c3fSMatthias Ringwald     tx_state->tx_seq = channel->next_tx_seq;
393474f5c3fSMatthias Ringwald     tx_state->sar = sar;
394474f5c3fSMatthias Ringwald     tx_state->retry_count = 0;
395474f5c3fSMatthias Ringwald 
3963b81f0d3SMatthias Ringwald     uint8_t * tx_packet = &channel->tx_packets_data[index * channel->local_mps];
397b90eac91SMatthias 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);
398474f5c3fSMatthias Ringwald     int pos = 0;
399474f5c3fSMatthias Ringwald     if (sar == L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU){
400474f5c3fSMatthias Ringwald         little_endian_store_16(tx_packet, 0, sdu_length);
401474f5c3fSMatthias Ringwald         pos += 2;
402474f5c3fSMatthias Ringwald     }
403474f5c3fSMatthias Ringwald     memcpy(&tx_packet[pos], data, len);
404b90eac91SMatthias Ringwald     tx_state->len = pos + len;
405474f5c3fSMatthias Ringwald 
406474f5c3fSMatthias Ringwald     // update
407a8409e80SMatthias Ringwald     channel->num_stored_tx_frames++;
408474f5c3fSMatthias Ringwald     channel->next_tx_seq = l2cap_next_ertm_seq_nr(channel->next_tx_seq);
409474f5c3fSMatthias Ringwald     l2cap_ertm_next_tx_write_index(channel);
41094301352SMatthias Ringwald 
411a8409e80SMatthias 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);
41294301352SMatthias Ringwald 
413474f5c3fSMatthias Ringwald }
414474f5c3fSMatthias Ringwald 
415474f5c3fSMatthias Ringwald static int l2cap_ertm_send(l2cap_channel_t * channel, uint8_t * data, uint16_t len){
416474f5c3fSMatthias Ringwald     if (len > channel->remote_mtu){
417a8409e80SMatthias Ringwald         log_error("l2cap_ertm_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
418474f5c3fSMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
419474f5c3fSMatthias Ringwald     }
420474f5c3fSMatthias Ringwald 
421a8409e80SMatthias Ringwald     if (!l2cap_ertm_can_store_packet_now(channel)){
422a8409e80SMatthias Ringwald         log_error("l2cap_ertm_send cid 0x%02x, fragment store full", channel->local_cid);
423a8409e80SMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
424a8409e80SMatthias Ringwald     }
425a8409e80SMatthias Ringwald 
426474f5c3fSMatthias Ringwald     // check if it needs to get fragmented
427b90eac91SMatthias Ringwald     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
428b90eac91SMatthias Ringwald     if (len > effective_mps){
429474f5c3fSMatthias Ringwald         // fragmentation needed.
430474f5c3fSMatthias Ringwald         l2cap_segmentation_and_reassembly_t sar =  L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU;
431474f5c3fSMatthias Ringwald         int chunk_len;
432474f5c3fSMatthias Ringwald         while (len){
433474f5c3fSMatthias Ringwald             switch (sar){
434474f5c3fSMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
435b90eac91SMatthias Ringwald                     chunk_len = effective_mps - 2;    // sdu_length
436474f5c3fSMatthias Ringwald                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
437474f5c3fSMatthias Ringwald                     len -= chunk_len;
438474f5c3fSMatthias Ringwald                     sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU;
439474f5c3fSMatthias Ringwald                     break;
440474f5c3fSMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
441b90eac91SMatthias Ringwald                     chunk_len = effective_mps;
442474f5c3fSMatthias Ringwald                     if (chunk_len >= len){
443474f5c3fSMatthias Ringwald                         sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU;
444474f5c3fSMatthias Ringwald                         chunk_len = len;
445474f5c3fSMatthias Ringwald                     }
446474f5c3fSMatthias Ringwald                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
447474f5c3fSMatthias Ringwald                     len -= chunk_len;
448474f5c3fSMatthias Ringwald                     break;
449474f5c3fSMatthias Ringwald                 default:
450474f5c3fSMatthias Ringwald                     break;
451474f5c3fSMatthias Ringwald             }
452474f5c3fSMatthias Ringwald         }
453474f5c3fSMatthias Ringwald 
454474f5c3fSMatthias Ringwald     } else {
455474f5c3fSMatthias Ringwald         l2cap_ertm_store_fragment(channel, L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU, 0, data, len);
456474f5c3fSMatthias Ringwald     }
457474f5c3fSMatthias Ringwald 
458474f5c3fSMatthias Ringwald     // try to send
459d89ab698SMatthias Ringwald     l2cap_notify_channel_can_send();
460474f5c3fSMatthias Ringwald     return 0;
461474f5c3fSMatthias Ringwald }
462474f5c3fSMatthias Ringwald 
4637cbe539fSMatthias Ringwald static uint16_t l2cap_setup_options_ertm_request(l2cap_channel_t * channel, uint8_t * config_options){
464fcb125edSMatthias Ringwald     int pos = 0;
465fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
466fcb125edSMatthias Ringwald     config_options[pos++] = 9;      // length
467fcb125edSMatthias Ringwald     config_options[pos++] = (uint8_t) channel->mode;
468fcb125edSMatthias Ringwald     config_options[pos++] = channel->num_rx_buffers;    // == TxWindows size
469fcb125edSMatthias Ringwald     config_options[pos++] = channel->local_max_transmit;
470fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
471fcb125edSMatthias Ringwald     pos += 2;
472fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
473fcb125edSMatthias Ringwald     pos += 2;
474fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_mps);
475fcb125edSMatthias Ringwald     pos += 2;
4766574158aSMatthias Ringwald     //
477fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT;
478fcb125edSMatthias Ringwald     config_options[pos++] = 2;     // length
479fcb125edSMatthias Ringwald     little_endian_store_16(config_options, pos, channel->local_mtu);
480fcb125edSMatthias Ringwald     pos += 2;
481c425ea4aSMatthias Ringwald 
482c425ea4aSMatthias Ringwald     // Issue: iOS (e.g. 10.2) uses "No FCS" as default while Core 5.0 specifies "FCS" as default
483c425ea4aSMatthias Ringwald     // Workaround: try to actively negotiate FCS option
484fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
485fcb125edSMatthias Ringwald     config_options[pos++] = 1;     // length
486fcb125edSMatthias Ringwald     config_options[pos++] = channel->fcs_option;
487f2c70799Sandryblack     return pos; // 11+4+3=18
488474f5c3fSMatthias Ringwald }
489474f5c3fSMatthias Ringwald 
4907cbe539fSMatthias Ringwald static uint16_t l2cap_setup_options_ertm_response(l2cap_channel_t * channel, uint8_t * config_options){
491fcb125edSMatthias Ringwald     int pos = 0;
492fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
493fcb125edSMatthias Ringwald     config_options[pos++] = 9;      // length
494fcb125edSMatthias Ringwald     config_options[pos++] = (uint8_t) channel->mode;
4957cbe539fSMatthias Ringwald     // less or equal to remote tx window size
496fcb125edSMatthias Ringwald     config_options[pos++] = btstack_min(channel->num_tx_buffers, channel->remote_tx_window_size);
4977cbe539fSMatthias Ringwald     // max transmit in response shall be ignored -> use sender values
498fcb125edSMatthias Ringwald     config_options[pos++] = channel->remote_max_transmit;
4997cbe539fSMatthias Ringwald     // A value for the Retransmission time-out shall be sent in a positive Configuration Response
5007cbe539fSMatthias Ringwald     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
501fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
502fcb125edSMatthias Ringwald     pos += 2;
5037cbe539fSMatthias Ringwald     // A value for the Monitor time-out shall be sent in a positive Configuration Response
5047cbe539fSMatthias Ringwald     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
505fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
506fcb125edSMatthias Ringwald     pos += 2;
5077cbe539fSMatthias Ringwald     // less or equal to remote mps
508b90eac91SMatthias Ringwald     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
509b90eac91SMatthias Ringwald     little_endian_store_16( config_options, pos, effective_mps);
510fcb125edSMatthias Ringwald     pos += 2;
5116574158aSMatthias Ringwald     //
512fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
513fcb125edSMatthias Ringwald     config_options[pos++] = 2;     // length
514fcb125edSMatthias Ringwald     little_endian_store_16(config_options, pos, channel->remote_mtu);
515fcb125edSMatthias Ringwald     pos += 2;
516fcb125edSMatthias Ringwald #if 0
517d64e9771SMatthias Ringwald     //
518fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
519fcb125edSMatthias Ringwald     config_options[pos++] = 1;     // length
520fcb125edSMatthias Ringwald     config_options[pos++] = channel->fcs_option;
521fcb125edSMatthias Ringwald #endif
522f2c70799Sandryblack     return pos; // 11+4=15
5237cbe539fSMatthias Ringwald }
5247cbe539fSMatthias Ringwald 
525474f5c3fSMatthias Ringwald static int l2cap_ertm_send_supervisor_frame(l2cap_channel_t * channel, uint16_t control){
526474f5c3fSMatthias Ringwald     hci_reserve_packet_buffer();
527474f5c3fSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
528474f5c3fSMatthias Ringwald     log_info("S-Frame: control 0x%04x", control);
529474f5c3fSMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
530474f5c3fSMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2);
531474f5c3fSMatthias Ringwald }
532474f5c3fSMatthias Ringwald 
5335774a392SMatthias Ringwald static uint8_t l2cap_ertm_validate_local_config(l2cap_ertm_config_t * ertm_config){
534474f5c3fSMatthias Ringwald 
535474f5c3fSMatthias Ringwald     uint8_t result = ERROR_CODE_SUCCESS;
5369c0e62d3SMatthias Ringwald     if (ertm_config->max_transmit < 1){
537474f5c3fSMatthias Ringwald         log_error("max_transmit must be >= 1");
538474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
539474f5c3fSMatthias Ringwald     }
5409c0e62d3SMatthias Ringwald     if (ertm_config->retransmission_timeout_ms < 2000){
541474f5c3fSMatthias Ringwald         log_error("retransmission_timeout_ms must be >= 2000 ms");
542474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
543474f5c3fSMatthias Ringwald     }
5449c0e62d3SMatthias Ringwald     if (ertm_config->monitor_timeout_ms < 12000){
545474f5c3fSMatthias Ringwald         log_error("monitor_timeout_ms must be >= 12000 ms");
546474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
547474f5c3fSMatthias Ringwald     }
5489c0e62d3SMatthias Ringwald     if (ertm_config->local_mtu < 48){
549474f5c3fSMatthias Ringwald         log_error("local_mtu must be >= 48");
550474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
551474f5c3fSMatthias Ringwald     }
5529c0e62d3SMatthias Ringwald     if (ertm_config->num_rx_buffers < 1){
553474f5c3fSMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
554474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
555474f5c3fSMatthias Ringwald     }
5569c0e62d3SMatthias Ringwald     if (ertm_config->num_tx_buffers < 1){
557474f5c3fSMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
558474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
559474f5c3fSMatthias Ringwald     }
560474f5c3fSMatthias Ringwald     return result;
561474f5c3fSMatthias Ringwald }
562474f5c3fSMatthias Ringwald 
5639c0e62d3SMatthias Ringwald static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
564474f5c3fSMatthias Ringwald 
565474f5c3fSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
5669c0e62d3SMatthias Ringwald     channel->ertm_mandatory = ertm_config->ertm_mandatory;
5679c0e62d3SMatthias Ringwald     channel->local_max_transmit = ertm_config->max_transmit;
5689c0e62d3SMatthias Ringwald     channel->local_retransmission_timeout_ms = ertm_config->retransmission_timeout_ms;
5699c0e62d3SMatthias Ringwald     channel->local_monitor_timeout_ms = ertm_config->monitor_timeout_ms;
5709c0e62d3SMatthias Ringwald     channel->local_mtu = ertm_config->local_mtu;
5719c0e62d3SMatthias Ringwald     channel->num_rx_buffers = ertm_config->num_rx_buffers;
5729c0e62d3SMatthias Ringwald     channel->num_tx_buffers = ertm_config->num_tx_buffers;
573474f5c3fSMatthias Ringwald 
574c342091bSMatthias Ringwald     // align buffer to 16-byte boundary to assert l2cap_ertm_rx_packet_state_t is aligned
575474f5c3fSMatthias Ringwald     int bytes_till_alignment = 16 - (((uintptr_t) buffer) & 0x0f);
576474f5c3fSMatthias Ringwald     buffer += bytes_till_alignment;
577474f5c3fSMatthias Ringwald     size   -= bytes_till_alignment;
578474f5c3fSMatthias Ringwald 
579c342091bSMatthias Ringwald     // setup state buffers - use void cast to avoid -Wcast-align warning
580474f5c3fSMatthias Ringwald     uint32_t pos = 0;
581c342091bSMatthias Ringwald     channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) (void *) &buffer[pos];
5829c0e62d3SMatthias Ringwald     pos += ertm_config->num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
583c342091bSMatthias Ringwald     channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) (void *) &buffer[pos];
5849c0e62d3SMatthias Ringwald     pos += ertm_config->num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
585474f5c3fSMatthias Ringwald 
586474f5c3fSMatthias Ringwald     // setup reassembly buffer
587474f5c3fSMatthias Ringwald     channel->reassembly_buffer = &buffer[pos];
5889c0e62d3SMatthias Ringwald     pos += ertm_config->local_mtu;
589474f5c3fSMatthias Ringwald 
590474f5c3fSMatthias Ringwald     // divide rest of data equally
5919c0e62d3SMatthias Ringwald     channel->local_mps = (size - pos) / (ertm_config->num_rx_buffers + ertm_config->num_tx_buffers);
5920d3ee2efSMatthias Ringwald     log_info("Local MPS: %u", channel->local_mps);
593474f5c3fSMatthias Ringwald     channel->rx_packets_data = &buffer[pos];
5940d3ee2efSMatthias Ringwald     pos += ertm_config->num_rx_buffers * channel->local_mps;
595474f5c3fSMatthias Ringwald     channel->tx_packets_data = &buffer[pos];
5966574158aSMatthias Ringwald 
597c425ea4aSMatthias Ringwald     channel->fcs_option = ertm_config->fcs_option;
598474f5c3fSMatthias Ringwald }
599474f5c3fSMatthias Ringwald 
600474f5c3fSMatthias Ringwald uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
6019c0e62d3SMatthias Ringwald     l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
602474f5c3fSMatthias Ringwald 
6039c0e62d3SMatthias 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);
604474f5c3fSMatthias Ringwald 
605474f5c3fSMatthias Ringwald     // validate local config
6065774a392SMatthias Ringwald     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
607474f5c3fSMatthias Ringwald     if (result) return result;
608474f5c3fSMatthias Ringwald 
609f16129ceSMatthias 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);
610474f5c3fSMatthias Ringwald     if (!channel) {
611474f5c3fSMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
612474f5c3fSMatthias Ringwald     }
613474f5c3fSMatthias Ringwald 
614474f5c3fSMatthias Ringwald     // configure ERTM
6159c0e62d3SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
616474f5c3fSMatthias Ringwald 
617474f5c3fSMatthias Ringwald     // add to connections list
618474f5c3fSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
619474f5c3fSMatthias Ringwald 
620474f5c3fSMatthias Ringwald     // store local_cid
621474f5c3fSMatthias Ringwald     if (out_local_cid){
622474f5c3fSMatthias Ringwald        *out_local_cid = channel->local_cid;
623474f5c3fSMatthias Ringwald     }
624474f5c3fSMatthias Ringwald 
625474f5c3fSMatthias Ringwald     // check if hci connection is already usable
626f16129ceSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
627474f5c3fSMatthias Ringwald     if (conn){
628474f5c3fSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
629474f5c3fSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
630474f5c3fSMatthias Ringwald         // check if remote supported fearures are already received
631474f5c3fSMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
632474f5c3fSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
633474f5c3fSMatthias Ringwald         }
634474f5c3fSMatthias Ringwald     }
635474f5c3fSMatthias Ringwald 
636474f5c3fSMatthias Ringwald     l2cap_run();
637474f5c3fSMatthias Ringwald 
638474f5c3fSMatthias Ringwald     return 0;
639474f5c3fSMatthias Ringwald }
640474f5c3fSMatthias Ringwald 
641474f5c3fSMatthias Ringwald static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel){
642474f5c3fSMatthias Ringwald     if (l2cap_ertm_can_store_packet_now(channel)){
643474f5c3fSMatthias Ringwald         channel->waiting_for_can_send_now = 0;
644474f5c3fSMatthias Ringwald         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
645474f5c3fSMatthias Ringwald     }
646474f5c3fSMatthias Ringwald }
647474f5c3fSMatthias Ringwald 
6489c0e62d3SMatthias Ringwald uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
649474f5c3fSMatthias Ringwald 
650474f5c3fSMatthias Ringwald     log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
651f68b21d7SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
652474f5c3fSMatthias Ringwald     if (!channel) {
653474f5c3fSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
654474f5c3fSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
655474f5c3fSMatthias Ringwald     }
656474f5c3fSMatthias Ringwald 
657474f5c3fSMatthias Ringwald     // validate local config
6585774a392SMatthias Ringwald     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
659474f5c3fSMatthias Ringwald     if (result) return result;
660474f5c3fSMatthias Ringwald 
661474f5c3fSMatthias Ringwald     // configure L2CAP ERTM
6629c0e62d3SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
663474f5c3fSMatthias Ringwald 
664836ae835SMatthias Ringwald     // default: continue
665474f5c3fSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
666474f5c3fSMatthias Ringwald 
6678b7155e0SMatthias Ringwald     // verify remote ERTM support
668836ae835SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
669836ae835SMatthias Ringwald     if (connection == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
670836ae835SMatthias Ringwald 
671836ae835SMatthias Ringwald     if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
6728b7155e0SMatthias Ringwald         // ERTM not possible, select basic mode and release buffer
6738b7155e0SMatthias Ringwald         channel->mode = L2CAP_CHANNEL_MODE_BASIC;
6748b7155e0SMatthias Ringwald         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
675836ae835SMatthias Ringwald 
6768b7155e0SMatthias Ringwald         // bail if ERTM is mandatory
677836ae835SMatthias Ringwald         if (channel->ertm_mandatory){
678836ae835SMatthias Ringwald             // We chose 'no resources available' for "ERTM mandatory but you don't even know ERTM exists"
6798b7155e0SMatthias Ringwald             log_info("ERTM mandatory -> reject connection");
680836ae835SMatthias Ringwald             channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
681836ae835SMatthias Ringwald             channel->reason = 0x04; // no resources available
6828b7155e0SMatthias Ringwald         }  else {
6838b7155e0SMatthias Ringwald             log_info("ERTM not supported by remote -> use Basic mode");
684836ae835SMatthias Ringwald         }
685836ae835SMatthias Ringwald     }
686836ae835SMatthias Ringwald 
687474f5c3fSMatthias Ringwald     // process
688474f5c3fSMatthias Ringwald     l2cap_run();
689474f5c3fSMatthias Ringwald 
690474f5c3fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
691474f5c3fSMatthias Ringwald }
692474f5c3fSMatthias Ringwald 
693474f5c3fSMatthias Ringwald uint8_t l2cap_ertm_set_busy(uint16_t local_cid){
694f68b21d7SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
695474f5c3fSMatthias Ringwald     if (!channel) {
696474f5c3fSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
697474f5c3fSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
698474f5c3fSMatthias Ringwald     }
699474f5c3fSMatthias Ringwald     if (!channel->local_busy){
700474f5c3fSMatthias Ringwald         channel->local_busy = 1;
701474f5c3fSMatthias Ringwald         channel->send_supervisor_frame_receiver_not_ready = 1;
702474f5c3fSMatthias Ringwald         l2cap_run();
703474f5c3fSMatthias Ringwald     }
704474f5c3fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
705474f5c3fSMatthias Ringwald }
706474f5c3fSMatthias Ringwald 
707474f5c3fSMatthias Ringwald uint8_t l2cap_ertm_set_ready(uint16_t local_cid){
708f68b21d7SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
709474f5c3fSMatthias Ringwald     if (!channel) {
710474f5c3fSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
711474f5c3fSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
712474f5c3fSMatthias Ringwald     }
713474f5c3fSMatthias Ringwald     if (channel->local_busy){
714474f5c3fSMatthias Ringwald         channel->local_busy = 0;
715474f5c3fSMatthias Ringwald         channel->send_supervisor_frame_receiver_ready_poll = 1;
716474f5c3fSMatthias Ringwald         l2cap_run();
717474f5c3fSMatthias Ringwald     }
718474f5c3fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
719474f5c3fSMatthias Ringwald }
720474f5c3fSMatthias Ringwald 
7211e1a46bbSMatthias Ringwald // Process-ReqSeq
7221e1a46bbSMatthias Ringwald static void l2cap_ertm_process_req_seq(l2cap_channel_t * l2cap_channel, uint8_t req_seq){
723474f5c3fSMatthias Ringwald     int num_buffers_acked = 0;
724474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
72594301352SMatthias 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);
726474f5c3fSMatthias Ringwald     while (1){
7271e1a46bbSMatthias Ringwald 
72894301352SMatthias Ringwald         // no unack packets left
72994301352SMatthias Ringwald         if (l2cap_channel->unacked_frames == 0) {
7301e1a46bbSMatthias Ringwald             // stop retransmission timer
7311e1a46bbSMatthias Ringwald             l2cap_ertm_stop_retransmission_timer(l2cap_channel);
7321e1a46bbSMatthias Ringwald             break;
7331e1a46bbSMatthias Ringwald         }
7341e1a46bbSMatthias Ringwald 
735474f5c3fSMatthias Ringwald         tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
736474f5c3fSMatthias Ringwald         // calc delta
737474f5c3fSMatthias Ringwald         int delta = (req_seq - tx_state->tx_seq) & 0x03f;
738474f5c3fSMatthias Ringwald         if (delta == 0) break;  // all packets acknowledged
739474f5c3fSMatthias Ringwald         if (delta > l2cap_channel->remote_tx_window_size) break;
740474f5c3fSMatthias Ringwald 
741474f5c3fSMatthias Ringwald         num_buffers_acked++;
742a8409e80SMatthias Ringwald         l2cap_channel->num_stored_tx_frames--;
74394301352SMatthias Ringwald         l2cap_channel->unacked_frames--;
744474f5c3fSMatthias Ringwald         log_info("RR seq %u => packet with tx_seq %u done", req_seq, tx_state->tx_seq);
745474f5c3fSMatthias Ringwald 
746474f5c3fSMatthias Ringwald         l2cap_channel->tx_read_index++;
747474f5c3fSMatthias Ringwald         if (l2cap_channel->tx_read_index >= l2cap_channel->num_rx_buffers){
748474f5c3fSMatthias Ringwald             l2cap_channel->tx_read_index = 0;
749474f5c3fSMatthias Ringwald         }
750474f5c3fSMatthias Ringwald     }
751474f5c3fSMatthias Ringwald     if (num_buffers_acked){
752a8409e80SMatthias Ringwald         log_info("num_buffers_acked %u", num_buffers_acked);
753474f5c3fSMatthias Ringwald     l2cap_ertm_notify_channel_can_send(l2cap_channel);
754474f5c3fSMatthias Ringwald }
755474f5c3fSMatthias Ringwald }
756474f5c3fSMatthias Ringwald 
757474f5c3fSMatthias Ringwald static l2cap_ertm_tx_packet_state_t * l2cap_ertm_get_tx_state(l2cap_channel_t * l2cap_channel, uint8_t tx_seq){
758474f5c3fSMatthias Ringwald     int i;
759474f5c3fSMatthias Ringwald     for (i=0;i<l2cap_channel->num_tx_buffers;i++){
760474f5c3fSMatthias Ringwald         l2cap_ertm_tx_packet_state_t * tx_state = &l2cap_channel->tx_packets_state[i];
761474f5c3fSMatthias Ringwald         if (tx_state->tx_seq == tx_seq) return tx_state;
762474f5c3fSMatthias Ringwald     }
763474f5c3fSMatthias Ringwald     return NULL;
764474f5c3fSMatthias Ringwald }
765474f5c3fSMatthias Ringwald 
766474f5c3fSMatthias Ringwald // @param delta number of frames in the future, >= 1
767122c2b05SMatthias Ringwald // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
7683d244bfaSMatthias 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){
769474f5c3fSMatthias Ringwald     log_info("Store SDU with delta %u", delta);
770474f5c3fSMatthias Ringwald     // get rx state for packet to store
771474f5c3fSMatthias Ringwald     int index = l2cap_channel->rx_store_index + delta - 1;
772474f5c3fSMatthias Ringwald     if (index > l2cap_channel->num_rx_buffers){
773474f5c3fSMatthias Ringwald         index -= l2cap_channel->num_rx_buffers;
774474f5c3fSMatthias Ringwald     }
775474f5c3fSMatthias Ringwald     log_info("Index of packet to store %u", index);
776474f5c3fSMatthias Ringwald     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
777474f5c3fSMatthias Ringwald     // check if buffer is free
778474f5c3fSMatthias Ringwald     if (rx_state->valid){
779474f5c3fSMatthias Ringwald         log_error("Packet buffer already used");
780474f5c3fSMatthias Ringwald         return;
781474f5c3fSMatthias Ringwald     }
782474f5c3fSMatthias Ringwald     rx_state->valid = 1;
783474f5c3fSMatthias Ringwald     rx_state->sar = sar;
784474f5c3fSMatthias Ringwald     rx_state->len = size;
785474f5c3fSMatthias Ringwald     uint8_t * rx_buffer = &l2cap_channel->rx_packets_data[index];
786474f5c3fSMatthias Ringwald     memcpy(rx_buffer, payload, size);
787474f5c3fSMatthias Ringwald }
788474f5c3fSMatthias Ringwald 
789122c2b05SMatthias Ringwald // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
7903d244bfaSMatthias 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){
791122c2b05SMatthias Ringwald     uint16_t reassembly_sdu_length;
792474f5c3fSMatthias Ringwald     switch (sar){
793474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
794122c2b05SMatthias Ringwald             // assert total packet size <= our mtu
795122c2b05SMatthias Ringwald             if (size > l2cap_channel->local_mtu) break;
796474f5c3fSMatthias Ringwald             // packet complete -> disapatch
7973d244bfaSMatthias Ringwald             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, (uint8_t*) payload, size);
798474f5c3fSMatthias Ringwald             break;
799474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
800122c2b05SMatthias Ringwald             // read SDU len
801122c2b05SMatthias Ringwald             reassembly_sdu_length = little_endian_read_16(payload, 0);
802474f5c3fSMatthias Ringwald             payload += 2;
803474f5c3fSMatthias Ringwald             size    -= 2;
804122c2b05SMatthias Ringwald             // assert reassembled size <= our mtu
805122c2b05SMatthias Ringwald             if (reassembly_sdu_length > l2cap_channel->local_mtu) break;
806122c2b05SMatthias Ringwald             // store start segment
807122c2b05SMatthias Ringwald             l2cap_channel->reassembly_sdu_length = reassembly_sdu_length;
808474f5c3fSMatthias Ringwald             memcpy(&l2cap_channel->reassembly_buffer[0], payload, size);
809474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos = size;
810474f5c3fSMatthias Ringwald             break;
811474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
812122c2b05SMatthias Ringwald             // assert size of reassembled data <= our mtu
813122c2b05SMatthias Ringwald             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
814122c2b05SMatthias Ringwald             // store continuation segment
815474f5c3fSMatthias Ringwald             memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos], payload, size);
816474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos += size;
817474f5c3fSMatthias Ringwald             break;
818474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
819122c2b05SMatthias Ringwald             // assert size of reassembled data <= our mtu
820122c2b05SMatthias Ringwald             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
821122c2b05SMatthias Ringwald             // store continuation segment
822474f5c3fSMatthias Ringwald             memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos], payload, size);
823474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos += size;
824122c2b05SMatthias Ringwald             // assert size of reassembled data matches announced sdu length
825122c2b05SMatthias Ringwald             if (l2cap_channel->reassembly_pos != l2cap_channel->reassembly_sdu_length) break;
826474f5c3fSMatthias Ringwald             // packet complete -> disapatch
827474f5c3fSMatthias Ringwald             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->reassembly_buffer, l2cap_channel->reassembly_pos);
828474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos = 0;
829474f5c3fSMatthias Ringwald             break;
830474f5c3fSMatthias Ringwald     }
831474f5c3fSMatthias Ringwald }
832474f5c3fSMatthias Ringwald 
833d89ab698SMatthias Ringwald static void l2cap_ertm_channel_send_information_frame(l2cap_channel_t * channel){
834d89ab698SMatthias Ringwald     channel->unacked_frames++;
835d89ab698SMatthias Ringwald     int index = channel->tx_send_index;
836d89ab698SMatthias Ringwald     channel->tx_send_index++;
837d89ab698SMatthias Ringwald     if (channel->tx_send_index >= channel->num_tx_buffers){
838d89ab698SMatthias Ringwald         channel->tx_send_index = 0;
839d89ab698SMatthias Ringwald     }
840d89ab698SMatthias Ringwald     l2cap_ertm_send_information_frame(channel, index, 0);   // final = 0
841d89ab698SMatthias Ringwald }
842d89ab698SMatthias Ringwald 
84385ddcd84SMatthias Ringwald #endif
84485ddcd84SMatthias Ringwald 
8456a5ffed8SMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
8466ddef68dSMilanka Ringwald static uint16_t l2cap_next_local_cid(void){
8476268fbfeSMilanka Ringwald     do {
8486268fbfeSMilanka Ringwald         if (local_source_cid == 0xffff) {
8496268fbfeSMilanka Ringwald             local_source_cid = 0x40;
8506268fbfeSMilanka Ringwald         } else {
8516268fbfeSMilanka Ringwald             local_source_cid++;
8526268fbfeSMilanka Ringwald         }
8536268fbfeSMilanka Ringwald     } while (l2cap_get_channel_for_local_cid(local_source_cid) != NULL);
8546268fbfeSMilanka Ringwald     return local_source_cid;
8556ddef68dSMilanka Ringwald }
8566a5ffed8SMatthias Ringwald #endif
8576ddef68dSMilanka Ringwald 
8586ddef68dSMilanka Ringwald static uint8_t l2cap_next_sig_id(void){
8596ddef68dSMilanka Ringwald     if (sig_seq_nr == 0xff) {
8606ddef68dSMilanka Ringwald         sig_seq_nr = 1;
8616ddef68dSMilanka Ringwald     } else {
8626ddef68dSMilanka Ringwald         sig_seq_nr++;
8636ddef68dSMilanka Ringwald     }
8646ddef68dSMilanka Ringwald     return sig_seq_nr;
8656ddef68dSMilanka Ringwald }
8666ddef68dSMilanka Ringwald 
86771de195eSMatthias Ringwald void l2cap_init(void){
8682b83fb7dSmatthias.ringwald     signaling_responses_pending = 0;
869808a48abSmatthias.ringwald 
870f5454fc6Smatthias.ringwald     l2cap_channels = NULL;
871fad84cafSMatthias Ringwald 
872fad84cafSMatthias Ringwald #ifdef ENABLE_CLASSIC
873f5454fc6Smatthias.ringwald     l2cap_services = NULL;
87409e9d05bSMatthias Ringwald     require_security_level2_for_outgoing_sdp = 0;
875fad84cafSMatthias Ringwald 
876fad84cafSMatthias Ringwald     // Setup Connectionless Channel
877fad84cafSMatthias Ringwald     l2cap_fixed_channel_connectionless.local_cid     = L2CAP_CID_CONNECTIONLESS_CHANNEL;
8787740e150SMatthias Ringwald     l2cap_fixed_channel_connectionless.channel_type  = L2CAP_CHANNEL_TYPE_CONNECTIONLESS;
879fad84cafSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_connectionless);
88009e9d05bSMatthias Ringwald #endif
881a3dc965aSMatthias Ringwald 
882a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
8837192e786SMatthias Ringwald     l2cap_le_services = NULL;
884a3dc965aSMatthias Ringwald #endif
885f5454fc6Smatthias.ringwald 
886d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
88733c40538SMatthias Ringwald     l2cap_event_packet_handler = NULL;
88825818320SMatthias Ringwald     l2cap_le_custom_max_mtu = 0;
889fad84cafSMatthias Ringwald 
890fad84cafSMatthias Ringwald     // Setup fixed ATT Channel
891fad84cafSMatthias Ringwald     l2cap_fixed_channel_att.local_cid    = L2CAP_CID_ATTRIBUTE_PROTOCOL;
8927740e150SMatthias Ringwald     l2cap_fixed_channel_att.channel_type = L2CAP_CHANNEL_TYPE_LE_FIXED;
893fad84cafSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_att);
894fad84cafSMatthias Ringwald 
895fad84cafSMatthias Ringwald     // Setup fixed SM Channel
896fad84cafSMatthias Ringwald     l2cap_fixed_channel_sm.local_cid     = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
8977740e150SMatthias Ringwald     l2cap_fixed_channel_sm.channel_type  = L2CAP_CHANNEL_TYPE_LE_FIXED;
898fad84cafSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_sm);
899d6ed9f9cSMatthias Ringwald #endif
900f5454fc6Smatthias.ringwald 
901fcadd0caSmatthias.ringwald     //
9022718e2e7Smatthias.ringwald     // register callback with HCI
903fcadd0caSmatthias.ringwald     //
904d9a7306aSMatthias Ringwald     hci_event_callback_registration.callback = &l2cap_hci_event_handler;
905fb37a842SMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
906fb37a842SMatthias Ringwald 
907d9a7306aSMatthias Ringwald     hci_register_acl_packet_handler(&l2cap_acl_handler);
908fb37a842SMatthias Ringwald 
909be005ed6SMatthias Ringwald #ifdef ENABLE_CLASSIC
91015a95bd5SMatthias Ringwald     gap_connectable_control(0); // no services yet
911be005ed6SMatthias Ringwald #endif
912fcadd0caSmatthias.ringwald }
913fcadd0caSmatthias.ringwald 
914ffbf8201SMatthias Ringwald void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
915d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
91633c40538SMatthias Ringwald     l2cap_event_packet_handler = handler;
917d6ed9f9cSMatthias Ringwald #else
9185774a392SMatthias Ringwald     UNUSED(handler);    // ok: no code
919d6ed9f9cSMatthias Ringwald #endif
9201e6aba47Smatthias.ringwald }
9211e6aba47Smatthias.ringwald 
92209e9d05bSMatthias Ringwald void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
923fad84cafSMatthias Ringwald     UNUSED(con_handle);  // ok: there is no con handle
9249ec2630cSMatthias Ringwald 
925f68b21d7SMatthias Ringwald     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
926fad84cafSMatthias Ringwald     if (!channel) return;
927fad84cafSMatthias Ringwald     channel->waiting_for_can_send_now = 1;
92809e9d05bSMatthias Ringwald     l2cap_notify_channel_can_send();
92909e9d05bSMatthias Ringwald }
93009e9d05bSMatthias Ringwald 
93109e9d05bSMatthias Ringwald int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
9325774a392SMatthias Ringwald     UNUSED(channel_id); // ok: only depends on Controller LE buffers
9339ec2630cSMatthias Ringwald 
93409e9d05bSMatthias Ringwald     return hci_can_send_acl_packet_now(con_handle);
93509e9d05bSMatthias Ringwald }
93609e9d05bSMatthias Ringwald 
93709e9d05bSMatthias Ringwald uint8_t *l2cap_get_outgoing_buffer(void){
93809e9d05bSMatthias Ringwald     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
93909e9d05bSMatthias Ringwald }
94009e9d05bSMatthias Ringwald 
9414e6fa3a2SMatthias Ringwald // only for L2CAP Basic Channels
94209e9d05bSMatthias Ringwald int l2cap_reserve_packet_buffer(void){
94309e9d05bSMatthias Ringwald     return hci_reserve_packet_buffer();
94409e9d05bSMatthias Ringwald }
94509e9d05bSMatthias Ringwald 
9464e6fa3a2SMatthias Ringwald // only for L2CAP Basic Channels
94709e9d05bSMatthias Ringwald void l2cap_release_packet_buffer(void){
94809e9d05bSMatthias Ringwald     hci_release_packet_buffer();
94909e9d05bSMatthias Ringwald }
95009e9d05bSMatthias Ringwald 
951f511cefaSMatthias 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){
95209e9d05bSMatthias Ringwald     // 0 - Connection handle : PB=pb : BC=00
953f511cefaSMatthias Ringwald     little_endian_store_16(acl_buffer, 0, con_handle | (packet_boundary << 12) | (0 << 14));
95409e9d05bSMatthias Ringwald     // 2 - ACL length
95509e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 2,  len + 4);
95609e9d05bSMatthias Ringwald     // 4 - L2CAP packet length
95709e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 4,  len + 0);
95809e9d05bSMatthias Ringwald     // 6 - L2CAP channel DEST
95909e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 6,  remote_cid);
96009e9d05bSMatthias Ringwald }
96109e9d05bSMatthias Ringwald 
962f511cefaSMatthias Ringwald // assumption - only on LE connections
96309e9d05bSMatthias Ringwald int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
96409e9d05bSMatthias Ringwald 
96509e9d05bSMatthias Ringwald     if (!hci_is_packet_buffer_reserved()){
96609e9d05bSMatthias Ringwald         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
96709e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
96809e9d05bSMatthias Ringwald     }
96909e9d05bSMatthias Ringwald 
97009e9d05bSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
97109e9d05bSMatthias Ringwald         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
97209e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
97309e9d05bSMatthias Ringwald     }
97409e9d05bSMatthias Ringwald 
97509e9d05bSMatthias Ringwald     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
97609e9d05bSMatthias Ringwald 
97709e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
978f511cefaSMatthias Ringwald     l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
97909e9d05bSMatthias Ringwald     // send
98009e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len+8);
98109e9d05bSMatthias Ringwald }
98209e9d05bSMatthias Ringwald 
983f511cefaSMatthias Ringwald // assumption - only on LE connections
98409e9d05bSMatthias Ringwald int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
98509e9d05bSMatthias Ringwald 
98609e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(con_handle)){
98709e9d05bSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", cid);
98809e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
98909e9d05bSMatthias Ringwald     }
99009e9d05bSMatthias Ringwald 
99109e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
99209e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
99309e9d05bSMatthias Ringwald 
99409e9d05bSMatthias Ringwald     memcpy(&acl_buffer[8], data, len);
99509e9d05bSMatthias Ringwald 
99609e9d05bSMatthias Ringwald     return l2cap_send_prepared_connectionless(con_handle, cid, len);
99709e9d05bSMatthias Ringwald }
99809e9d05bSMatthias Ringwald 
99909e9d05bSMatthias Ringwald static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
1000d9d23054SMatthias Ringwald     log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
100109e9d05bSMatthias Ringwald     uint8_t event[4];
100209e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
100309e9d05bSMatthias Ringwald     event[1] = sizeof(event) - 2;
100409e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, channel);
100509e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
100609e9d05bSMatthias Ringwald     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
100709e9d05bSMatthias Ringwald }
100809e9d05bSMatthias Ringwald 
100909e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
101017a9b554SMatthias Ringwald static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
101158de5610Smatthias.ringwald     (* (channel->packet_handler))(type, channel->local_cid, data, size);
101258de5610Smatthias.ringwald }
101358de5610Smatthias.ringwald 
101444276248SMatthias Ringwald static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
101544276248SMatthias Ringwald     uint8_t event[4];
101644276248SMatthias Ringwald     event[0] = event_code;
101744276248SMatthias Ringwald     event[1] = sizeof(event) - 2;
101844276248SMatthias Ringwald     little_endian_store_16(event, 2, channel->local_cid);
101944276248SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
102044276248SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
102144276248SMatthias Ringwald }
102209e9d05bSMatthias Ringwald #endif
102344276248SMatthias Ringwald 
102409e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
102558de5610Smatthias.ringwald void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
1026c9dc710bS[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",
1027fc64f94aSMatthias Ringwald              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
1028c9dc710bS[email protected]              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
10297f1690cfSMatthias Ringwald     uint8_t event[26];
103058de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
103158de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
103258de5610Smatthias.ringwald     event[2] = status;
1033724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
1034fc64f94aSMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
1035f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
1036f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
1037f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
1038f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 17, channel->local_mtu);
1039f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 19, channel->remote_mtu);
1040f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 21, channel->flush_timeout);
1041*c1ab6cc1SMatthias Ringwald     event[23] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
10427f1690cfSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
10437f1690cfSMatthias Ringwald     log_info("ERTM mode %u, fcs enabled %u", channel->mode, channel->fcs_option);
10447f1690cfSMatthias Ringwald     event[24] = channel->mode;
10457f1690cfSMatthias Ringwald     event[25] = channel->fcs_option;
10467f1690cfSMatthias Ringwald 
10477f1690cfSMatthias Ringwald #else
10487f1690cfSMatthias Ringwald     event[24] = L2CAP_CHANNEL_MODE_BASIC;
10497f1690cfSMatthias Ringwald     event[25] = 0;
10507f1690cfSMatthias Ringwald #endif
105158de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
105217a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
105358de5610Smatthias.ringwald }
105458de5610Smatthias.ringwald 
105544276248SMatthias Ringwald static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
1056e0abb8e7S[email protected]     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
105744276248SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
105858de5610Smatthias.ringwald }
105958de5610Smatthias.ringwald 
106044276248SMatthias Ringwald static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
1061e0abb8e7S[email protected]     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
1062fc64f94aSMatthias Ringwald              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
106358de5610Smatthias.ringwald     uint8_t event[16];
106458de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
106558de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
1066724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[2]);
1067fc64f94aSMatthias Ringwald     little_endian_store_16(event,  8, channel->con_handle);
1068f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 10, channel->psm);
1069f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 12, channel->local_cid);
1070f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 14, channel->remote_cid);
107158de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
107217a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
10730af41d30Smatthias.ringwald }
1074f62db1e3Smatthias.ringwald 
107566a72640SMatthias Ringwald static void l2cap_handle_channel_open_failed(l2cap_channel_t * channel, uint8_t status){
107666a72640SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
107766a72640SMatthias Ringwald     // emit ertm buffer released, as it's not needed. if in basic mode, it was either not allocated or already released
107866a72640SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
107966a72640SMatthias Ringwald         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
108066a72640SMatthias Ringwald     }
108166a72640SMatthias Ringwald #endif
1082624873c3SMatthias Ringwald     l2cap_emit_channel_opened(channel, status);
1083624873c3SMatthias Ringwald }
1084624873c3SMatthias Ringwald 
108566a72640SMatthias Ringwald static void l2cap_handle_channel_closed(l2cap_channel_t * channel){
108666a72640SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
108766a72640SMatthias Ringwald     // emit ertm buffer released, as it's not needed anymore. if in basic mode, it was either not allocated or already released
108866a72640SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
108966a72640SMatthias Ringwald         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
109066a72640SMatthias Ringwald     }
109166a72640SMatthias Ringwald #endif
109266a72640SMatthias Ringwald     l2cap_emit_channel_closed(channel);
109366a72640SMatthias Ringwald }
1094dd3bf36fSMatthias Ringwald #endif
1095dd3bf36fSMatthias Ringwald 
1096dd3bf36fSMatthias Ringwald static l2cap_fixed_channel_t * l2cap_channel_item_by_cid(uint16_t cid){
1097dd3bf36fSMatthias Ringwald     btstack_linked_list_iterator_t it;
1098dd3bf36fSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1099dd3bf36fSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1100dd3bf36fSMatthias Ringwald         l2cap_fixed_channel_t * channel = (l2cap_fixed_channel_t*) btstack_linked_list_iterator_next(&it);
1101dd3bf36fSMatthias Ringwald         if (channel->local_cid == cid) {
1102dd3bf36fSMatthias Ringwald             return channel;
1103dd3bf36fSMatthias Ringwald         }
1104dd3bf36fSMatthias Ringwald     }
1105dd3bf36fSMatthias Ringwald     return NULL;
1106dd3bf36fSMatthias Ringwald }
110766a72640SMatthias Ringwald 
1108fad84cafSMatthias Ringwald // used for fixed channels in LE (ATT/SM) and Classic (Connectionless Channel). CID < 0x04
1109fad84cafSMatthias Ringwald static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid){
1110fad84cafSMatthias Ringwald     if (local_cid >= 0x40) return NULL;
1111fad84cafSMatthias Ringwald     return (l2cap_fixed_channel_t*) l2cap_channel_item_by_cid(local_cid);
1112fad84cafSMatthias Ringwald }
111324eb964eSMatthias Ringwald 
111424eb964eSMatthias Ringwald // used for Classic Channels + LE Data Channels. local_cid >= 0x40
111524eb964eSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
111624eb964eSMatthias Ringwald static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
111724eb964eSMatthias Ringwald     if (local_cid < 0x40) return NULL;
111824eb964eSMatthias Ringwald     return (l2cap_channel_t*) l2cap_channel_item_by_cid(local_cid);
111924eb964eSMatthias Ringwald }
11200b9d7e78SMatthias Ringwald 
112130725612SMatthias Ringwald void l2cap_request_can_send_now_event(uint16_t local_cid){
112230725612SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
112330725612SMatthias Ringwald     if (!channel) return;
112430725612SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
112596646001SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
112696646001SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
112796646001SMatthias Ringwald         l2cap_ertm_notify_channel_can_send(channel);
112896646001SMatthias Ringwald         return;
112996646001SMatthias Ringwald     }
113096646001SMatthias Ringwald #endif
113130725612SMatthias Ringwald     l2cap_notify_channel_can_send();
113230725612SMatthias Ringwald }
113330725612SMatthias Ringwald 
113496646001SMatthias Ringwald int  l2cap_can_send_packet_now(uint16_t local_cid){
113596646001SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
113696646001SMatthias Ringwald     if (!channel) return 0;
113796646001SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
113896646001SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
113996646001SMatthias Ringwald         return l2cap_ertm_can_store_packet_now(channel);
114096646001SMatthias Ringwald     }
114196646001SMatthias Ringwald #endif
11420b9d7e78SMatthias Ringwald     return hci_can_send_acl_packet_now(channel->con_handle);
11437856fb31S[email protected] }
11447856fb31S[email protected] 
114583e7cdd9SMatthias Ringwald int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
114683e7cdd9SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
114783e7cdd9SMatthias Ringwald     if (!channel) return 0;
11480b20b13bSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
11490b20b13bSMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
11500b20b13bSMatthias Ringwald         return 0;
11510b20b13bSMatthias Ringwald     }
11520b20b13bSMatthias Ringwald #endif
11530b9d7e78SMatthias Ringwald     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
115483e7cdd9SMatthias Ringwald }
11550b20b13bSMatthias Ringwald 
115696cbd662Smatthias.ringwald uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
115796cbd662Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
115896cbd662Smatthias.ringwald     if (channel) {
115996cbd662Smatthias.ringwald         return channel->remote_mtu;
116096cbd662Smatthias.ringwald     }
116196cbd662Smatthias.ringwald     return 0;
116296cbd662Smatthias.ringwald }
116324eb964eSMatthias Ringwald #endif
116496cbd662Smatthias.ringwald 
116524eb964eSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
1166fad84cafSMatthias Ringwald static int l2cap_is_dynamic_channel_type(l2cap_channel_type_t channel_type){
1167fad84cafSMatthias Ringwald     switch (channel_type){
1168fad84cafSMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CLASSIC:
1169fad84cafSMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
1170fad84cafSMatthias Ringwald             return 1;
1171fad84cafSMatthias Ringwald         default:
1172fad84cafSMatthias Ringwald             return 0;
1173fad84cafSMatthias Ringwald     }
1174fad84cafSMatthias Ringwald }
117524eb964eSMatthias Ringwald #endif
1176fad84cafSMatthias Ringwald 
117724eb964eSMatthias Ringwald #ifdef ENABLE_CLASSIC
1178fad84cafSMatthias Ringwald // RTX Timer only exist for dynamic channels
1179ec820d77SMatthias Ringwald static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
1180665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1181665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1182665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1183665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1184fad84cafSMatthias Ringwald         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
11855932bd7cS[email protected]         if (&channel->rtx == ts) {
11865932bd7cS[email protected]             return channel;
11875932bd7cS[email protected]         }
11885932bd7cS[email protected]     }
11895932bd7cS[email protected]     return NULL;
11905932bd7cS[email protected] }
11915932bd7cS[email protected] 
1192ec820d77SMatthias Ringwald static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
11935932bd7cS[email protected]     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
119495d2c8f4SMatthias Ringwald     if (!channel) return;
11955932bd7cS[email protected] 
11965932bd7cS[email protected]     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
11975932bd7cS[email protected] 
11985932bd7cS[email protected]     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
11995932bd7cS[email protected]     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
12005932bd7cS[email protected]     // notify client
120166a72640SMatthias Ringwald     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
12025932bd7cS[email protected] 
12035932bd7cS[email protected]     // discard channel
1204665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1205c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
12065932bd7cS[email protected] }
12075932bd7cS[email protected] 
120813aa3e4bSMatthias Ringwald #endif
120913aa3e4bSMatthias Ringwald 
121013aa3e4bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
12115932bd7cS[email protected] static void l2cap_stop_rtx(l2cap_channel_t * channel){
12125932bd7cS[email protected]     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
1213528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->rtx);
12145932bd7cS[email protected] }
121513aa3e4bSMatthias Ringwald #endif
121613aa3e4bSMatthias Ringwald 
121713aa3e4bSMatthias Ringwald #ifdef ENABLE_CLASSIC
12185932bd7cS[email protected] 
12195932bd7cS[email protected] static void l2cap_start_rtx(l2cap_channel_t * channel){
12205932bd7cS[email protected]     l2cap_stop_rtx(channel);
1221cb0ff06bS[email protected]     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
1222528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1223528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
1224528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
12255932bd7cS[email protected] }
12265932bd7cS[email protected] 
12275932bd7cS[email protected] static void l2cap_start_ertx(l2cap_channel_t * channel){
12285932bd7cS[email protected]     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
12295932bd7cS[email protected]     l2cap_stop_rtx(channel);
1230528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1231528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
1232528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
12335932bd7cS[email protected] }
12345932bd7cS[email protected] 
123571de195eSMatthias Ringwald void l2cap_require_security_level_2_for_outgoing_sdp(void){
1236ac301f95S[email protected]     require_security_level2_for_outgoing_sdp = 1;
1237ac301f95S[email protected] }
1238ac301f95S[email protected] 
1239df3354fcS[email protected] static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
124084e3541eSMilanka Ringwald     return (psm == BLUETOOTH_PSM_SDP) && (!require_security_level2_for_outgoing_sdp);
1241df3354fcS[email protected] }
12425932bd7cS[email protected] 
124363854e74SMatthias Ringwald static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1244a35252c8S[email protected]     if (!hci_can_send_acl_packet_now(handle)){
12459da54300S[email protected]         log_info("l2cap_send_signaling_packet, cannot send");
1246b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
1247b1d43497Smatthias.ringwald     }
1248b1d43497Smatthias.ringwald 
12499da54300S[email protected]     // log_info("l2cap_send_signaling_packet type %u", cmd);
12502a373862S[email protected]     hci_reserve_packet_buffer();
1251facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
125258de5610Smatthias.ringwald     va_list argptr;
125358de5610Smatthias.ringwald     va_start(argptr, identifier);
125470efece1S[email protected]     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
125558de5610Smatthias.ringwald     va_end(argptr);
12569da54300S[email protected]     // log_info("l2cap_send_signaling_packet con %u!", handle);
1257826f7347S[email protected]     return hci_send_acl_packet_buffer(len);
125858de5610Smatthias.ringwald }
125958de5610Smatthias.ringwald 
1260f511cefaSMatthias Ringwald // assumption - only on Classic connections
12614e6fa3a2SMatthias Ringwald // cannot be used for L2CAP ERTM
1262b1d43497Smatthias.ringwald int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
1263b1d43497Smatthias.ringwald 
1264c8b9416aS[email protected]     if (!hci_is_packet_buffer_reserved()){
1265c8b9416aS[email protected]         log_error("l2cap_send_prepared called without reserving packet first");
1266c8b9416aS[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
1267c8b9416aS[email protected]     }
1268c8b9416aS[email protected] 
126958de5610Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1270b1d43497Smatthias.ringwald     if (!channel) {
12719da54300S[email protected]         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
1272b1d43497Smatthias.ringwald         return -1;   // TODO: define error
12736218e6f1Smatthias.ringwald     }
12746218e6f1Smatthias.ringwald 
1275fc64f94aSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
12769da54300S[email protected]         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
1277a35252c8S[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
1278a35252c8S[email protected]     }
1279a35252c8S[email protected] 
1280fc64f94aSMatthias Ringwald     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
1281b1d43497Smatthias.ringwald 
128285ddcd84SMatthias Ringwald     int fcs_size = 0;
128385ddcd84SMatthias Ringwald 
128485ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
12856574158aSMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->fcs_option){
128685ddcd84SMatthias Ringwald         fcs_size = 2;
128785ddcd84SMatthias Ringwald     }
128885ddcd84SMatthias Ringwald #endif
128985ddcd84SMatthias Ringwald 
1290f511cefaSMatthias Ringwald     // set non-flushable packet boundary flag if supported on Controller
1291facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1292f511cefaSMatthias Ringwald     uint8_t packet_boundary_flag = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
129385ddcd84SMatthias Ringwald     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
129485ddcd84SMatthias Ringwald 
129585ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1296b72f6906SMatthias Ringwald     if (fcs_size){
129785ddcd84SMatthias Ringwald         // calculate FCS over l2cap data
129885ddcd84SMatthias Ringwald         uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
129985ddcd84SMatthias Ringwald         log_info("I-Frame: fcs 0x%04x", fcs);
130085ddcd84SMatthias Ringwald         little_endian_store_16(acl_buffer, 8 + len, fcs);
130158de5610Smatthias.ringwald     }
130285ddcd84SMatthias Ringwald #endif
130385ddcd84SMatthias Ringwald 
130485ddcd84SMatthias Ringwald     // send
130585ddcd84SMatthias Ringwald     return hci_send_acl_packet_buffer(len+8+fcs_size);
130685ddcd84SMatthias Ringwald }
130785ddcd84SMatthias Ringwald 
1308f511cefaSMatthias Ringwald // assumption - only on Classic connections
1309ce8f182eSMatthias Ringwald int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
1310a35252c8S[email protected]     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1311a35252c8S[email protected]     if (!channel) {
1312ce8f182eSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
1313a35252c8S[email protected]         return -1;   // TODO: define error
1314a35252c8S[email protected]     }
1315a35252c8S[email protected] 
1316f0fb4cd7SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1317f0fb4cd7SMatthias Ringwald     // send in ERTM
1318f0fb4cd7SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1319f0fb4cd7SMatthias Ringwald         return l2cap_ertm_send(channel, data, len);
1320f0fb4cd7SMatthias Ringwald     }
1321f0fb4cd7SMatthias Ringwald #endif
1322f0fb4cd7SMatthias Ringwald 
1323f0efaa57S[email protected]     if (len > channel->remote_mtu){
1324ce8f182eSMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
1325f0efaa57S[email protected]         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
1326f0efaa57S[email protected]     }
1327f0efaa57S[email protected] 
1328fc64f94aSMatthias Ringwald     if (!hci_can_send_acl_packet_now(channel->con_handle)){
1329ce8f182eSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
1330b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
1331b1d43497Smatthias.ringwald     }
1332b1d43497Smatthias.ringwald 
13332a373862S[email protected]     hci_reserve_packet_buffer();
1334facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1335f0fb4cd7SMatthias Ringwald     memcpy(&acl_buffer[8], data, len);
1336f0fb4cd7SMatthias Ringwald     return l2cap_send_prepared(local_cid, len);
1337b1d43497Smatthias.ringwald }
1338b1d43497Smatthias.ringwald 
1339fc64f94aSMatthias Ringwald int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
1340fc64f94aSMatthias Ringwald     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
13410e37e417S[email protected] }
13420e37e417S[email protected] 
134328ca2b46S[email protected] static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
134428ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
134528ca2b46S[email protected] }
134628ca2b46S[email protected] 
134728ca2b46S[email protected] static inline void channelStateVarClearFlag(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] }
135009e9d05bSMatthias Ringwald #endif
135128ca2b46S[email protected] 
135228ca2b46S[email protected] 
135309e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
135463854e74SMatthias Ringwald static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
135509e9d05bSMatthias Ringwald 
135609e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(handle)){
135709e9d05bSMatthias Ringwald         log_info("l2cap_send_le_signaling_packet, cannot send");
135809e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
135909e9d05bSMatthias Ringwald     }
136009e9d05bSMatthias Ringwald 
136109e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
136209e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
136309e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
136409e9d05bSMatthias Ringwald     va_list argptr;
136509e9d05bSMatthias Ringwald     va_start(argptr, identifier);
136609e9d05bSMatthias Ringwald     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
136709e9d05bSMatthias Ringwald     va_end(argptr);
136809e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
136909e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len);
137009e9d05bSMatthias Ringwald }
137109e9d05bSMatthias Ringwald #endif
137209e9d05bSMatthias Ringwald 
137309e9d05bSMatthias Ringwald uint16_t l2cap_max_mtu(void){
137409e9d05bSMatthias Ringwald     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
137509e9d05bSMatthias Ringwald }
137609e9d05bSMatthias Ringwald 
13773e329ddfSandryblack #ifdef ENABLE_BLE
137809e9d05bSMatthias Ringwald uint16_t l2cap_max_le_mtu(void){
137925818320SMatthias Ringwald     if (l2cap_le_custom_max_mtu != 0) return l2cap_le_custom_max_mtu;
138009e9d05bSMatthias Ringwald     return l2cap_max_mtu();
138109e9d05bSMatthias Ringwald }
1382b1d43497Smatthias.ringwald 
138325818320SMatthias Ringwald void l2cap_set_max_le_mtu(uint16_t max_mtu){
138425818320SMatthias Ringwald     if (max_mtu < l2cap_max_mtu()){
138525818320SMatthias Ringwald         l2cap_le_custom_max_mtu = max_mtu;
138625818320SMatthias Ringwald     }
138725818320SMatthias Ringwald }
13883e329ddfSandryblack #endif
138925818320SMatthias Ringwald 
1390d2afdd38SMatthias Ringwald #ifdef ENABLE_CLASSIC
1391d2afdd38SMatthias Ringwald 
13926b99230fSMatthias Ringwald static uint16_t l2cap_setup_options_mtu(uint8_t * config_options, uint16_t mtu){
1393d64e9771SMatthias Ringwald     config_options[0] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
1394d2afdd38SMatthias Ringwald     config_options[1] = 2; // len param
13956b99230fSMatthias Ringwald     little_endian_store_16(config_options, 2, mtu);
1396d2afdd38SMatthias Ringwald     return 4;
1397d2afdd38SMatthias Ringwald }
1398d2afdd38SMatthias Ringwald 
1399450ad7ecSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
14006b99230fSMatthias Ringwald static int l2cap_ertm_mode(l2cap_channel_t * channel){
1401450ad7ecSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
14026b99230fSMatthias Ringwald     return ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE)
14036b99230fSMatthias Ringwald         &&  (connection->l2cap_state.extended_feature_mask & 0x08));
1404450ad7ecSMatthias Ringwald }
1405450ad7ecSMatthias Ringwald #endif
14066b99230fSMatthias Ringwald 
14076b99230fSMatthias Ringwald static uint16_t l2cap_setup_options_request(l2cap_channel_t * channel, uint8_t * config_options){
14086b99230fSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1409313d3a26SMatthias Ringwald     // use ERTM options if supported by remote and channel ready to use it
1410313d3a26SMatthias Ringwald     if (l2cap_ertm_mode(channel) && channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
14117cbe539fSMatthias Ringwald         return l2cap_setup_options_ertm_request(channel, config_options);
14126b99230fSMatthias Ringwald     }
14136b99230fSMatthias Ringwald #endif
14146b99230fSMatthias Ringwald     uint16_t mtu = channel->local_mtu;
14156b99230fSMatthias Ringwald     return l2cap_setup_options_mtu(config_options, mtu);
14166b99230fSMatthias Ringwald }
14176b99230fSMatthias Ringwald 
1418b8134563SMatthias Ringwald static uint16_t l2cap_setup_options_mtu_response(l2cap_channel_t * channel, uint8_t * config_options){
141932717978SMatthias Ringwald     uint16_t mtu = btstack_min(channel->local_mtu, channel->remote_mtu);
14206b99230fSMatthias Ringwald     return l2cap_setup_options_mtu(config_options, mtu);
14216dca2a0cSMatthias Ringwald }
14226dca2a0cSMatthias Ringwald 
14231b9cb13dSMatthias Ringwald static uint32_t l2cap_extended_features_mask(void){
14241b9cb13dSMatthias Ringwald     // extended features request supported, features: fixed channels, unicast connectionless data reception
14251b9cb13dSMatthias Ringwald     uint32_t features = 0x280;
14261b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
142754901195SMatthias Ringwald     features |= 0x0028;
14281b9cb13dSMatthias Ringwald #endif
14291b9cb13dSMatthias Ringwald     return features;
14301b9cb13dSMatthias Ringwald }
1431d2afdd38SMatthias Ringwald #endif
14321b9cb13dSMatthias Ringwald 
14338158c421Smatthias.ringwald // MARK: L2CAP_RUN
14342cd0be45Smatthias.ringwald // process outstanding signaling tasks
14357f02f414SMatthias Ringwald static void l2cap_run(void){
14362b83fb7dSmatthias.ringwald 
143722c29ab4SMatthias Ringwald     // log_info("l2cap_run: entered");
143822c29ab4SMatthias Ringwald 
14392b83fb7dSmatthias.ringwald     // check pending signaling responses
14402b83fb7dSmatthias.ringwald     while (signaling_responses_pending){
14412b83fb7dSmatthias.ringwald 
14422b83fb7dSmatthias.ringwald         hci_con_handle_t handle = signaling_responses[0].handle;
1443a35252c8S[email protected] 
1444a35252c8S[email protected]         if (!hci_can_send_acl_packet_now(handle)) break;
1445a35252c8S[email protected] 
14462b83fb7dSmatthias.ringwald         uint8_t  sig_id        = signaling_responses[0].sig_id;
1447e74c5f58SMatthias Ringwald         uint8_t  response_code = signaling_responses[0].code;
144863a7246aSmatthias.ringwald         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
1449b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
14505774a392SMatthias Ringwald         uint16_t info_type     = signaling_responses[0].data;  // INFORMATION_REQUEST
1451b3264428SMatthias Ringwald         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
1452b3264428SMatthias Ringwald #endif
145309e9d05bSMatthias Ringwald 
1454f53da564S[email protected]         // remove first item before sending (to avoid sending response mutliple times)
1455f53da564S[email protected]         signaling_responses_pending--;
1456f53da564S[email protected]         int i;
1457f53da564S[email protected]         for (i=0; i < signaling_responses_pending; i++){
1458f53da564S[email protected]             memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t));
1459f53da564S[email protected]         }
1460f53da564S[email protected] 
1461f53da564S[email protected]         switch (response_code){
146209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
14632b360848Smatthias.ringwald             case CONNECTION_REQUEST:
1464e74c5f58SMatthias Ringwald                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
14652bd8b7e7S[email protected]                 // also disconnect if result is 0x0003 - security blocked
14664d816277S[email protected]                 if (result == 0x0003){
14672bd8b7e7S[email protected]                     hci_disconnect_security_block(handle);
14684d816277S[email protected]                 }
14692b360848Smatthias.ringwald                 break;
14702b83fb7dSmatthias.ringwald             case ECHO_REQUEST:
14712b83fb7dSmatthias.ringwald                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
14722b83fb7dSmatthias.ringwald                 break;
14732b83fb7dSmatthias.ringwald             case INFORMATION_REQUEST:
14743e64cb44SMatthias Ringwald                 switch (info_type){
14753e64cb44SMatthias Ringwald                     case L2CAP_INFO_TYPE_CONNECTIONLESS_MTU: {
14763b0484b3S[email protected]                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
14773e64cb44SMatthias Ringwald                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(connectionless_mtu), &connectionless_mtu);
14783b0484b3S[email protected]                         }
1479202c8a4cSMatthias Ringwald                         break;
14803e64cb44SMatthias Ringwald                     case L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED: {
14811b9cb13dSMatthias Ringwald                             uint32_t features = l2cap_extended_features_mask();
14823e64cb44SMatthias Ringwald                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(features), &features);
14833b0484b3S[email protected]                         }
1484202c8a4cSMatthias Ringwald                         break;
14853e64cb44SMatthias Ringwald                     case L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED: {
14863b0484b3S[email protected]                             uint8_t map[8];
14873b0484b3S[email protected]                             memset(map, 0, 8);
1488288636a2SMatthias Ringwald                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
14893e64cb44SMatthias Ringwald                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(map), &map);
14903b0484b3S[email protected]                         }
1491202c8a4cSMatthias Ringwald                         break;
14923b0484b3S[email protected]                     default:
14932b83fb7dSmatthias.ringwald                         // all other types are not supported
14943e64cb44SMatthias Ringwald                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 1, 0, NULL);
14953b0484b3S[email protected]                         break;
14962b83fb7dSmatthias.ringwald                 }
14972b83fb7dSmatthias.ringwald                 break;
149863a7246aSmatthias.ringwald             case COMMAND_REJECT:
14995ca8d57bS[email protected]                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
150063f0ac45SMatthias Ringwald                 break;
150109e9d05bSMatthias Ringwald #endif
1502a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
150363f0ac45SMatthias Ringwald             case LE_CREDIT_BASED_CONNECTION_REQUEST:
150463f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
150563f0ac45SMatthias Ringwald                 break;
150670efece1S[email protected]             case COMMAND_REJECT_LE:
150770efece1S[email protected]                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
150863a7246aSmatthias.ringwald                 break;
150970efece1S[email protected] #endif
15102b83fb7dSmatthias.ringwald             default:
15112b83fb7dSmatthias.ringwald                 // should not happen
15122b83fb7dSmatthias.ringwald                 break;
15132b83fb7dSmatthias.ringwald         }
15142b83fb7dSmatthias.ringwald     }
15152b83fb7dSmatthias.ringwald 
1516959f646aSMatthias Ringwald #if defined(ENABLE_CLASSIC) || defined(ENABLE_BLE)
1517665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
15185774a392SMatthias Ringwald #endif
151909e9d05bSMatthias Ringwald 
15201b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
15211b9cb13dSMatthias Ringwald     // send l2cap information request if neccessary
15221b9cb13dSMatthias Ringwald     hci_connections_get_iterator(&it);
15231b9cb13dSMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
15241b9cb13dSMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
15251b9cb13dSMatthias Ringwald         if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST){
152693d791b2SMatthias Ringwald             if (!hci_can_send_acl_packet_now(connection->con_handle)) break;
15271b9cb13dSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
15281b9cb13dSMatthias Ringwald             uint8_t sig_id = l2cap_next_sig_id();
15293e64cb44SMatthias Ringwald             uint8_t info_type = L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED;
15301b9cb13dSMatthias Ringwald             l2cap_send_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
15311b9cb13dSMatthias Ringwald             return;
15321b9cb13dSMatthias Ringwald         }
15331b9cb13dSMatthias Ringwald     }
15341b9cb13dSMatthias Ringwald #endif
15351b9cb13dSMatthias Ringwald 
153609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1537f2c70799Sandryblack #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1538f2c70799Sandryblack     uint8_t  config_options[18];
1539f2c70799Sandryblack #else
154043ec931dSMatthias Ringwald     uint8_t  config_options[10];
1541f2c70799Sandryblack #endif
1542665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1543665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1544baf94f06S[email protected] 
1545665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1546421cb104SMatthias Ringwald 
1547421cb104SMatthias Ringwald         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CLASSIC) continue;
1548421cb104SMatthias Ringwald 
154922c29ab4SMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
15502cd0be45Smatthias.ringwald         switch (channel->state){
15512cd0be45Smatthias.ringwald 
1552df3354fcS[email protected]             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1553ad671560S[email protected]             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
1554fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1555a00031e2S[email protected]                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
1556ad671560S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
1557fc64f94aSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
1558ad671560S[email protected]                 }
1559ad671560S[email protected]                 break;
1560ad671560S[email protected] 
156102b22dc4Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1562baf94f06S[email protected]                 if (!hci_can_send_command_packet_now()) break;
156364472d52Smatthias.ringwald                 // send connection request - set state first
156464472d52Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
156502b22dc4Smatthias.ringwald                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
1566ece97caeSMatthias Ringwald                 memcpy(l2cap_outgoing_classic_addr, channel->address, 6);
15678f8108aaSmatthias.ringwald                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
156802b22dc4Smatthias.ringwald                 break;
156902b22dc4Smatthias.ringwald 
1570e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
1571fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
157222c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1573fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
1574e7ff783cSmatthias.ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1575665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1576c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
1577e7ff783cSmatthias.ringwald                 break;
1578e7ff783cSmatthias.ringwald 
1579552d92a1Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
1580fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1581fa8473a4Smatthias.ringwald                 channel->state = L2CAP_STATE_CONFIG;
158228ca2b46S[email protected]                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1583fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
1584552d92a1Smatthias.ringwald                 break;
1585552d92a1Smatthias.ringwald 
15866fdcc387Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
1587fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
15886fdcc387Smatthias.ringwald                 // success, start l2cap handshake
1589b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
15906fdcc387Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
1591fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
15925932bd7cS[email protected]                 l2cap_start_rtx(channel);
15936fdcc387Smatthias.ringwald                 break;
15946fdcc387Smatthias.ringwald 
1595fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
1596fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
159761c3f6deSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
159861c3f6deSMatthias Ringwald                     // fallback to basic mode if ERTM requested but not not supported by remote
159961c3f6deSMatthias Ringwald                      if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
160061c3f6deSMatthias Ringwald                         if (!l2cap_ertm_mode(channel)){
160161c3f6deSMatthias Ringwald                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
160261c3f6deSMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
160361c3f6deSMatthias Ringwald                         }
160461c3f6deSMatthias Ringwald                     }
160561c3f6deSMatthias Ringwald #endif
160673cf2b3dSmatthias.ringwald                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
160763a7246aSmatthias.ringwald                     uint16_t flags = 0;
160828ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
160963a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
161063a7246aSmatthias.ringwald                         flags = 1;
161163a7246aSmatthias.ringwald                     } else {
161228ca2b46S[email protected]                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
161363a7246aSmatthias.ringwald                     }
161463a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
1615ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1616fc64f94aSMatthias 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);
1617ac8f1300SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1618ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
1619ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1620ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1621b8134563SMatthias Ringwald                         uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1622ac8f1300SMatthias 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);
1623b8134563SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM){
1624b8134563SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
1625b8134563SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1626b8134563SMatthias Ringwald                         uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1627b8134563SMatthias 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);
1628ac8f1300SMatthias Ringwald #endif
1629ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
163063a7246aSmatthias.ringwald                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1631b8134563SMatthias Ringwald                         uint16_t options_size = l2cap_setup_options_mtu_response(channel, config_options);
1632ac8f1300SMatthias 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);
163363a7246aSmatthias.ringwald                     } else {
1634ac8f1300SMatthias Ringwald                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
163563a7246aSmatthias.ringwald                     }
163663a7246aSmatthias.ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1637fa8473a4Smatthias.ringwald                 }
163873cf2b3dSmatthias.ringwald                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
163928ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
164028ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
1641b1988dceSmatthias.ringwald                     channel->local_sig_id = l2cap_next_sig_id();
16426b99230fSMatthias Ringwald                     uint16_t options_size = l2cap_setup_options_request(channel, config_options);
16436dca2a0cSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options);
16445932bd7cS[email protected]                     l2cap_start_rtx(channel);
1645fa8473a4Smatthias.ringwald                 }
1646fa8473a4Smatthias.ringwald                 if (l2cap_channel_ready_for_open(channel)){
1647552d92a1Smatthias.ringwald                     channel->state = L2CAP_STATE_OPEN;
1648552d92a1Smatthias.ringwald                     l2cap_emit_channel_opened(channel, 0);  // success
1649fa8473a4Smatthias.ringwald                 }
1650552d92a1Smatthias.ringwald                 break;
1651552d92a1Smatthias.ringwald 
1652e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1653fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
165422c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1655fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
16565932bd7cS[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 :)
1657756102d3Smatthias.ringwald                 l2cap_finialize_channel_close(channel);  // -- remove from list
165864cb054cSMatthias Ringwald                 channel = NULL;
1659e7ff783cSmatthias.ringwald                 break;
1660e7ff783cSmatthias.ringwald 
1661e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1662fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1663b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
16642cd0be45Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1665fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
16662cd0be45Smatthias.ringwald                 break;
16672cd0be45Smatthias.ringwald             default:
16682cd0be45Smatthias.ringwald                 break;
16692cd0be45Smatthias.ringwald         }
167038f62777SMatthias Ringwald 
167138f62777SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
167264cb054cSMatthias Ringwald 
16739700d53bSMilanka Ringwald         // handle channel finalize on L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE
167464cb054cSMatthias Ringwald         if (!channel) continue;
16759700d53bSMilanka Ringwald 
16769700d53bSMilanka Ringwald         // ERTM mode
16779700d53bSMilanka Ringwald         if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
16789700d53bSMilanka Ringwald 
16799700d53bSMilanka Ringwald             // check if we can still send
1680e0780573SMatthias Ringwald             if (channel->con_handle == HCI_CON_HANDLE_INVALID) continue;
168138f62777SMatthias Ringwald             if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
1682675e6881SMatthias Ringwald 
1683d84e866fSMatthias Ringwald             if (channel->send_supervisor_frame_receiver_ready){
168478cd8a22SMatthias Ringwald                 channel->send_supervisor_frame_receiver_ready = 0;
1685d2afdd38SMatthias Ringwald                 log_info("Send S-Frame: RR %u, final %u", channel->req_seq, channel->set_final_bit_after_packet_with_poll_bit_set);
1686d2afdd38SMatthias 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);
1687d2afdd38SMatthias Ringwald                 channel->set_final_bit_after_packet_with_poll_bit_set = 0;
168838f62777SMatthias Ringwald                 l2cap_ertm_send_supervisor_frame(channel, control);
1689675e6881SMatthias Ringwald                 continue;
169038f62777SMatthias Ringwald             }
169162041d70SMatthias Ringwald             if (channel->send_supervisor_frame_receiver_ready_poll){
169278cd8a22SMatthias Ringwald                 channel->send_supervisor_frame_receiver_ready_poll = 0;
169362041d70SMatthias Ringwald                 log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
169462041d70SMatthias Ringwald                 uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
169562041d70SMatthias Ringwald                 l2cap_ertm_send_supervisor_frame(channel, control);
169662041d70SMatthias Ringwald                 continue;
169762041d70SMatthias Ringwald             }
16988f1c9639SMatthias Ringwald             if (channel->send_supervisor_frame_receiver_not_ready){
169978cd8a22SMatthias Ringwald                 channel->send_supervisor_frame_receiver_not_ready = 0;
17008f1c9639SMatthias Ringwald                 log_info("Send S-Frame: RNR %u", channel->req_seq);
17018f1c9639SMatthias Ringwald                 uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
17028f1c9639SMatthias Ringwald                 l2cap_ertm_send_supervisor_frame(channel, control);
17038f1c9639SMatthias Ringwald                 continue;
17048f1c9639SMatthias Ringwald             }
1705c7309e8dSMatthias Ringwald             if (channel->send_supervisor_frame_reject){
1706c7309e8dSMatthias Ringwald                 channel->send_supervisor_frame_reject = 0;
1707c7309e8dSMatthias Ringwald                 log_info("Send S-Frame: REJ %u", channel->req_seq);
1708c7309e8dSMatthias Ringwald                 uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 0, 0, channel->req_seq);
1709c7309e8dSMatthias Ringwald                 l2cap_ertm_send_supervisor_frame(channel, control);
1710c7309e8dSMatthias Ringwald                 continue;
1711c7309e8dSMatthias Ringwald             }
1712df2191a7SMatthias Ringwald             if (channel->send_supervisor_frame_selective_reject){
1713df2191a7SMatthias Ringwald                 channel->send_supervisor_frame_selective_reject = 0;
1714df2191a7SMatthias Ringwald                 log_info("Send S-Frame: SREJ %u", channel->expected_tx_seq);
1715f85ade6bSMatthias 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);
1716f85ade6bSMatthias Ringwald                 channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1717df2191a7SMatthias Ringwald                 l2cap_ertm_send_supervisor_frame(channel, control);
1718df2191a7SMatthias Ringwald                 continue;
1719df2191a7SMatthias Ringwald             }
17207b7901d8SMatthias Ringwald 
17217b7901d8SMatthias Ringwald             if (channel->srej_active){
17227b7901d8SMatthias Ringwald                 int i;
17237b7901d8SMatthias Ringwald                 for (i=0;i<channel->num_tx_buffers;i++){
17247b7901d8SMatthias Ringwald                     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
17257b7901d8SMatthias Ringwald                     if (tx_state->retransmission_requested) {
17267b7901d8SMatthias Ringwald                         tx_state->retransmission_requested = 0;
1727d2afdd38SMatthias Ringwald                         uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set;
1728d2afdd38SMatthias Ringwald                         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1729d2afdd38SMatthias Ringwald                         l2cap_ertm_send_information_frame(channel, i, final);
17307b7901d8SMatthias Ringwald                         break;
17317b7901d8SMatthias Ringwald                     }
17327b7901d8SMatthias Ringwald                 }
17337b7901d8SMatthias Ringwald                 if (i == channel->num_tx_buffers){
17347b7901d8SMatthias Ringwald                     // no retransmission request found
17357b7901d8SMatthias Ringwald                     channel->srej_active = 0;
17367b7901d8SMatthias Ringwald                 } else {
17377b7901d8SMatthias Ringwald                     // packet was sent
17387b7901d8SMatthias Ringwald                     continue;
17397b7901d8SMatthias Ringwald                 }
17407b7901d8SMatthias Ringwald             }
17419700d53bSMilanka Ringwald         }
174238f62777SMatthias Ringwald #endif
174338f62777SMatthias Ringwald 
17442cd0be45Smatthias.ringwald     }
174509e9d05bSMatthias Ringwald #endif
1746da886c03S[email protected] 
1747cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1748421cb104SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1749efedfb4cSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1750b5803aafSMatthias Ringwald         uint16_t mps;
1751efedfb4cSMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1752421cb104SMatthias Ringwald 
1753421cb104SMatthias Ringwald         if (channel->channel_type != L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL) continue;
1754421cb104SMatthias Ringwald 
1755efedfb4cSMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1756efedfb4cSMatthias Ringwald         switch (channel->state){
17575cb87675SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
17585cb87675SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
17595cb87675SMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
17605cb87675SMatthias Ringwald                 // le psm, source cid, mtu, mps, initial credits
17611b8b8d05SMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
176263f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
176363f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
1764b5803aafSMatthias Ringwald                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
1765b5803aafSMatthias 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);
17665cb87675SMatthias Ringwald                 break;
176723017473SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
176823017473SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
176923017473SMatthias Ringwald                 // TODO: support larger MPS
177023017473SMatthias Ringwald                 channel->state = L2CAP_STATE_OPEN;
177163f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
177263f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
1773b5803aafSMatthias Ringwald                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
1774b5803aafSMatthias 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);
177564e11ca9SMatthias Ringwald                 // notify client
177644276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0);
177723017473SMatthias Ringwald                 break;
1778e7d0c9aaSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
1779e7d0c9aaSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1780e7d0c9aaSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
178163f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
1782e7d0c9aaSMatthias Ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1783e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1784c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
1785e7d0c9aaSMatthias Ringwald                 break;
17867f107edaSMatthias Ringwald             case L2CAP_STATE_OPEN:
178785aeef60SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
178885aeef60SMatthias Ringwald 
178985aeef60SMatthias Ringwald                 // send credits
179085aeef60SMatthias Ringwald                 if (channel->new_credits_incoming){
179185aeef60SMatthias Ringwald                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
179285aeef60SMatthias Ringwald                     channel->local_sig_id = l2cap_next_sig_id();
179385aeef60SMatthias Ringwald                     uint16_t new_credits = channel->new_credits_incoming;
179485aeef60SMatthias Ringwald                     channel->new_credits_incoming = 0;
179585aeef60SMatthias Ringwald                     channel->credits_incoming += new_credits;
179685aeef60SMatthias Ringwald                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
17976774d5c9SMatthias Ringwald                 }
179885aeef60SMatthias Ringwald                 break;
179985aeef60SMatthias Ringwald 
1800828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1801828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1802828a7f7aSMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
1803828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1804828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1805828a7f7aSMatthias Ringwald                 break;
1806828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1807828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1808828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1809828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1810828a7f7aSMatthias Ringwald                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
1811828a7f7aSMatthias Ringwald                 break;
1812efedfb4cSMatthias Ringwald             default:
1813efedfb4cSMatthias Ringwald                 break;
1814efedfb4cSMatthias Ringwald         }
1815efedfb4cSMatthias Ringwald     }
181609e9d05bSMatthias Ringwald #endif
1817efedfb4cSMatthias Ringwald 
181809e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
1819da886c03S[email protected]     // send l2cap con paramter update if necessary
1820da886c03S[email protected]     hci_connections_get_iterator(&it);
1821665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
1822665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1823*c1ab6cc1SMatthias Ringwald         if ((connection->address_type != BD_ADDR_TYPE_LE_PUBLIC) && (connection->address_type != BD_ADDR_TYPE_LE_RANDOM)) continue;
1824b68d7bc3SMatthias Ringwald         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
1825da886c03S[email protected]         switch (connection->le_con_parameter_update_state){
1826b68d7bc3SMatthias Ringwald             case CON_PARAMETER_UPDATE_SEND_REQUEST:
1827b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1828fe8aebe6SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, l2cap_next_sig_id(),
1829b68d7bc3SMatthias Ringwald                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
1830b68d7bc3SMatthias Ringwald                 break;
1831da886c03S[email protected]             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
1832b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
1833b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
1834da886c03S[email protected]                 break;
1835da886c03S[email protected]             case CON_PARAMETER_UPDATE_DENY:
1836b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1837b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
1838da886c03S[email protected]                 break;
1839da886c03S[email protected]             default:
1840da886c03S[email protected]                 break;
1841da886c03S[email protected]         }
1842da886c03S[email protected]     }
18434d7157c3S[email protected] #endif
1844da886c03S[email protected] 
184522c29ab4SMatthias Ringwald     // log_info("l2cap_run: exit");
18462cd0be45Smatthias.ringwald }
18472cd0be45Smatthias.ringwald 
184809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1849fc64f94aSMatthias Ringwald static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
18502df5dadcS[email protected]     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
1851e5ac0afcSMatthias Ringwald         log_info("connection complete con_handle %04x - for channel %p cid 0x%04x", (int) con_handle, channel, channel->local_cid);
18522df5dadcS[email protected]         // success, start l2cap handshake
1853fc64f94aSMatthias Ringwald         channel->con_handle = con_handle;
18542df5dadcS[email protected]         // check remote SSP feature first
18552df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
18562df5dadcS[email protected]     }
18572df5dadcS[email protected] }
18582df5dadcS[email protected] 
18591b9cb13dSMatthias Ringwald static void l2cap_ready_to_connect(l2cap_channel_t * channel){
18601b9cb13dSMatthias Ringwald 
18611b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
186227e0774aSMatthias Ringwald     // assumption: outgoing connection
18631b9cb13dSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
18641b9cb13dSMatthias Ringwald     if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
18651b9cb13dSMatthias Ringwald         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
18661b9cb13dSMatthias Ringwald         channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
18671b9cb13dSMatthias Ringwald         return;
18681b9cb13dSMatthias Ringwald     }
18691b9cb13dSMatthias Ringwald #endif
18701b9cb13dSMatthias Ringwald 
18711b9cb13dSMatthias Ringwald     // fine, go ahead
18721b9cb13dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
18731b9cb13dSMatthias Ringwald }
18741b9cb13dSMatthias Ringwald 
18752df5dadcS[email protected] static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
18762df5dadcS[email protected]     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
18772df5dadcS[email protected] 
18782df5dadcS[email protected]     // we have been waiting for remote supported features, if both support SSP,
1879ac301f95S[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));
1880fc64f94aSMatthias Ringwald     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
18812df5dadcS[email protected]         // request security level 2
18822df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
1883dfce2622SMilanka Ringwald         channel->required_security_level = LEVEL_2;
1884fc64f94aSMatthias Ringwald         gap_request_security_level(channel->con_handle, LEVEL_2);
18852df5dadcS[email protected]         return;
18862df5dadcS[email protected]     }
18871b9cb13dSMatthias Ringwald 
18881b9cb13dSMatthias Ringwald     l2cap_ready_to_connect(channel);
18892df5dadcS[email protected] }
189009e9d05bSMatthias Ringwald #endif
18912df5dadcS[email protected] 
189209e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
18935d18f623SMatthias 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,
1894da144af5SMatthias Ringwald     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
1895da144af5SMatthias Ringwald 
1896da144af5SMatthias Ringwald     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1897da144af5SMatthias Ringwald     if (!channel) {
1898da144af5SMatthias Ringwald         return NULL;
1899da144af5SMatthias Ringwald     }
1900da144af5SMatthias Ringwald 
1901da144af5SMatthias Ringwald     // fill in
1902da144af5SMatthias Ringwald     channel->packet_handler = packet_handler;
19035d18f623SMatthias Ringwald     channel->channel_type   = channel_type;
1904da144af5SMatthias Ringwald     bd_addr_copy(channel->address, address);
1905da144af5SMatthias Ringwald     channel->address_type = address_type;
1906da144af5SMatthias Ringwald     channel->psm = psm;
1907da144af5SMatthias Ringwald     channel->local_mtu  = local_mtu;
1908b37a9357SMatthias Ringwald     channel->remote_mtu = L2CAP_DEFAULT_MTU;
1909da144af5SMatthias Ringwald     channel->required_security_level = security_level;
1910da144af5SMatthias Ringwald 
1911da144af5SMatthias Ringwald     //
1912da144af5SMatthias Ringwald     channel->local_cid = l2cap_next_local_cid();
1913e0780573SMatthias Ringwald     channel->con_handle = HCI_CON_HANDLE_INVALID;
1914da144af5SMatthias Ringwald 
1915da144af5SMatthias Ringwald     // set initial state
1916da144af5SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
1917da144af5SMatthias Ringwald     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
1918da144af5SMatthias Ringwald     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
1919da144af5SMatthias Ringwald     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
192038f62777SMatthias Ringwald 
1921c45d6b2cSMatthias Ringwald     log_info("create channel %p, local_cid 0x%04x", channel, channel->local_cid);
1922e5ac0afcSMatthias Ringwald 
1923da144af5SMatthias Ringwald     return channel;
1924da144af5SMatthias Ringwald }
1925c45d6b2cSMatthias Ringwald 
1926c45d6b2cSMatthias Ringwald static void l2cap_free_channel_entry(l2cap_channel_t * channel){
1927c45d6b2cSMatthias Ringwald     log_info("free channel %p, local_cid 0x%04x", channel, channel->local_cid);
19288f4dd6c1SMatthias Ringwald     // assert all timers are stopped
1929b5bab9c8SMatthias Ringwald     l2cap_stop_rtx(channel);
19308f4dd6c1SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
19318f4dd6c1SMatthias Ringwald     l2cap_ertm_stop_retransmission_timer(channel);
19328f4dd6c1SMatthias Ringwald     l2cap_ertm_stop_monitor_timer(channel);
19338f4dd6c1SMatthias Ringwald #endif
1934b5bab9c8SMatthias Ringwald     // free  memory
1935c45d6b2cSMatthias Ringwald     btstack_memory_l2cap_channel_free(channel);
1936c45d6b2cSMatthias Ringwald }
193709e9d05bSMatthias Ringwald #endif
193809e9d05bSMatthias Ringwald 
193909e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1940da144af5SMatthias Ringwald 
19419077cb15SMatthias Ringwald /**
19429077cb15SMatthias Ringwald  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
19439077cb15SMatthias Ringwald  * @param packet_handler
19449077cb15SMatthias Ringwald  * @param address
19459077cb15SMatthias Ringwald  * @param psm
19469077cb15SMatthias Ringwald  * @param mtu
19479077cb15SMatthias Ringwald  * @param local_cid
19489077cb15SMatthias Ringwald  */
19499077cb15SMatthias Ringwald 
19509d139fbaSMatthias 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){
19519d139fbaSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
19529d139fbaSMatthias Ringwald     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1953da144af5SMatthias Ringwald 
19549d139fbaSMatthias 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);
1955da144af5SMatthias Ringwald 
1956f16129ceSMatthias 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);
1957fc64f94aSMatthias Ringwald     if (!channel) {
19589077cb15SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
19599077cb15SMatthias Ringwald     }
19609077cb15SMatthias Ringwald 
19611b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
19621b9cb13dSMatthias Ringwald     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
19631b9cb13dSMatthias Ringwald #endif
19641b9cb13dSMatthias Ringwald 
19659077cb15SMatthias Ringwald     // add to connections list
1966fc64f94aSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
19679077cb15SMatthias Ringwald 
19689077cb15SMatthias Ringwald     // store local_cid
19699077cb15SMatthias Ringwald     if (out_local_cid){
1970fc64f94aSMatthias Ringwald        *out_local_cid = channel->local_cid;
19719077cb15SMatthias Ringwald     }
19729077cb15SMatthias Ringwald 
19739077cb15SMatthias Ringwald     // check if hci connection is already usable
1974f16129ceSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
19759077cb15SMatthias Ringwald     if (conn){
1976e5ac0afcSMatthias Ringwald         log_info("l2cap_create_channel, hci connection 0x%04x already exists", conn->con_handle);
1977fc64f94aSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
19789077cb15SMatthias Ringwald         // check if remote supported fearures are already received
19799077cb15SMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
1980fc64f94aSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
19819077cb15SMatthias Ringwald         }
19829077cb15SMatthias Ringwald     }
19839077cb15SMatthias Ringwald 
19849077cb15SMatthias Ringwald     l2cap_run();
19859077cb15SMatthias Ringwald 
1986c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
19879077cb15SMatthias Ringwald }
19889077cb15SMatthias Ringwald 
19891ea99aafSMilanka Ringwald void l2cap_disconnect(uint16_t local_cid, uint8_t reason){
1990e0abb8e7S[email protected]     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
1991b35f641cSmatthias.ringwald     // find channel for local_cid
1992b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1993f62db1e3Smatthias.ringwald     if (channel) {
1994e7ff783cSmatthias.ringwald         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1995f62db1e3Smatthias.ringwald     }
19962cd0be45Smatthias.ringwald     // process
19972cd0be45Smatthias.ringwald     l2cap_run();
199843625864Smatthias.ringwald }
19991e6aba47Smatthias.ringwald 
2000afde0c52Smatthias.ringwald static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
2001ceec418aSMatthias Ringwald     // mark all channels before emitting open events as these could trigger new connetion requests to the same device
2002665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
2003665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2004665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2005665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2006fad84cafSMatthias Ringwald         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2007058e3d6bSMatthias Ringwald         if (bd_addr_cmp( channel->address, address) != 0) continue;
2008c22aecc9S[email protected]         // channel for this address found
2009c22aecc9S[email protected]         switch (channel->state){
2010c22aecc9S[email protected]             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2011c22aecc9S[email protected]             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2012ceec418aSMatthias Ringwald                 channel->state = L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD;
2013c22aecc9S[email protected]                 break;
2014c22aecc9S[email protected]             default:
2015c22aecc9S[email protected]                 break;
2016afde0c52Smatthias.ringwald         }
2017afde0c52Smatthias.ringwald     }
2018ceec418aSMatthias Ringwald     // emit and free marked entries. restart loop to deal with list changes
2019ceec418aSMatthias Ringwald     int done = 0;
2020ceec418aSMatthias Ringwald     while (!done) {
2021ceec418aSMatthias Ringwald         done = 1;
2022ceec418aSMatthias Ringwald         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2023ceec418aSMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
2024ceec418aSMatthias Ringwald             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2025fad84cafSMatthias Ringwald             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2026ceec418aSMatthias Ringwald             if (channel->state == L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD){
2027ceec418aSMatthias Ringwald                 done = 0;
2028ceec418aSMatthias Ringwald                 // failure, forward error code
202966a72640SMatthias Ringwald                 l2cap_handle_channel_open_failed(channel, status);
2030ceec418aSMatthias Ringwald                 // discard channel
2031ceec418aSMatthias Ringwald                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2032c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
2033ceec418aSMatthias Ringwald                 break;
2034ceec418aSMatthias Ringwald             }
2035ceec418aSMatthias Ringwald         }
2036ceec418aSMatthias Ringwald     }
2037ceec418aSMatthias Ringwald 
2038afde0c52Smatthias.ringwald }
2039afde0c52Smatthias.ringwald 
2040afde0c52Smatthias.ringwald static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
2041665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
2042665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2043665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2044665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2045fad84cafSMatthias Ringwald         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2046058e3d6bSMatthias Ringwald         if ( ! bd_addr_cmp( channel->address, address) ){
20472df5dadcS[email protected]             l2cap_handle_connection_complete(handle, channel);
2048afde0c52Smatthias.ringwald         }
2049afde0c52Smatthias.ringwald     }
20506fdcc387Smatthias.ringwald     // process
20516fdcc387Smatthias.ringwald     l2cap_run();
2052afde0c52Smatthias.ringwald }
205309e9d05bSMatthias Ringwald #endif
2054b448a0e7Smatthias.ringwald 
20556774d5c9SMatthias Ringwald static bool l2cap_channel_ready_to_send(l2cap_channel_t * channel){
20566774d5c9SMatthias Ringwald     switch (channel->channel_type){
20576774d5c9SMatthias Ringwald #ifdef ENABLE_CLASSIC
20586774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CLASSIC:
20596774d5c9SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2060d89ab698SMatthias Ringwald             // send if we have more data and remote windows isn't full yet
2061d89ab698SMatthias Ringwald             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2062d89ab698SMatthias Ringwald                 if (channel->unacked_frames >= btstack_min(channel->num_stored_tx_frames, channel->remote_tx_window_size)) return false;
20636774d5c9SMatthias Ringwald                 return hci_can_send_acl_classic_packet_now() != 0;
2064d89ab698SMatthias Ringwald             }
2065d89ab698SMatthias Ringwald #endif
2066d89ab698SMatthias Ringwald             if (!channel->waiting_for_can_send_now) return false;
2067d89ab698SMatthias Ringwald             return (hci_can_send_acl_classic_packet_now() != 0);
20686774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
20696774d5c9SMatthias Ringwald             if (!channel->waiting_for_can_send_now) return false;
20706774d5c9SMatthias Ringwald             return hci_can_send_acl_classic_packet_now() != 0;
20716774d5c9SMatthias Ringwald #endif
20726774d5c9SMatthias Ringwald #ifdef ENABLE_BLE
20736774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_FIXED:
20746774d5c9SMatthias Ringwald             if (!channel->waiting_for_can_send_now) return false;
20756774d5c9SMatthias Ringwald             return hci_can_send_acl_le_packet_now() != 0;
20766774d5c9SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
20776774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
20786774d5c9SMatthias Ringwald             if (channel->send_sdu_buffer == NULL) return false;
20796774d5c9SMatthias Ringwald             if (channel->credits_outgoing == 0) return false;
20806774d5c9SMatthias Ringwald             return hci_can_send_acl_le_packet_now() != 0;
20816774d5c9SMatthias Ringwald #endif
20826774d5c9SMatthias Ringwald #endif
20836774d5c9SMatthias Ringwald         default:
20846774d5c9SMatthias Ringwald             return false;
20856774d5c9SMatthias Ringwald     }
20866774d5c9SMatthias Ringwald }
20876774d5c9SMatthias Ringwald 
20886774d5c9SMatthias Ringwald static void l2cap_channel_trigger_send(l2cap_channel_t * channel){
20896774d5c9SMatthias Ringwald     switch (channel->channel_type){
2090d89ab698SMatthias Ringwald #ifdef ENABLE_CLASSIC
2091d89ab698SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CLASSIC:
2092d89ab698SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2093d89ab698SMatthias Ringwald             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2094d89ab698SMatthias Ringwald                 l2cap_ertm_channel_send_information_frame(channel);
2095d89ab698SMatthias Ringwald                 return;
2096d89ab698SMatthias Ringwald             }
2097d89ab698SMatthias Ringwald #endif
2098d89ab698SMatthias Ringwald             channel->waiting_for_can_send_now = 0;
2099d89ab698SMatthias Ringwald             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2100d89ab698SMatthias Ringwald             break;
2101d89ab698SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2102d89ab698SMatthias Ringwald             channel->waiting_for_can_send_now = 0;
2103d89ab698SMatthias Ringwald             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2104d89ab698SMatthias Ringwald             break;
2105d89ab698SMatthias Ringwald #endif
21066774d5c9SMatthias Ringwald #ifdef ENABLE_BLE
2107d89ab698SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_FIXED:
2108d89ab698SMatthias Ringwald             channel->waiting_for_can_send_now = 0;
2109d89ab698SMatthias Ringwald             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2110d89ab698SMatthias Ringwald             break;
21116774d5c9SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
21126774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
21136774d5c9SMatthias Ringwald             l2cap_le_send_pdu(channel);
21146774d5c9SMatthias Ringwald             break;
21156774d5c9SMatthias Ringwald #endif
21166774d5c9SMatthias Ringwald #endif
21176774d5c9SMatthias Ringwald         default:
21186774d5c9SMatthias Ringwald             break;
21196774d5c9SMatthias Ringwald     }
21206774d5c9SMatthias Ringwald }
21216774d5c9SMatthias Ringwald 
212233c40538SMatthias Ringwald static void l2cap_notify_channel_can_send(void){
21236774d5c9SMatthias Ringwald     bool done = false;
21247740e150SMatthias Ringwald     while (!done){
21256774d5c9SMatthias Ringwald         done = true;
212633c40538SMatthias Ringwald         btstack_linked_list_iterator_t it;
212733c40538SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &l2cap_channels);
212833c40538SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
212933c40538SMatthias Ringwald             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
21306774d5c9SMatthias Ringwald             bool ready = l2cap_channel_ready_to_send(channel);
21316774d5c9SMatthias Ringwald             if (!ready) continue;
21326774d5c9SMatthias Ringwald 
21336774d5c9SMatthias Ringwald             // requeue channel for fairness
21347740e150SMatthias Ringwald             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
21357740e150SMatthias Ringwald             btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
21366774d5c9SMatthias Ringwald 
21376774d5c9SMatthias Ringwald             // trigger sending
21386774d5c9SMatthias Ringwald             l2cap_channel_trigger_send(channel);
21396774d5c9SMatthias Ringwald 
21407740e150SMatthias Ringwald             // exit inner loop as we just broke the iterator, but try again
21416774d5c9SMatthias Ringwald             done = false;
21427740e150SMatthias Ringwald             break;
21437740e150SMatthias Ringwald         }
214433c40538SMatthias Ringwald     }
214533c40538SMatthias Ringwald }
214633c40538SMatthias Ringwald 
21472053036dSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
21482053036dSMatthias Ringwald 
21492053036dSMatthias Ringwald static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){
21502053036dSMatthias Ringwald     // open cannot fail for for incoming connections
21512053036dSMatthias Ringwald     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0;
21522053036dSMatthias Ringwald 
21532053036dSMatthias Ringwald     // check state
21542053036dSMatthias Ringwald     switch (channel->state){
21552053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
21562053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
21572053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES:
21582053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
21592053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
21602053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES:
21612053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
21622053036dSMatthias Ringwald         case L2CAP_STATE_CONFIG:
21632053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
21642053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
21652053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE:
2166ceec418aSMatthias Ringwald         case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD:
21672053036dSMatthias Ringwald             return 1;
21682053036dSMatthias Ringwald 
21692053036dSMatthias Ringwald         case L2CAP_STATE_OPEN:
21702053036dSMatthias Ringwald         case L2CAP_STATE_CLOSED:
21712053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES:
21722053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
21732053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY:
21742053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
21752053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
21762053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
21772053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
21782053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
21792053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
21802053036dSMatthias Ringwald         case L2CAP_STATE_INVALID:
21812053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
21822053036dSMatthias Ringwald             return 0;
21836aa7d794SMatthias Ringwald         // no default here, to get a warning about new states
21842053036dSMatthias Ringwald     }
21856aa7d794SMatthias Ringwald     // still, the compiler insists on a return value
21866aa7d794SMatthias Ringwald     return 0;
21872053036dSMatthias Ringwald }
218813aa3e4bSMatthias Ringwald #endif
21892053036dSMatthias Ringwald 
219013aa3e4bSMatthias Ringwald #ifdef ENABLE_CLASSIC
21912053036dSMatthias Ringwald static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){
21922053036dSMatthias Ringwald     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
219366a72640SMatthias Ringwald         l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
21942053036dSMatthias Ringwald     } else {
219566a72640SMatthias Ringwald         l2cap_handle_channel_closed(channel);
21962053036dSMatthias Ringwald     }
2197c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
21982053036dSMatthias Ringwald }
21992053036dSMatthias Ringwald #endif
22002053036dSMatthias Ringwald 
22012cf36df7SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
22022cf36df7SMatthias Ringwald static void l2cap_handle_hci_le_disconnect_event(l2cap_channel_t * channel){
22032cf36df7SMatthias Ringwald     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
22042cf36df7SMatthias Ringwald         l2cap_emit_le_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
22052cf36df7SMatthias Ringwald     } else {
22062cf36df7SMatthias Ringwald         l2cap_emit_le_channel_closed(channel);
22072cf36df7SMatthias Ringwald     }
2208c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
22092cf36df7SMatthias Ringwald }
22102cf36df7SMatthias Ringwald #endif
22112053036dSMatthias Ringwald 
2212d9a7306aSMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
2213afde0c52Smatthias.ringwald 
22145774a392SMatthias Ringwald     UNUSED(packet_type); // ok: registered with hci_event_callback_registration
22155774a392SMatthias Ringwald     UNUSED(cid);         // ok: there is no channel
22165774a392SMatthias Ringwald     UNUSED(size);        // ok: fixed format events read from HCI buffer
22179ec2630cSMatthias Ringwald 
22185774a392SMatthias Ringwald #ifdef ENABLE_CLASSIC
2219afde0c52Smatthias.ringwald     bd_addr_t address;
22202d00edd4Smatthias.ringwald     int hci_con_used;
22215774a392SMatthias Ringwald #endif
22225774a392SMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
22235774a392SMatthias Ringwald     hci_con_handle_t handle;
222409e9d05bSMatthias Ringwald     btstack_linked_list_iterator_t it;
22255774a392SMatthias Ringwald #endif
2226afde0c52Smatthias.ringwald 
22270e2df43fSMatthias Ringwald     switch(hci_event_packet_get_type(packet)){
2228afde0c52Smatthias.ringwald 
222909e9d05bSMatthias Ringwald         // Notify channel packet handler if they can send now
223009e9d05bSMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
223109e9d05bSMatthias Ringwald         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
2232eea99214SMatthias Ringwald         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
223309e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
223409e9d05bSMatthias Ringwald             l2cap_notify_channel_can_send();
223509e9d05bSMatthias Ringwald             break;
223609e9d05bSMatthias Ringwald 
223709e9d05bSMatthias Ringwald         case HCI_EVENT_COMMAND_STATUS:
2238ece97caeSMatthias Ringwald #ifdef ENABLE_CLASSIC
2239ece97caeSMatthias Ringwald             // check command status for create connection for errors
2240ece97caeSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
2241ece97caeSMatthias Ringwald                 // cache outgoing address and reset
2242ece97caeSMatthias Ringwald                 memcpy(address, l2cap_outgoing_classic_addr, 6);
2243ece97caeSMatthias Ringwald                 memset(l2cap_outgoing_classic_addr, 0, 6);
2244ece97caeSMatthias Ringwald                 // error => outgoing connection failed
2245ece97caeSMatthias Ringwald                 uint8_t status = hci_event_command_status_get_status(packet);
2246ece97caeSMatthias Ringwald                 if (status){
2247ece97caeSMatthias Ringwald                     l2cap_handle_connection_failed_for_addr(address, status);
2248ece97caeSMatthias Ringwald                 }
2249ece97caeSMatthias Ringwald             }
2250ece97caeSMatthias Ringwald #endif
225109e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
225209e9d05bSMatthias Ringwald             break;
225309e9d05bSMatthias Ringwald 
225409e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2255afde0c52Smatthias.ringwald         // handle connection complete events
2256afde0c52Smatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
2257724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], address);
2258afde0c52Smatthias.ringwald             if (packet[2] == 0){
2259f8fbdce0SMatthias Ringwald                 handle = little_endian_read_16(packet, 3);
2260afde0c52Smatthias.ringwald                 l2cap_handle_connection_success_for_addr(address, handle);
2261afde0c52Smatthias.ringwald             } else {
2262afde0c52Smatthias.ringwald                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
2263afde0c52Smatthias.ringwald             }
2264afde0c52Smatthias.ringwald             break;
2265afde0c52Smatthias.ringwald 
2266afde0c52Smatthias.ringwald         // handle successful create connection cancel command
2267afde0c52Smatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
2268073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
2269afde0c52Smatthias.ringwald                 if (packet[5] == 0){
2270724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[6], address);
2271afde0c52Smatthias.ringwald                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
2272afde0c52Smatthias.ringwald                     l2cap_handle_connection_failed_for_addr(address, 0x16);
227303cfbabcSmatthias.ringwald                 }
22741e6aba47Smatthias.ringwald             }
227539d59809Smatthias.ringwald             l2cap_run();    // try sending signaling packets first
227639d59809Smatthias.ringwald             break;
227709e9d05bSMatthias Ringwald #endif
227827a923d0Smatthias.ringwald 
22792053036dSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
22801e6aba47Smatthias.ringwald         // handle disconnection complete events
2281afde0c52Smatthias.ringwald         case HCI_EVENT_DISCONNECTION_COMPLETE:
2282d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
22832053036dSMatthias Ringwald             // send l2cap open failed or closed events for all channels on this handle and free them
2284665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2285665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2286665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2287fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2288fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
2289665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
2290421cb104SMatthias Ringwald                 switch(channel->channel_type){
2291421cb104SMatthias Ringwald #ifdef ENABLE_CLASSIC
2292421cb104SMatthias Ringwald                     case L2CAP_CHANNEL_TYPE_CLASSIC:
22932053036dSMatthias Ringwald                         l2cap_handle_hci_disconnect_event(channel);
2294421cb104SMatthias Ringwald                         break;
229509e9d05bSMatthias Ringwald #endif
2296a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2297421cb104SMatthias Ringwald                     case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
22982cf36df7SMatthias Ringwald                         l2cap_handle_hci_le_disconnect_event(channel);
2299afde0c52Smatthias.ringwald                         break;
23002053036dSMatthias Ringwald #endif
2301421cb104SMatthias Ringwald                     default:
2302421cb104SMatthias Ringwald                         break;
2303421cb104SMatthias Ringwald                 }
2304421cb104SMatthias Ringwald             }
23059909e5e4SMatthias Ringwald             break;
2306421cb104SMatthias Ringwald #endif
2307fcadd0caSmatthias.ringwald 
23089909e5e4SMatthias Ringwald 
2309ee091cf1Smatthias.ringwald         // HCI Connection Timeouts
231009e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2311afde0c52Smatthias.ringwald         case L2CAP_EVENT_TIMEOUT_CHECK:
2312f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
2313bd04d84aSMatthias Ringwald             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
231480ca58a0Smatthias.ringwald             if (hci_authentication_active_for_handle(handle)) break;
23152d00edd4Smatthias.ringwald             hci_con_used = 0;
2316665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2317665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2318665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2319fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2320fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
23212d00edd4Smatthias.ringwald                 hci_con_used = 1;
2322c22aecc9S[email protected]                 break;
2323ee091cf1Smatthias.ringwald             }
23242d00edd4Smatthias.ringwald             if (hci_con_used) break;
2325d94d3cafS[email protected]             if (!hci_can_send_command_packet_now()) break;
23269edc8742Smatthias.ringwald             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
2327afde0c52Smatthias.ringwald             break;
2328ee091cf1Smatthias.ringwald 
2329df3354fcS[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2330f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
2331665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2332665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2333665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2334fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2335fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
2336e5ac0afcSMatthias Ringwald                 log_info("remote supported features, channel %p, cid %04x - state %u", channel, channel->local_cid, channel->state);
23372df5dadcS[email protected]                 l2cap_handle_remote_supported_features_received(channel);
2338df3354fcS[email protected]             }
2339c22aecc9S[email protected]             break;
2340df3354fcS[email protected] 
23415611a760SMatthias Ringwald         case GAP_EVENT_SECURITY_LEVEL:
2342f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
2343e5ac0afcSMatthias Ringwald             log_info("l2cap - security level update for handle 0x%04x", handle);
2344665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2345665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2346665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2347fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2348fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
23495533f01eS[email protected] 
2350e569dfd9SMatthias Ringwald                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
23515533f01eS[email protected]                 gap_security_level_t required_level = channel->required_security_level;
23525533f01eS[email protected] 
2353e5ac0afcSMatthias Ringwald                 log_info("channel %p, cid %04x - state %u: actual %u >= required %u?", channel, channel->local_cid, channel->state, actual_level, required_level);
2354dfce2622SMilanka Ringwald 
2355df3354fcS[email protected]                 switch (channel->state){
2356df3354fcS[email protected]                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
23575533f01eS[email protected]                         if (actual_level >= required_level){
235852606043SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
235952606043SMatthias Ringwald                             // we need to know if ERTM is supported before sending a config response
236052606043SMatthias Ringwald                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
236152606043SMatthias Ringwald                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
236252606043SMatthias Ringwald                             channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
236352606043SMatthias Ringwald #else
2364f85a9399S[email protected]                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
236544276248SMatthias Ringwald                             l2cap_emit_incoming_connection(channel);
236652606043SMatthias Ringwald #endif
23671eb2563eS[email protected]                         } else {
2368775ecc36SMatthias Ringwald                             channel->reason = 0x0003; // security block
23691eb2563eS[email protected]                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
23701eb2563eS[email protected]                         }
2371df3354fcS[email protected]                         break;
2372df3354fcS[email protected] 
2373df3354fcS[email protected]                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
23745533f01eS[email protected]                         if (actual_level >= required_level){
23751b9cb13dSMatthias Ringwald                             l2cap_ready_to_connect(channel);
2376df3354fcS[email protected]                         } else {
2377df3354fcS[email protected]                             // disconnnect, authentication not good enough
2378df3354fcS[email protected]                             hci_disconnect_security_block(handle);
2379df3354fcS[email protected]                         }
2380df3354fcS[email protected]                         break;
2381df3354fcS[email protected] 
2382df3354fcS[email protected]                     default:
2383df3354fcS[email protected]                         break;
2384df3354fcS[email protected]                 }
2385f85a9399S[email protected]             }
2386f85a9399S[email protected]             break;
238709e9d05bSMatthias Ringwald #endif
2388f85a9399S[email protected] 
2389afde0c52Smatthias.ringwald         default:
2390afde0c52Smatthias.ringwald             break;
2391afde0c52Smatthias.ringwald     }
2392afde0c52Smatthias.ringwald 
2393bd63148eS[email protected]     l2cap_run();
23941e6aba47Smatthias.ringwald }
23951e6aba47Smatthias.ringwald 
2396e74c5f58SMatthias 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){
23974cf56b4aSmatthias.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."
23982b360848Smatthias.ringwald     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
23992b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].handle = handle;
24002b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].code = code;
24012b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].sig_id = sig_id;
2402e74c5f58SMatthias Ringwald         signaling_responses[signaling_responses_pending].cid = cid;
24032b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].data = data;
24042b360848Smatthias.ringwald         signaling_responses_pending++;
24052b360848Smatthias.ringwald         l2cap_run();
24062b360848Smatthias.ringwald     }
24072b360848Smatthias.ringwald }
24082b360848Smatthias.ringwald 
240909e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
241009e9d05bSMatthias Ringwald static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
241109e9d05bSMatthias Ringwald     channel->remote_sig_id = identifier;
241209e9d05bSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
241309e9d05bSMatthias Ringwald     l2cap_run();
241409e9d05bSMatthias Ringwald }
241509e9d05bSMatthias Ringwald 
2416b35f641cSmatthias.ringwald static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
2417645658c9Smatthias.ringwald 
24189da54300S[email protected]     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
2419645658c9Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
2420645658c9Smatthias.ringwald     if (!service) {
2421645658c9Smatthias.ringwald         // 0x0002 PSM not supported
2422e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2423645658c9Smatthias.ringwald         return;
2424645658c9Smatthias.ringwald     }
2425645658c9Smatthias.ringwald 
24265061f3afS[email protected]     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
2427645658c9Smatthias.ringwald     if (!hci_connection) {
24282b360848Smatthias.ringwald         //
24299da54300S[email protected]         log_error("no hci_connection for handle %u", handle);
2430645658c9Smatthias.ringwald         return;
2431645658c9Smatthias.ringwald     }
24322bd8b7e7S[email protected] 
2433645658c9Smatthias.ringwald     // alloc structure
24349da54300S[email protected]     // log_info("l2cap_handle_connection_request register channel");
2435f16129ceSMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, hci_connection->address, BD_ADDR_TYPE_ACL,
2436da144af5SMatthias Ringwald     psm, service->mtu, service->required_security_level);
24372b360848Smatthias.ringwald     if (!channel){
24382b360848Smatthias.ringwald         // 0x0004 No resources available
2439e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
24402b360848Smatthias.ringwald         return;
24412b360848Smatthias.ringwald     }
2442da144af5SMatthias Ringwald 
2443fc64f94aSMatthias Ringwald     channel->con_handle = handle;
2444b35f641cSmatthias.ringwald     channel->remote_cid = source_cid;
2445b1988dceSmatthias.ringwald     channel->remote_sig_id = sig_id;
2446645658c9Smatthias.ringwald 
2447f53da564S[email protected]     // limit local mtu to max acl packet length - l2cap header
24482985cb84Smatthias.ringwald     if (channel->local_mtu > l2cap_max_mtu()) {
24492985cb84Smatthias.ringwald         channel->local_mtu = l2cap_max_mtu();
24509775e25bSmatthias.ringwald     }
24519775e25bSmatthias.ringwald 
2452645658c9Smatthias.ringwald     // set initial state
2453df3354fcS[email protected]     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
2454a24785d0SMatthias Ringwald     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
2455e405ae81Smatthias.ringwald 
2456645658c9Smatthias.ringwald     // add to connections list
2457665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
2458645658c9Smatthias.ringwald 
2459f85a9399S[email protected]     // assert security requirements
24601eb2563eS[email protected]     gap_request_security_level(handle, channel->required_security_level);
2461e405ae81Smatthias.ringwald }
2462645658c9Smatthias.ringwald 
2463ce8f182eSMatthias Ringwald void l2cap_accept_connection(uint16_t local_cid){
2464e0abb8e7S[email protected]     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
2465b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2466e405ae81Smatthias.ringwald     if (!channel) {
2467ce8f182eSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
2468e405ae81Smatthias.ringwald         return;
2469e405ae81Smatthias.ringwald     }
2470e405ae81Smatthias.ringwald 
247143ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
247243ec931dSMatthias Ringwald     // configure L2CAP Basic mode
247343ec931dSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
247443ec931dSMatthias Ringwald #endif
247543ec931dSMatthias Ringwald 
2476552d92a1Smatthias.ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
2477e405ae81Smatthias.ringwald 
2478552d92a1Smatthias.ringwald     // process
2479552d92a1Smatthias.ringwald     l2cap_run();
2480e405ae81Smatthias.ringwald }
2481645658c9Smatthias.ringwald 
24827ef6a7bbSMatthias Ringwald void l2cap_decline_connection(uint16_t local_cid){
24837ef6a7bbSMatthias Ringwald     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
2484b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
2485e405ae81Smatthias.ringwald     if (!channel) {
2486ce8f182eSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
2487e405ae81Smatthias.ringwald         return;
2488e405ae81Smatthias.ringwald     }
2489e7ff783cSmatthias.ringwald     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
24907ef6a7bbSMatthias Ringwald     channel->reason = 0x04; // no resources available
2491e7ff783cSmatthias.ringwald     l2cap_run();
2492645658c9Smatthias.ringwald }
2493645658c9Smatthias.ringwald 
2494e9cfb251SMatthias Ringwald // @pre command len is valid, see check in l2cap_signaling_handler_channel
24957f02f414SMatthias Ringwald static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
2496b1988dceSmatthias.ringwald 
2497fcb125edSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2498fcb125edSMatthias Ringwald     uint8_t use_fcs = 1;
2499fcb125edSMatthias Ringwald #endif
2500fcb125edSMatthias Ringwald 
2501b1988dceSmatthias.ringwald     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2502b1988dceSmatthias.ringwald 
2503f8fbdce0SMatthias Ringwald     uint16_t flags = little_endian_read_16(command, 6);
250463a7246aSmatthias.ringwald     if (flags & 1) {
250563a7246aSmatthias.ringwald         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
250663a7246aSmatthias.ringwald     }
250763a7246aSmatthias.ringwald 
25082784b77dSmatthias.ringwald     // accept the other's configuration options
2509f8fbdce0SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
25103de7c0caSmatthias.ringwald     uint16_t pos     = 8;
25113de7c0caSmatthias.ringwald     while (pos < end_pos){
251263a7246aSmatthias.ringwald         uint8_t option_hint = command[pos] >> 7;
251363a7246aSmatthias.ringwald         uint8_t option_type = command[pos] & 0x7f;
25143844aeadSMatthias Ringwald         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
251563a7246aSmatthias.ringwald         pos++;
25161dc511deSmatthias.ringwald         uint8_t length = command[pos++];
25171dc511deSmatthias.ringwald         // MTU { type(8): 1, len(8):2, MTU(16) }
2518*c1ab6cc1SMatthias Ringwald         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) && (length == 2)){
2519f8fbdce0SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, pos);
25203844aeadSMatthias Ringwald             log_info("Remote MTU %u", channel->remote_mtu);
25219d139fbaSMatthias Ringwald             if (channel->remote_mtu > l2cap_max_mtu()){
25229d139fbaSMatthias Ringwald                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
25239d139fbaSMatthias Ringwald                 channel->remote_mtu = l2cap_max_mtu();
25249d139fbaSMatthias Ringwald             }
252563a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
252663a7246aSmatthias.ringwald         }
25270fe7a9d0S[email protected]         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
2528*c1ab6cc1SMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT && (length == 2)){
2529f8fbdce0SMatthias Ringwald             channel->flush_timeout = little_endian_read_16(command, pos);
25303844aeadSMatthias Ringwald             log_info("Flush timeout: %u ms", channel->flush_timeout);
25310fe7a9d0S[email protected]         }
2532f2fa388dSMatthias Ringwald 
25336dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
25346dca2a0cSMatthias Ringwald         // Retransmission and Flow Control Option
2535671fb338SMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
25363232a1c6SMatthias Ringwald             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
2537ac8f1300SMatthias Ringwald             switch(channel->mode){
2538ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
253925cd60d3SMatthias Ringwald                     // Store remote config
2540bbc0a9e7SMatthias Ringwald                     channel->remote_tx_window_size = command[pos+1];
2541bbc0a9e7SMatthias Ringwald                     channel->remote_max_transmit   = command[pos+2];
2542bbc0a9e7SMatthias Ringwald                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
2543bbc0a9e7SMatthias Ringwald                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
25443844aeadSMatthias Ringwald                     channel->remote_mps = little_endian_read_16(command, pos + 7);
25453844aeadSMatthias Ringwald                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
2546bbc0a9e7SMatthias Ringwald                         channel->remote_tx_window_size,
2547bbc0a9e7SMatthias Ringwald                         channel->remote_max_transmit,
2548bbc0a9e7SMatthias Ringwald                         channel->remote_retransmission_timeout_ms,
25493844aeadSMatthias Ringwald                         channel->remote_monitor_timeout_ms,
25503844aeadSMatthias Ringwald                         channel->remote_mps);
255125cd60d3SMatthias Ringwald                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
255225cd60d3SMatthias Ringwald                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
255325cd60d3SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2554ac8f1300SMatthias Ringwald                     } else {
2555b8134563SMatthias Ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2556ac8f1300SMatthias Ringwald                     }
2557ac8f1300SMatthias Ringwald                     break;
2558ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
2559ac8f1300SMatthias Ringwald                     switch (mode){
2560ac8f1300SMatthias Ringwald                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2561ac8f1300SMatthias Ringwald                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
2562ac8f1300SMatthias Ringwald                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
2563ac8f1300SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2564ac8f1300SMatthias Ringwald                             }
2565ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
2566ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
2567ac8f1300SMatthias Ringwald                             break;
2568ac8f1300SMatthias Ringwald                         default: // case L2CAP_CHANNEL_MODE_BASIC:
2569ac8f1300SMatthias Ringwald                             // TODO store and evaluate configuration
2570b8134563SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2571ac8f1300SMatthias Ringwald                             break;
2572ac8f1300SMatthias Ringwald                     }
2573ac8f1300SMatthias Ringwald                     break;
2574ac8f1300SMatthias Ringwald                 default:
2575ac8f1300SMatthias Ringwald                     break;
2576ac8f1300SMatthias Ringwald             }
25773232a1c6SMatthias Ringwald         }
25786574158aSMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
2579fcb125edSMatthias Ringwald             use_fcs = command[pos];
25806574158aSMatthias Ringwald         }
25816dca2a0cSMatthias Ringwald #endif
258263a7246aSmatthias.ringwald         // check for unknown options
2583*c1ab6cc1SMatthias Ringwald         if ((option_hint == 0) && ((option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
2584c177a91cS[email protected]             log_info("l2cap cid %u, unknown options", channel->local_cid);
258563a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
25861dc511deSmatthias.ringwald         }
25871dc511deSmatthias.ringwald         pos += length;
25881dc511deSmatthias.ringwald     }
2589fcb125edSMatthias Ringwald 
2590fcb125edSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2591fcb125edSMatthias Ringwald         // "FCS" has precedence over "No FCS"
2592fcb125edSMatthias Ringwald         uint8_t update = channel->fcs_option || use_fcs;
2593fcb125edSMatthias Ringwald         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
2594fcb125edSMatthias Ringwald         channel->fcs_option = update;
259567f8f607SMatthias Ringwald         // If ERTM mandatory, but remote didn't send Retransmission and Flowcontrol options -> disconnect
259667f8f607SMatthias Ringwald         if (((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM) == 0) & (channel->ertm_mandatory)){
259767f8f607SMatthias Ringwald             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
259867f8f607SMatthias Ringwald         }
2599fcb125edSMatthias Ringwald #endif
26002784b77dSmatthias.ringwald }
26012784b77dSmatthias.ringwald 
2602e9cfb251SMatthias Ringwald // @pre command len is valid, see check in l2cap_signaling_handler_channel
2603f2fa388dSMatthias Ringwald static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
2604f2fa388dSMatthias Ringwald     log_info("l2cap_signaling_handle_configure_response");
26053232a1c6SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
26063232a1c6SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2607f2fa388dSMatthias Ringwald     uint16_t pos     = 10;
26083232a1c6SMatthias Ringwald     while (pos < end_pos){
26093232a1c6SMatthias Ringwald         uint8_t option_hint = command[pos] >> 7;
26103232a1c6SMatthias Ringwald         uint8_t option_type = command[pos] & 0x7f;
2611fcb125edSMatthias Ringwald         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
26123232a1c6SMatthias Ringwald         pos++;
26133232a1c6SMatthias Ringwald         uint8_t length = command[pos++];
26143232a1c6SMatthias Ringwald 
26153232a1c6SMatthias Ringwald         // Retransmission and Flow Control Option
2616671fb338SMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2617ac8f1300SMatthias Ringwald             switch (channel->mode){
2618ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2619f2fa388dSMatthias Ringwald                     if (channel->ertm_mandatory){
2620ac8f1300SMatthias Ringwald                         // ??
2621f2fa388dSMatthias Ringwald                     } else {
2622ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
2623ac8f1300SMatthias Ringwald                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
262466a72640SMatthias Ringwald                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
2625f2fa388dSMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
26263232a1c6SMatthias Ringwald                         }
26273232a1c6SMatthias Ringwald                     }
2628ac8f1300SMatthias Ringwald                     break;
2629ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
2630ac8f1300SMatthias Ringwald                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2631ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
2632ac8f1300SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2633ac8f1300SMatthias Ringwald                     }
2634ac8f1300SMatthias Ringwald                     break;
2635ac8f1300SMatthias Ringwald                 default:
2636ac8f1300SMatthias Ringwald                     break;
26373232a1c6SMatthias Ringwald             }
2638f2fa388dSMatthias Ringwald         }
26393232a1c6SMatthias Ringwald 
26403232a1c6SMatthias Ringwald         // check for unknown options
2641671fb338SMatthias Ringwald         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
26423232a1c6SMatthias Ringwald             log_info("l2cap cid %u, unknown options", channel->local_cid);
26433232a1c6SMatthias Ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
26443232a1c6SMatthias Ringwald         }
26453232a1c6SMatthias Ringwald 
26463232a1c6SMatthias Ringwald         pos += length;
26473232a1c6SMatthias Ringwald     }
2648688f9764SMatthias Ringwald #else
26495774a392SMatthias Ringwald     UNUSED(channel);  // ok: no code
26505774a392SMatthias Ringwald     UNUSED(result);   // ok: no code
26515774a392SMatthias Ringwald     UNUSED(command);  // ok: no code
26523232a1c6SMatthias Ringwald #endif
26533232a1c6SMatthias Ringwald }
26543232a1c6SMatthias Ringwald 
2655fa8473a4Smatthias.ringwald static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
26569da54300S[email protected]     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
265773cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
265873cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
2659019f9b43SMatthias Ringwald     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
2660019f9b43SMatthias Ringwald     if (channel->state == L2CAP_STATE_OPEN) return 0;
2661fa8473a4Smatthias.ringwald     return 1;
2662fa8473a4Smatthias.ringwald }
2663fa8473a4Smatthias.ringwald 
2664fa8473a4Smatthias.ringwald 
2665e9cfb251SMatthias Ringwald // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
26667f02f414SMatthias Ringwald static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
26671e6aba47Smatthias.ringwald 
266800d93d79Smatthias.ringwald     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
266900d93d79Smatthias.ringwald     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2670e9cfb251SMatthias Ringwald     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
267138e5900eSmatthias.ringwald     uint16_t result = 0;
26721e6aba47Smatthias.ringwald 
26739da54300S[email protected]     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
2674b35f641cSmatthias.ringwald 
26759a011532Smatthias.ringwald     // handle DISCONNECT REQUESTS seperately
26769a011532Smatthias.ringwald     if (code == DISCONNECTION_REQUEST){
26779a011532Smatthias.ringwald         switch (channel->state){
2678fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
26799a011532Smatthias.ringwald             case L2CAP_STATE_OPEN:
26802b83fb7dSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
26819a011532Smatthias.ringwald             case L2CAP_STATE_WAIT_DISCONNECT:
26829a011532Smatthias.ringwald                 l2cap_handle_disconnect_request(channel, identifier);
26839a011532Smatthias.ringwald                 break;
26849a011532Smatthias.ringwald 
26859a011532Smatthias.ringwald             default:
26869a011532Smatthias.ringwald                 // ignore in other states
26879a011532Smatthias.ringwald                 break;
26889a011532Smatthias.ringwald         }
26899a011532Smatthias.ringwald         return;
26909a011532Smatthias.ringwald     }
26919a011532Smatthias.ringwald 
269256081214Smatthias.ringwald     // @STATEMACHINE(l2cap)
26931e6aba47Smatthias.ringwald     switch (channel->state) {
26941e6aba47Smatthias.ringwald 
26951e6aba47Smatthias.ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
26961e6aba47Smatthias.ringwald             switch (code){
26971e6aba47Smatthias.ringwald                 case CONNECTION_RESPONSE:
2698e9cfb251SMatthias Ringwald                     if (cmd_len < 8){
2699e9cfb251SMatthias Ringwald                         // command imcomplete
2700e9cfb251SMatthias Ringwald                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2701e9cfb251SMatthias Ringwald                         break;
2702e9cfb251SMatthias Ringwald                     }
27035932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2704f8fbdce0SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
270538e5900eSmatthias.ringwald                     switch (result) {
270638e5900eSmatthias.ringwald                         case 0:
2707169f8b28Smatthias.ringwald                             // successful connection
2708f8fbdce0SMatthias Ringwald                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2709fa8473a4Smatthias.ringwald                             channel->state = L2CAP_STATE_CONFIG;
271028ca2b46S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
271138e5900eSmatthias.ringwald                             break;
271238e5900eSmatthias.ringwald                         case 1:
27135932bd7cS[email protected]                             // connection pending. get some coffee, but start the ERTX
27145932bd7cS[email protected]                             l2cap_start_ertx(channel);
271538e5900eSmatthias.ringwald                             break;
271638e5900eSmatthias.ringwald                         default:
2717eb920dbeSmatthias.ringwald                             // channel closed
2718eb920dbeSmatthias.ringwald                             channel->state = L2CAP_STATE_CLOSED;
2719f32b992eSmatthias.ringwald                             // map l2cap connection response result to BTstack status enumeration
272066a72640SMatthias Ringwald                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
2721eb920dbeSmatthias.ringwald 
2722eb920dbeSmatthias.ringwald                             // drop link key if security block
2723*c1ab6cc1SMatthias Ringwald                             if ((L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result) == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
272415a95bd5SMatthias Ringwald                                 gap_drop_link_key_for_bd_addr(channel->address);
2725eb920dbeSmatthias.ringwald                             }
2726eb920dbeSmatthias.ringwald 
2727eb920dbeSmatthias.ringwald                             // discard channel
2728665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2729c45d6b2cSMatthias Ringwald                             l2cap_free_channel_entry(channel);
273038e5900eSmatthias.ringwald                             break;
27311e6aba47Smatthias.ringwald                     }
27321e6aba47Smatthias.ringwald                     break;
273338e5900eSmatthias.ringwald 
273438e5900eSmatthias.ringwald                 default:
27351e6aba47Smatthias.ringwald                     //@TODO: implement other signaling packets
273638e5900eSmatthias.ringwald                     break;
27371e6aba47Smatthias.ringwald             }
27381e6aba47Smatthias.ringwald             break;
27391e6aba47Smatthias.ringwald 
2740fa8473a4Smatthias.ringwald         case L2CAP_STATE_CONFIG:
2741ae280e73Smatthias.ringwald             switch (code) {
2742ae280e73Smatthias.ringwald                 case CONFIGURE_REQUEST:
2743e9cfb251SMatthias Ringwald                     if (cmd_len < 4){
2744e9cfb251SMatthias Ringwald                         // command incomplete
2745e9cfb251SMatthias Ringwald                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2746e9cfb251SMatthias Ringwald                         break;
2747e9cfb251SMatthias Ringwald                     }
274828ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
2749ae280e73Smatthias.ringwald                     l2cap_signaling_handle_configure_request(channel, command);
275063a7246aSmatthias.ringwald                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
275163a7246aSmatthias.ringwald                         // only done if continuation not set
275263a7246aSmatthias.ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
275363a7246aSmatthias.ringwald                     }
2754ae280e73Smatthias.ringwald                     break;
27551e6aba47Smatthias.ringwald                 case CONFIGURE_RESPONSE:
2756e9cfb251SMatthias Ringwald                     if (cmd_len < 6){
2757e9cfb251SMatthias Ringwald                         // command incomplete
2758e9cfb251SMatthias Ringwald                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2759e9cfb251SMatthias Ringwald                         break;
2760e9cfb251SMatthias Ringwald                     }
2761e9cfb251SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
27625932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2763f2fa388dSMatthias Ringwald                     l2cap_signaling_handle_configure_response(channel, result, command);
27645932bd7cS[email protected]                     switch (result){
27655932bd7cS[email protected]                         case 0: // success
27665932bd7cS[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
27675932bd7cS[email protected]                             break;
27685932bd7cS[email protected]                         case 4: // pending
27695932bd7cS[email protected]                             l2cap_start_ertx(channel);
27705932bd7cS[email protected]                             break;
27715932bd7cS[email protected]                         default:
2772a32d6a03SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2773a32d6a03SMatthias Ringwald                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
2774a32d6a03SMatthias Ringwald                                 // remote does not offer ertm but it's required
2775a32d6a03SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2776a32d6a03SMatthias Ringwald                                 break;
2777a32d6a03SMatthias Ringwald                             }
2778a32d6a03SMatthias Ringwald #endif
2779fe9d8984S[email protected]                             // retry on negative result
2780fe9d8984S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2781fe9d8984S[email protected]                             break;
2782fe9d8984S[email protected]                     }
27835a67bd4aSmatthias.ringwald                     break;
27845a67bd4aSmatthias.ringwald                 default:
27855a67bd4aSmatthias.ringwald                     break;
27861e6aba47Smatthias.ringwald             }
2787fa8473a4Smatthias.ringwald             if (l2cap_channel_ready_for_open(channel)){
27882e4c1850SMatthias Ringwald 
27892e4c1850SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
27902e4c1850SMatthias Ringwald                 // assert that packet can be stored in fragment buffers in ertm
27912e4c1850SMatthias Ringwald                 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
27922e4c1850SMatthias Ringwald                     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
27932e4c1850SMatthias Ringwald                     uint16_t usable_mtu = channel->num_tx_buffers == 1 ? effective_mps : channel->num_tx_buffers * effective_mps - 2;
27942e4c1850SMatthias Ringwald                     if (usable_mtu < channel->remote_mtu){
27952e4c1850SMatthias Ringwald                         log_info("Remote MTU %u > max storable ERTM packet, only using MTU = %u", channel->remote_mtu, usable_mtu);
27962e4c1850SMatthias Ringwald                         channel->remote_mtu = usable_mtu;
27972e4c1850SMatthias Ringwald                     }
27982e4c1850SMatthias Ringwald                 }
27992e4c1850SMatthias Ringwald #endif
2800fa8473a4Smatthias.ringwald                 // for open:
28015a67bd4aSmatthias.ringwald                 channel->state = L2CAP_STATE_OPEN;
2802fa8473a4Smatthias.ringwald                 l2cap_emit_channel_opened(channel, 0);
2803c8e4258aSmatthias.ringwald             }
2804c8e4258aSmatthias.ringwald             break;
2805f62db1e3Smatthias.ringwald 
2806f62db1e3Smatthias.ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
2807f62db1e3Smatthias.ringwald             switch (code) {
2808f62db1e3Smatthias.ringwald                 case DISCONNECTION_RESPONSE:
280927a923d0Smatthias.ringwald                     l2cap_finialize_channel_close(channel);
281027a923d0Smatthias.ringwald                     break;
28115a67bd4aSmatthias.ringwald                 default:
28125a67bd4aSmatthias.ringwald                     //@TODO: implement other signaling packets
28135a67bd4aSmatthias.ringwald                     break;
281427a923d0Smatthias.ringwald             }
281527a923d0Smatthias.ringwald             break;
281684836b65Smatthias.ringwald 
281784836b65Smatthias.ringwald         case L2CAP_STATE_CLOSED:
281884836b65Smatthias.ringwald             // @TODO handle incoming requests
281984836b65Smatthias.ringwald             break;
282084836b65Smatthias.ringwald 
282184836b65Smatthias.ringwald         case L2CAP_STATE_OPEN:
282284836b65Smatthias.ringwald             //@TODO: implement other signaling packets, e.g. re-configure
282384836b65Smatthias.ringwald             break;
282410642e45Smatthias.ringwald         default:
282510642e45Smatthias.ringwald             break;
282627a923d0Smatthias.ringwald     }
28279da54300S[email protected]     // log_info("new state %u", channel->state);
282827a923d0Smatthias.ringwald }
282927a923d0Smatthias.ringwald 
283000d93d79Smatthias.ringwald 
2831ed2ed8e1SMatthias Ringwald // @pre command len is valid, see check in l2cap_acl_classic_handler
28327f02f414SMatthias Ringwald static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
283300d93d79Smatthias.ringwald 
28341b9cb13dSMatthias Ringwald     btstack_linked_list_iterator_t it;
28351b9cb13dSMatthias Ringwald 
283600d93d79Smatthias.ringwald     // get code, signalind identifier and command len
283700d93d79Smatthias.ringwald     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
283800d93d79Smatthias.ringwald     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
28390493bf3aSMatthias Ringwald     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
284000d93d79Smatthias.ringwald 
28411b9cb13dSMatthias Ringwald     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
2842*c1ab6cc1SMatthias Ringwald     if ((code < 1) || code == ECHO_RESPONSE || code > INFORMATION_RESPONSE){
2843e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
284400d93d79Smatthias.ringwald         return;
284500d93d79Smatthias.ringwald     }
284600d93d79Smatthias.ringwald 
284700d93d79Smatthias.ringwald     // general commands without an assigned channel
284800d93d79Smatthias.ringwald     switch(code) {
284900d93d79Smatthias.ringwald 
28500493bf3aSMatthias Ringwald         case CONNECTION_REQUEST:
28510493bf3aSMatthias Ringwald             if (cmd_len == 4){
2852f8fbdce0SMatthias Ringwald                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2853f8fbdce0SMatthias Ringwald                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
285400d93d79Smatthias.ringwald                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
28550493bf3aSMatthias Ringwald             } else {
28560493bf3aSMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
285700d93d79Smatthias.ringwald             }
28580493bf3aSMatthias Ringwald             return;
285900d93d79Smatthias.ringwald 
28602b360848Smatthias.ringwald         case ECHO_REQUEST:
2861e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
28622b83fb7dSmatthias.ringwald             return;
286300d93d79Smatthias.ringwald 
28640493bf3aSMatthias Ringwald         case INFORMATION_REQUEST:
28650493bf3aSMatthias Ringwald             if (cmd_len == 2) {
28663e64cb44SMatthias Ringwald                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
28673e64cb44SMatthias Ringwald                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
28680493bf3aSMatthias Ringwald             } else {
28690493bf3aSMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
287000d93d79Smatthias.ringwald             }
28710493bf3aSMatthias Ringwald             return;
287200d93d79Smatthias.ringwald 
28731b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
28741b9cb13dSMatthias Ringwald         case INFORMATION_RESPONSE: {
28751b9cb13dSMatthias Ringwald             hci_connection_t * connection = hci_connection_for_handle(handle);
28761b9cb13dSMatthias Ringwald             if (!connection) return;
28770defadfbSMatthias Ringwald             if (connection->l2cap_state.information_state != L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE) return;
28780defadfbSMatthias Ringwald 
28790defadfbSMatthias Ringwald             // get extended features from response if valid
28800defadfbSMatthias Ringwald             connection->l2cap_state.extended_feature_mask = 0;
28810defadfbSMatthias Ringwald             if (cmd_len >= 6) {
28821b9cb13dSMatthias Ringwald                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
28831b9cb13dSMatthias Ringwald                 uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
28840defadfbSMatthias Ringwald                 if (result == 0 && info_type == L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) {
28851b9cb13dSMatthias Ringwald                     connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
28860defadfbSMatthias Ringwald                 }
28870defadfbSMatthias Ringwald             }
28880defadfbSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
2889543b84e4SMatthias Ringwald             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
28900defadfbSMatthias Ringwald 
28911b9cb13dSMatthias Ringwald             // trigger connection request
28921b9cb13dSMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
28931b9cb13dSMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
28941b9cb13dSMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2895fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2896543b84e4SMatthias Ringwald                 if (channel->con_handle != handle) continue;
2897f8ecb114SMatthias Ringwald 
2898f8ecb114SMatthias Ringwald                 // incoming connection: ask user for channel configuration, esp. if ertm will be mandatory
2899f8ecb114SMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
2900f8ecb114SMatthias Ringwald                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2901f8ecb114SMatthias Ringwald                     l2cap_emit_incoming_connection(channel);
2902f8ecb114SMatthias Ringwald                     continue;
2903f8ecb114SMatthias Ringwald                 }
2904f8ecb114SMatthias Ringwald 
2905f8ecb114SMatthias Ringwald                 // outgoing connection
2906f8ecb114SMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
2907f8ecb114SMatthias Ringwald 
2908dae3b2abSMatthias Ringwald                     // if ERTM was requested, but is not listed in extended feature mask:
2909543b84e4SMatthias Ringwald                     if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2910dae3b2abSMatthias Ringwald 
2911f073f086SMatthias Ringwald                         if (channel->ertm_mandatory){
2912dae3b2abSMatthias Ringwald                             // bail if ERTM is mandatory
2913543b84e4SMatthias Ringwald                             channel->state = L2CAP_STATE_CLOSED;
2914543b84e4SMatthias Ringwald                             // map l2cap connection response result to BTstack status enumeration
291566a72640SMatthias Ringwald                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
2916543b84e4SMatthias Ringwald                             // discard channel
2917543b84e4SMatthias Ringwald                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2918c45d6b2cSMatthias Ringwald                             l2cap_free_channel_entry(channel);
2919543b84e4SMatthias Ringwald                             continue;
2920dae3b2abSMatthias Ringwald 
2921f073f086SMatthias Ringwald                         } else {
2922f073f086SMatthias Ringwald                             // fallback to Basic mode
292366a72640SMatthias Ringwald                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
2924f073f086SMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2925f073f086SMatthias Ringwald                         }
2926dae3b2abSMatthias Ringwald                     }
2927f8ecb114SMatthias Ringwald 
292852606043SMatthias Ringwald                     // respond to connection request
2929f8ecb114SMatthias Ringwald                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
2930f8ecb114SMatthias Ringwald                     continue;
293152606043SMatthias Ringwald                 }
29321b9cb13dSMatthias Ringwald             }
29331b9cb13dSMatthias Ringwald             return;
29341b9cb13dSMatthias Ringwald         }
29351b9cb13dSMatthias Ringwald #endif
29361b9cb13dSMatthias Ringwald 
293700d93d79Smatthias.ringwald         default:
293800d93d79Smatthias.ringwald             break;
293900d93d79Smatthias.ringwald     }
294000d93d79Smatthias.ringwald 
294100d93d79Smatthias.ringwald     // Get potential destination CID
2942f8fbdce0SMatthias Ringwald     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
294300d93d79Smatthias.ringwald 
294400d93d79Smatthias.ringwald     // Find channel for this sig_id and connection handle
2945665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2946665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2947665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2948fad84cafSMatthias Ringwald         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2949fc64f94aSMatthias Ringwald         if (channel->con_handle != handle) continue;
295000d93d79Smatthias.ringwald         if (code & 1) {
2951b1988dceSmatthias.ringwald             // match odd commands (responses) by previous signaling identifier
2952b1988dceSmatthias.ringwald             if (channel->local_sig_id == sig_id) {
295300d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
29544e32727eSmatthias.ringwald                 break;
295500d93d79Smatthias.ringwald             }
295600d93d79Smatthias.ringwald         } else {
2957b1988dceSmatthias.ringwald             // match even commands (requests) by local channel id
295800d93d79Smatthias.ringwald             if (channel->local_cid == dest_cid) {
295900d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
29604e32727eSmatthias.ringwald                 break;
296100d93d79Smatthias.ringwald             }
296200d93d79Smatthias.ringwald         }
296300d93d79Smatthias.ringwald     }
296400d93d79Smatthias.ringwald }
296509e9d05bSMatthias Ringwald #endif
296600d93d79Smatthias.ringwald 
2967e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
296809e9d05bSMatthias Ringwald 
296909e9d05bSMatthias Ringwald static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
297009e9d05bSMatthias Ringwald     uint8_t event[6];
297109e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
297209e9d05bSMatthias Ringwald     event[1] = 4;
297309e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
297409e9d05bSMatthias Ringwald     little_endian_store_16(event, 4, result);
297509e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
297609e9d05bSMatthias Ringwald     if (!l2cap_event_packet_handler) return;
297709e9d05bSMatthias Ringwald     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
297809e9d05bSMatthias Ringwald }
297909e9d05bSMatthias Ringwald 
2980c48b2a2cSMatthias Ringwald // @returns valid
2981c48b2a2cSMatthias Ringwald static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
2982e7d0c9aaSMatthias Ringwald     hci_connection_t * connection;
2983c48b2a2cSMatthias Ringwald     uint16_t result;
2984f299206dSMatthias Ringwald     uint8_t  event[12];
298583fd9c76SMatthias Ringwald 
2986cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2987a3dc965aSMatthias Ringwald     btstack_linked_list_iterator_t it;
2988a3dc965aSMatthias Ringwald     l2cap_channel_t * channel;
2989a3dc965aSMatthias Ringwald     uint16_t local_cid;
299083fd9c76SMatthias Ringwald     uint16_t le_psm;
299163f0ac45SMatthias Ringwald     uint16_t new_credits;
299263f0ac45SMatthias Ringwald     uint16_t credits_before;
2993e7d0c9aaSMatthias Ringwald     l2cap_service_t * service;
299411cae19eSMilanka Ringwald     uint16_t source_cid;
299583fd9c76SMatthias Ringwald #endif
299600d93d79Smatthias.ringwald 
29971b8b8d05SMatthias Ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2998adcfabadSMatthias Ringwald     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
29991fcd10b7SMatthias Ringwald     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
30001b8b8d05SMatthias Ringwald 
30011b8b8d05SMatthias Ringwald     switch (code){
300200d93d79Smatthias.ringwald 
3003c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_REQUEST:
3004adcfabadSMatthias Ringwald             // check size
30051fcd10b7SMatthias Ringwald             if (len < 8) return 0;
3006e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
3007da886c03S[email protected]             if (connection){
30086d91fb6cSMatthias Ringwald                 if (connection->role != HCI_ROLE_MASTER){
30096d91fb6cSMatthias Ringwald                     // reject command without notifying upper layer when not in master role
3010c48b2a2cSMatthias Ringwald                     return 0;
30116d91fb6cSMatthias Ringwald                 }
3012a4c06b28SMatthias Ringwald                 le_connection_parameter_range_t existing_range;
30134ced4e8cSMatthias Ringwald                 gap_get_connection_parameter_range(&existing_range);
3014d5e694a3SMatthias Ringwald                 uint16_t le_conn_interval_min   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3015d5e694a3SMatthias Ringwald                 uint16_t le_conn_interval_max   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3016d5e694a3SMatthias Ringwald                 uint16_t le_conn_latency        = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3017d5e694a3SMatthias Ringwald                 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
3018da886c03S[email protected] 
301973cd8a2aSMatthias 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);
3020da886c03S[email protected]                 if (update_parameter){
3021da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
3022da886c03S[email protected]                     connection->le_conn_interval_min = le_conn_interval_min;
3023da886c03S[email protected]                     connection->le_conn_interval_max = le_conn_interval_max;
3024da886c03S[email protected]                     connection->le_conn_latency = le_conn_latency;
3025da886c03S[email protected]                     connection->le_supervision_timeout = le_supervision_timeout;
3026da886c03S[email protected]                 } else {
3027da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
3028da886c03S[email protected]                 }
3029c48b2a2cSMatthias Ringwald                 connection->le_con_param_update_identifier = sig_id;
3030da886c03S[email protected]             }
3031da886c03S[email protected] 
303233c40538SMatthias Ringwald             if (!l2cap_event_packet_handler) break;
3033c48b2a2cSMatthias Ringwald 
3034c48b2a2cSMatthias Ringwald             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
3035c48b2a2cSMatthias Ringwald             event[1] = 8;
3036f299206dSMatthias Ringwald             little_endian_store_16(event, 2, handle);
3037f299206dSMatthias Ringwald             memcpy(&event[4], &command[4], 8);
3038c48b2a2cSMatthias Ringwald             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
303933c40538SMatthias Ringwald             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
3040ccf076adS[email protected]             break;
3041c48b2a2cSMatthias Ringwald 
30421fcd10b7SMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
30431fcd10b7SMatthias Ringwald             // check size
30441fcd10b7SMatthias Ringwald             if (len < 2) return 0;
30451fcd10b7SMatthias Ringwald             result = little_endian_read_16(command, 4);
30461fcd10b7SMatthias Ringwald             l2cap_emit_connection_parameter_update_response(handle, result);
30471fcd10b7SMatthias Ringwald             break;
30481fcd10b7SMatthias Ringwald 
3049a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
3050a3dc965aSMatthias Ringwald 
305163f0ac45SMatthias Ringwald         case COMMAND_REJECT:
305263f0ac45SMatthias Ringwald             // Find channel for this sig_id and connection handle
305363f0ac45SMatthias Ringwald             channel = NULL;
3054421cb104SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
305563f0ac45SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
305663f0ac45SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3057fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
305863f0ac45SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
305963f0ac45SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
306063f0ac45SMatthias Ringwald                 channel = a_channel;
306163f0ac45SMatthias Ringwald                 break;
306263f0ac45SMatthias Ringwald             }
306363f0ac45SMatthias Ringwald             if (!channel) break;
306463f0ac45SMatthias Ringwald 
306563f0ac45SMatthias Ringwald             // if received while waiting for le connection response, assume legacy device
306663f0ac45SMatthias Ringwald             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
306763f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
306863f0ac45SMatthias Ringwald                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
306944276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0x0002);
307063f0ac45SMatthias Ringwald 
307163f0ac45SMatthias Ringwald                 // discard channel
3072421cb104SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3073c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
307463f0ac45SMatthias Ringwald                 break;
307563f0ac45SMatthias Ringwald             }
307663f0ac45SMatthias Ringwald             break;
307763f0ac45SMatthias Ringwald 
3078e7d0c9aaSMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_REQUEST:
3079adcfabadSMatthias Ringwald             // check size
3080adcfabadSMatthias Ringwald             if (len < 10) return 0;
3081e7d0c9aaSMatthias Ringwald 
3082e7d0c9aaSMatthias Ringwald             // get hci connection, bail if not found (must not happen)
3083e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
3084e7d0c9aaSMatthias Ringwald             if (!connection) return 0;
3085e7d0c9aaSMatthias Ringwald 
3086e7d0c9aaSMatthias Ringwald             // check if service registered
3087e7d0c9aaSMatthias Ringwald             le_psm  = little_endian_read_16(command, 4);
3088e7d0c9aaSMatthias Ringwald             service = l2cap_le_get_service(le_psm);
308911cae19eSMilanka Ringwald             source_cid = little_endian_read_16(command, 6);
3090e7d0c9aaSMatthias Ringwald 
3091e7d0c9aaSMatthias Ringwald             if (service){
3092e7d0c9aaSMatthias Ringwald                 if (source_cid < 0x40){
3093e7d0c9aaSMatthias Ringwald                     // 0x0009 Connection refused - Invalid Source CID
3094e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
3095e7d0c9aaSMatthias Ringwald                     return 1;
3096e7d0c9aaSMatthias Ringwald                 }
3097e7d0c9aaSMatthias Ringwald 
3098e7d0c9aaSMatthias Ringwald                 // go through list of channels for this ACL connection and check if we get a match
3099421cb104SMatthias Ringwald                 btstack_linked_list_iterator_init(&it, &l2cap_channels);
3100e7d0c9aaSMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&it)){
31011b8b8d05SMatthias Ringwald                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3102fad84cafSMatthias Ringwald                     if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
31031b8b8d05SMatthias Ringwald                     if (a_channel->con_handle != handle) continue;
31041b8b8d05SMatthias Ringwald                     if (a_channel->remote_cid != source_cid) continue;
3105e7d0c9aaSMatthias Ringwald                     // 0x000a Connection refused - Source CID already allocated
3106e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
3107e7d0c9aaSMatthias Ringwald                     return 1;
3108e7d0c9aaSMatthias Ringwald                 }
3109e7d0c9aaSMatthias Ringwald 
311083fd9c76SMatthias Ringwald                 // security: check encryption
311183fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_2){
31129c6e867eSMatthias Ringwald                     if (gap_encryption_key_size(handle) == 0){
311383fd9c76SMatthias Ringwald                         // 0x0008 Connection refused - insufficient encryption
3114e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
311583fd9c76SMatthias Ringwald                         return 1;
311683fd9c76SMatthias Ringwald                     }
311783fd9c76SMatthias Ringwald                     // anything less than 16 byte key size is insufficient
31189c6e867eSMatthias Ringwald                     if (gap_encryption_key_size(handle) < 16){
311983fd9c76SMatthias Ringwald                         // 0x0007 Connection refused – insufficient encryption key size
3120e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
312183fd9c76SMatthias Ringwald                         return 1;
312283fd9c76SMatthias Ringwald                     }
312383fd9c76SMatthias Ringwald                 }
312483fd9c76SMatthias Ringwald 
312583fd9c76SMatthias Ringwald                 // security: check authencation
312683fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_3){
31279c6e867eSMatthias Ringwald                     if (!gap_authenticated(handle)){
312883fd9c76SMatthias Ringwald                         // 0x0005 Connection refused – insufficient authentication
3129e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
313083fd9c76SMatthias Ringwald                         return 1;
313183fd9c76SMatthias Ringwald                     }
313283fd9c76SMatthias Ringwald                 }
313383fd9c76SMatthias Ringwald 
313483fd9c76SMatthias Ringwald                 // security: check authorization
313583fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_4){
31369c6e867eSMatthias Ringwald                     if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
313783fd9c76SMatthias Ringwald                         // 0x0006 Connection refused – insufficient authorization
3138e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
313983fd9c76SMatthias Ringwald                         return 1;
314083fd9c76SMatthias Ringwald                     }
314183fd9c76SMatthias Ringwald                 }
3142e7d0c9aaSMatthias Ringwald 
3143e7d0c9aaSMatthias Ringwald                 // allocate channel
31445d18f623SMatthias Ringwald                 channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL, connection->address,
3145e7d0c9aaSMatthias Ringwald                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
3146e7d0c9aaSMatthias Ringwald                 if (!channel){
3147e7d0c9aaSMatthias Ringwald                     // 0x0004 Connection refused – no resources available
3148e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
3149e7d0c9aaSMatthias Ringwald                     return 1;
3150e7d0c9aaSMatthias Ringwald                 }
3151e7d0c9aaSMatthias Ringwald 
3152e7d0c9aaSMatthias Ringwald                 channel->con_handle = handle;
3153e7d0c9aaSMatthias Ringwald                 channel->remote_cid = source_cid;
3154e7d0c9aaSMatthias Ringwald                 channel->remote_sig_id = sig_id;
31557f107edaSMatthias Ringwald                 channel->remote_mtu = little_endian_read_16(command, 8);
31567f107edaSMatthias Ringwald                 channel->remote_mps = little_endian_read_16(command, 10);
31577f107edaSMatthias Ringwald                 channel->credits_outgoing = little_endian_read_16(command, 12);
3158e7d0c9aaSMatthias Ringwald 
3159e7d0c9aaSMatthias Ringwald                 // set initial state
3160e7d0c9aaSMatthias Ringwald                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
3161c99bb618SMatthias Ringwald                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
3162e7d0c9aaSMatthias Ringwald 
3163e7d0c9aaSMatthias Ringwald                 // add to connections list
3164421cb104SMatthias Ringwald                 btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
3165e7d0c9aaSMatthias Ringwald 
3166e7d0c9aaSMatthias Ringwald                 // post connection request event
316744276248SMatthias Ringwald                 l2cap_emit_le_incoming_connection(channel);
3168e7d0c9aaSMatthias Ringwald 
3169e7d0c9aaSMatthias Ringwald             } else {
3170e7d0c9aaSMatthias Ringwald                 // Connection refused – LE_PSM not supported
3171e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
3172e7d0c9aaSMatthias Ringwald             }
3173e7d0c9aaSMatthias Ringwald             break;
31741b8b8d05SMatthias Ringwald 
31751b8b8d05SMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
3176adcfabadSMatthias Ringwald             // check size
3177adcfabadSMatthias Ringwald             if (len < 10) return 0;
3178adcfabadSMatthias Ringwald 
31791b8b8d05SMatthias Ringwald             // Find channel for this sig_id and connection handle
31801b8b8d05SMatthias Ringwald             channel = NULL;
3181421cb104SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
31821b8b8d05SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
31831b8b8d05SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3184fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
31851b8b8d05SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
31861b8b8d05SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
31871b8b8d05SMatthias Ringwald                 channel = a_channel;
31881b8b8d05SMatthias Ringwald                 break;
31891b8b8d05SMatthias Ringwald             }
31901b8b8d05SMatthias Ringwald             if (!channel) break;
31911b8b8d05SMatthias Ringwald 
31921b8b8d05SMatthias Ringwald             // cid + 0
31931b8b8d05SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
31941b8b8d05SMatthias Ringwald             if (result){
31951b8b8d05SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
31961b8b8d05SMatthias Ringwald                 // map l2cap connection response result to BTstack status enumeration
319744276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, result);
31981b8b8d05SMatthias Ringwald 
31991b8b8d05SMatthias Ringwald                 // discard channel
3200421cb104SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3201c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
32021b8b8d05SMatthias Ringwald                 break;
32031b8b8d05SMatthias Ringwald             }
32041b8b8d05SMatthias Ringwald 
32051b8b8d05SMatthias Ringwald             // success
32061b8b8d05SMatthias Ringwald             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
32071b8b8d05SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
32081b8b8d05SMatthias Ringwald             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
32091b8b8d05SMatthias Ringwald             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
32101b8b8d05SMatthias Ringwald             channel->state = L2CAP_STATE_OPEN;
321144276248SMatthias Ringwald             l2cap_emit_le_channel_opened(channel, result);
32121b8b8d05SMatthias Ringwald             break;
32131b8b8d05SMatthias Ringwald 
321485aeef60SMatthias Ringwald         case LE_FLOW_CONTROL_CREDIT:
3215adcfabadSMatthias Ringwald             // check size
3216adcfabadSMatthias Ringwald             if (len < 4) return 0;
3217adcfabadSMatthias Ringwald 
321885aeef60SMatthias Ringwald             // find channel
321985aeef60SMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3220421cb104SMatthias Ringwald             channel = l2cap_get_channel_for_local_cid(local_cid);
322163f0ac45SMatthias Ringwald             if (!channel) {
322263f0ac45SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
322363f0ac45SMatthias Ringwald                 break;
322463f0ac45SMatthias Ringwald             }
322563f0ac45SMatthias Ringwald             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
322663f0ac45SMatthias Ringwald             credits_before = channel->credits_outgoing;
322763f0ac45SMatthias Ringwald             channel->credits_outgoing += new_credits;
322863f0ac45SMatthias Ringwald             // check for credit overrun
322963f0ac45SMatthias Ringwald             if (credits_before > channel->credits_outgoing){
323063f0ac45SMatthias Ringwald                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
323163f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
323263f0ac45SMatthias Ringwald                 break;
323363f0ac45SMatthias Ringwald             }
323463f0ac45SMatthias Ringwald             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
323585aeef60SMatthias Ringwald             break;
323685aeef60SMatthias Ringwald 
3237828a7f7aSMatthias Ringwald         case DISCONNECTION_REQUEST:
3238adcfabadSMatthias Ringwald 
3239adcfabadSMatthias Ringwald             // check size
3240adcfabadSMatthias Ringwald             if (len < 4) return 0;
3241adcfabadSMatthias Ringwald 
3242828a7f7aSMatthias Ringwald             // find channel
3243828a7f7aSMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3244421cb104SMatthias Ringwald             channel = l2cap_get_channel_for_local_cid(local_cid);
324563f34e00SMatthias Ringwald             if (!channel) {
324663f34e00SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
324763f34e00SMatthias Ringwald                 break;
324863f34e00SMatthias Ringwald             }
3249828a7f7aSMatthias Ringwald             channel->remote_sig_id = sig_id;
3250828a7f7aSMatthias Ringwald             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
3251828a7f7aSMatthias Ringwald             break;
3252828a7f7aSMatthias Ringwald 
3253a3dc965aSMatthias Ringwald #endif
3254a3dc965aSMatthias Ringwald 
325563f0ac45SMatthias Ringwald         case DISCONNECTION_RESPONSE:
325663f0ac45SMatthias Ringwald             break;
325763f0ac45SMatthias Ringwald 
3258c48b2a2cSMatthias Ringwald         default:
3259c48b2a2cSMatthias Ringwald             // command unknown -> reject command
3260c48b2a2cSMatthias Ringwald             return 0;
3261ccf076adS[email protected]     }
3262c48b2a2cSMatthias Ringwald     return 1;
3263c48b2a2cSMatthias Ringwald }
3264e7d0c9aaSMatthias Ringwald #endif
3265c48b2a2cSMatthias Ringwald 
3266bb0a72a6SMatthias Ringwald static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3267bb0a72a6SMatthias Ringwald #ifdef ENABLE_CLASSIC
326809e9d05bSMatthias Ringwald     l2cap_channel_t * l2cap_channel;
3269fad84cafSMatthias Ringwald     l2cap_fixed_channel_t * l2cap_fixed_channel;
327009e9d05bSMatthias Ringwald 
3271c48b2a2cSMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3272c48b2a2cSMatthias Ringwald     switch (channel_id) {
3273c48b2a2cSMatthias Ringwald 
3274c48b2a2cSMatthias Ringwald         case L2CAP_CID_SIGNALING: {
3275eaeabfdaSMatthias Ringwald             uint32_t command_offset = 8;
3276eaeabfdaSMatthias Ringwald             while ((command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET) < size) {
3277ed2ed8e1SMatthias Ringwald                 // assert signaling command is fully inside packet
3278ed2ed8e1SMatthias Ringwald                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3279eaeabfdaSMatthias Ringwald                 uint32_t next_command_offset = command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
3280ed2ed8e1SMatthias Ringwald                 if (next_command_offset > size){
3281ed2ed8e1SMatthias Ringwald                     log_error("l2cap signaling command len invalid -> drop");
3282ed2ed8e1SMatthias Ringwald                     break;
3283ed2ed8e1SMatthias Ringwald                 }
3284ed2ed8e1SMatthias Ringwald                 // handle signaling command
3285c48b2a2cSMatthias Ringwald                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
3286ed2ed8e1SMatthias Ringwald                 // go to next command
3287eaeabfdaSMatthias Ringwald                 command_offset = next_command_offset;
3288c48b2a2cSMatthias Ringwald             }
3289c48b2a2cSMatthias Ringwald             break;
3290c48b2a2cSMatthias Ringwald         }
3291c48b2a2cSMatthias Ringwald         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
3292fad84cafSMatthias Ringwald             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL);
3293fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel) break;
3294fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel->packet_handler) break;
3295fad84cafSMatthias Ringwald             (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3296c48b2a2cSMatthias Ringwald             break;
32971bbc0b23S[email protected] 
329809e9d05bSMatthias Ringwald         default:
329900d93d79Smatthias.ringwald             // Find channel for this channel_id and connection handle
330064e11ca9SMatthias Ringwald             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
3301d1fd2a88SMatthias Ringwald             if (l2cap_channel) {
330227e0774aSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
330327e0774aSMatthias Ringwald                 if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
330427e0774aSMatthias Ringwald 
33056574158aSMatthias Ringwald                     int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
330607c7de86SMatthias Ringwald 
33076574158aSMatthias Ringwald                     // assert control + FCS fields are inside
33086574158aSMatthias Ringwald                     if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) break;
33096574158aSMatthias Ringwald 
33106574158aSMatthias Ringwald                     if (l2cap_channel->fcs_option){
3311fcb125edSMatthias Ringwald                         // verify FCS (required if one side requested it)
331227e0774aSMatthias Ringwald                         uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
331327e0774aSMatthias Ringwald                         uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
3314e288be62SMatthias Ringwald 
3315e288be62SMatthias Ringwald #ifdef L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL
3316e288be62SMatthias Ringwald                         // simulate fcs error
3317e288be62SMatthias Ringwald                         static int counter = 0;
3318e288be62SMatthias Ringwald                         if (++counter == L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL) {
3319e288be62SMatthias Ringwald                             log_info("Simulate fcs error");
3320e288be62SMatthias Ringwald                             fcs_calculated++;
3321e288be62SMatthias Ringwald                             counter = 0;
3322e288be62SMatthias Ringwald                         }
3323e288be62SMatthias Ringwald #endif
3324e288be62SMatthias Ringwald 
33256574158aSMatthias Ringwald                         if (fcs_calculated == fcs_packet){
33266574158aSMatthias Ringwald                             log_info("Packet FCS 0x%04x verified", fcs_packet);
33276574158aSMatthias Ringwald                         } else {
332827e0774aSMatthias Ringwald                             log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
3329ef2faf56SMatthias Ringwald                             // ERTM State Machine in Bluetooth Spec does not handle 'I-Frame with invalid FCS'
333027e0774aSMatthias Ringwald                             break;
333127e0774aSMatthias Ringwald                         }
33326574158aSMatthias Ringwald                     }
333327e0774aSMatthias Ringwald 
333427e0774aSMatthias Ringwald                     // switch on packet type
333527e0774aSMatthias Ringwald                     uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
333638f62777SMatthias Ringwald                     uint8_t  req_seq = (control >> 8) & 0x3f;
33372bea1b8dSMatthias Ringwald                     int final = (control >> 7) & 0x01;
333827e0774aSMatthias Ringwald                     if (control & 1){
333927e0774aSMatthias Ringwald                         // S-Frame
334078cd8a22SMatthias Ringwald                         int poll  = (control >> 4) & 0x01;
3341bdbe2e49SMatthias Ringwald                         l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
33429ffcbce4SMatthias Ringwald                         log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
33437b7901d8SMatthias Ringwald                         l2cap_ertm_tx_packet_state_t * tx_state;
3344bdbe2e49SMatthias Ringwald                         switch (s){
3345bdbe2e49SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
33469ffcbce4SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
33471e1a46bbSMatthias Ringwald                                 l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
33483233d8abSMatthias Ringwald                                 if (poll && final){
33493233d8abSMatthias Ringwald                                     // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
33503233d8abSMatthias Ringwald                                     log_error("P=F=1 in S-Frame");
33513233d8abSMatthias Ringwald                                     break;
33523233d8abSMatthias Ringwald                                 }
335378cd8a22SMatthias Ringwald                                 if (poll){
3354f85ade6bSMatthias Ringwald                                     // check if we did request selective retransmission before <==> we have stored SDU segments
3355f85ade6bSMatthias Ringwald                                     int i;
3356f85ade6bSMatthias Ringwald                                     int num_stored_out_of_order_packets = 0;
3357f85ade6bSMatthias Ringwald                                     for (i=0;i<l2cap_channel->num_rx_buffers;i++){
3358f85ade6bSMatthias Ringwald                                         int index = l2cap_channel->rx_store_index + i;
3359f85ade6bSMatthias Ringwald                                         if (index >= l2cap_channel->num_rx_buffers){
3360f85ade6bSMatthias Ringwald                                             index -= l2cap_channel->num_rx_buffers;
3361f85ade6bSMatthias Ringwald                                         }
3362f85ade6bSMatthias Ringwald                                         l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3363f85ade6bSMatthias Ringwald                                         if (!rx_state->valid) continue;
3364f85ade6bSMatthias Ringwald                                         num_stored_out_of_order_packets++;
3365f85ade6bSMatthias Ringwald                                     }
3366f85ade6bSMatthias Ringwald                                     if (num_stored_out_of_order_packets){
3367f85ade6bSMatthias Ringwald                                         l2cap_channel->send_supervisor_frame_selective_reject = 1;
3368f85ade6bSMatthias Ringwald                                     } else {
3369d2afdd38SMatthias Ringwald                                         l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
337078cd8a22SMatthias Ringwald                                     }
3371f85ade6bSMatthias Ringwald                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
3372f85ade6bSMatthias Ringwald                                 }
33733233d8abSMatthias Ringwald                                 if (final){
3374550189ffSMatthias Ringwald                                     // Stop-MonitorTimer
3375550189ffSMatthias Ringwald                                     l2cap_ertm_stop_monitor_timer(l2cap_channel);
3376550189ffSMatthias Ringwald                                     // If UnackedFrames > 0 then Start-RetransTimer
337794301352SMatthias Ringwald                                     if (l2cap_channel->unacked_frames){
3378550189ffSMatthias Ringwald                                         l2cap_ertm_start_retransmission_timer(l2cap_channel);
3379550189ffSMatthias Ringwald                                     }
33803233d8abSMatthias Ringwald                                     // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3381ef2faf56SMatthias Ringwald                                     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
33823233d8abSMatthias Ringwald                                 }
3383bdbe2e49SMatthias Ringwald                                 break;
33849ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
33859ffcbce4SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
33861e1a46bbSMatthias Ringwald                                 l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3387600cf12dSMatthias Ringwald                                 // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
3388ef2faf56SMatthias Ringwald                                 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
33899ffcbce4SMatthias Ringwald                                 break;
33909ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
33919ffcbce4SMatthias Ringwald                                 log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
33929ffcbce4SMatthias Ringwald                                 break;
33939ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
33947b7901d8SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
33957b7901d8SMatthias Ringwald                                 if (poll){
33961e1a46bbSMatthias Ringwald                                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
33977b7901d8SMatthias Ringwald                                 }
33987b7901d8SMatthias Ringwald                                 // find requested i-frame
33997b7901d8SMatthias Ringwald                                 tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
34007b7901d8SMatthias Ringwald                                 if (tx_state){
34017b7901d8SMatthias Ringwald                                     log_info("Retransmission for tx_seq %u requested", req_seq);
3402d2afdd38SMatthias Ringwald                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
34037b7901d8SMatthias Ringwald                                     tx_state->retransmission_requested = 1;
34047b7901d8SMatthias Ringwald                                     l2cap_channel->srej_active = 1;
34057b7901d8SMatthias Ringwald                                 }
34069ffcbce4SMatthias Ringwald                                 break;
3407bdbe2e49SMatthias Ringwald                             default:
3408bdbe2e49SMatthias Ringwald                                 break;
3409bdbe2e49SMatthias Ringwald                         }
341027e0774aSMatthias Ringwald                         break;
341127e0774aSMatthias Ringwald                     } else {
341227e0774aSMatthias Ringwald                         // I-Frame
341327e0774aSMatthias Ringwald                         // get control
341427e0774aSMatthias Ringwald                         l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
341538f62777SMatthias Ringwald                         uint8_t tx_seq = (control >> 1) & 0x3f;
341638f62777SMatthias Ringwald                         log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
3417e8e9809fSMatthias Ringwald                         log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
341838f62777SMatthias Ringwald                         log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
34191e1a46bbSMatthias Ringwald                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
342011b576c5SMatthias Ringwald                         if (final){
342111b576c5SMatthias Ringwald                             // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3422ef2faf56SMatthias Ringwald                             l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
342311b576c5SMatthias Ringwald                         }
342407c7de86SMatthias Ringwald 
342507c7de86SMatthias Ringwald                         // get SDU
3426826c39d0SMatthias Ringwald                         const uint8_t * payload_data = &packet[COMPLETE_L2CAP_HEADER+2];
3427826c39d0SMatthias Ringwald                         uint16_t        payload_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
342807c7de86SMatthias Ringwald 
342907c7de86SMatthias Ringwald                         // assert SDU size is smaller or equal to our buffers
3430826c39d0SMatthias Ringwald                         uint16_t max_payload_size = 0;
3431826c39d0SMatthias Ringwald                         switch (sar){
3432826c39d0SMatthias Ringwald                             case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
3433826c39d0SMatthias Ringwald                             case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
3434826c39d0SMatthias Ringwald                                 // SDU Length + MPS
3435826c39d0SMatthias Ringwald                                 max_payload_size = l2cap_channel->local_mps + 2;
3436826c39d0SMatthias Ringwald                                 break;
3437826c39d0SMatthias Ringwald                             case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
3438826c39d0SMatthias Ringwald                             case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
3439826c39d0SMatthias Ringwald                                 max_payload_size = l2cap_channel->local_mps;
3440826c39d0SMatthias Ringwald                                 break;
3441826c39d0SMatthias Ringwald                         }
3442826c39d0SMatthias Ringwald                         if (payload_len > max_payload_size){
3443826c39d0SMatthias Ringwald                             log_info("payload len %u > max payload %u -> drop packet", payload_len, max_payload_size);
3444826c39d0SMatthias Ringwald                             break;
3445826c39d0SMatthias Ringwald                         }
344607c7de86SMatthias Ringwald 
344738f62777SMatthias Ringwald                         // check ordering
344838f62777SMatthias Ringwald                         if (l2cap_channel->expected_tx_seq == tx_seq){
344938f62777SMatthias Ringwald                             log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
345038f62777SMatthias Ringwald                             l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3451f85ade6bSMatthias Ringwald                             l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3452d48432d4SMatthias Ringwald 
3453e32be409SMatthias Ringwald                             // process SDU
3454826c39d0SMatthias Ringwald                             l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, payload_data, payload_len);
3455d48432d4SMatthias Ringwald 
345670734707SMatthias Ringwald                             // process stored segments
345770734707SMatthias Ringwald                             while (1){
345870734707SMatthias Ringwald                                 int index = l2cap_channel->rx_store_index;
345970734707SMatthias Ringwald                                 l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
346070734707SMatthias Ringwald                                 if (!rx_state->valid) break;
3461f85ade6bSMatthias Ringwald 
3462f85ade6bSMatthias Ringwald                                 log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
3463f85ade6bSMatthias Ringwald                                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3464f85ade6bSMatthias Ringwald                                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3465f85ade6bSMatthias Ringwald 
346670734707SMatthias Ringwald                                 rx_state->valid = 0;
346770734707SMatthias Ringwald                                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
3468f85ade6bSMatthias Ringwald 
3469f85ade6bSMatthias Ringwald                                 // update rx store index
347070734707SMatthias Ringwald                                 index++;
347170734707SMatthias Ringwald                                 if (index >= l2cap_channel->num_rx_buffers){
347270734707SMatthias Ringwald                                     index = 0;
347370734707SMatthias Ringwald                                 }
347470734707SMatthias Ringwald                                 l2cap_channel->rx_store_index = index;
347570734707SMatthias Ringwald                             }
347670734707SMatthias Ringwald 
3477f85ade6bSMatthias Ringwald                             //
3478f85ade6bSMatthias Ringwald                             l2cap_channel->send_supervisor_frame_receiver_ready = 1;
3479f85ade6bSMatthias Ringwald 
3480c7309e8dSMatthias Ringwald                         } else {
3481df2191a7SMatthias Ringwald                             int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
3482df2191a7SMatthias Ringwald                             if (delta < 2){
348370734707SMatthias Ringwald                                 // store segment
3484826c39d0SMatthias Ringwald                                 l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, payload_data, payload_len);
348570734707SMatthias Ringwald 
3486df2191a7SMatthias Ringwald                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
3487df2191a7SMatthias Ringwald                                 l2cap_channel->send_supervisor_frame_selective_reject = 1;
3488df2191a7SMatthias Ringwald                             } else {
3489df2191a7SMatthias Ringwald                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
3490c7309e8dSMatthias Ringwald                                 l2cap_channel->send_supervisor_frame_reject = 1;
349127e0774aSMatthias Ringwald                             }
349238f62777SMatthias Ringwald                         }
3493df2191a7SMatthias Ringwald                     }
349427e0774aSMatthias Ringwald                     break;
349527e0774aSMatthias Ringwald                 }
349627e0774aSMatthias Ringwald #endif
34973d50b4baSMatthias Ringwald                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
349800d93d79Smatthias.ringwald             }
3499bb0a72a6SMatthias Ringwald             break;
3500bb0a72a6SMatthias Ringwald     }
3501bb0a72a6SMatthias Ringwald #else
3502bb0a72a6SMatthias Ringwald     UNUSED(handle); // ok: no code
3503bb0a72a6SMatthias Ringwald     UNUSED(packet); // ok: no code
3504bb0a72a6SMatthias Ringwald     UNUSED(size);   // ok: no code
350509e9d05bSMatthias Ringwald #endif
3506bb0a72a6SMatthias Ringwald }
3507bb0a72a6SMatthias Ringwald 
3508bb0a72a6SMatthias Ringwald static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3509bb0a72a6SMatthias Ringwald #ifdef ENABLE_BLE
3510bb0a72a6SMatthias Ringwald 
3511fad84cafSMatthias Ringwald     l2cap_fixed_channel_t * l2cap_fixed_channel;
3512fad84cafSMatthias Ringwald 
3513bb0a72a6SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
3514bb0a72a6SMatthias Ringwald     l2cap_channel_t * l2cap_channel;
3515bb0a72a6SMatthias Ringwald #endif
3516bb0a72a6SMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3517bb0a72a6SMatthias Ringwald     switch (channel_id) {
3518bb0a72a6SMatthias Ringwald 
3519bb0a72a6SMatthias Ringwald         case L2CAP_CID_SIGNALING_LE: {
3520bb0a72a6SMatthias Ringwald             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
3521adcfabadSMatthias Ringwald             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
3522adcfabadSMatthias Ringwald             if (COMPLETE_L2CAP_HEADER + 4 + len > size) break;
3523bb0a72a6SMatthias Ringwald             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
3524bb0a72a6SMatthias Ringwald             if (!valid){
3525bb0a72a6SMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3526bb0a72a6SMatthias Ringwald             }
3527bb0a72a6SMatthias Ringwald             break;
3528bb0a72a6SMatthias Ringwald         }
3529bb0a72a6SMatthias Ringwald 
3530bb0a72a6SMatthias Ringwald         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
3531fad84cafSMatthias Ringwald             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL);
3532fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel) break;
3533fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel->packet_handler) break;
3534fad84cafSMatthias Ringwald             (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3535bb0a72a6SMatthias Ringwald             break;
3536bb0a72a6SMatthias Ringwald 
3537bb0a72a6SMatthias Ringwald         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
3538fad84cafSMatthias Ringwald             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
3539fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel) break;
3540fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel->packet_handler) break;
3541fad84cafSMatthias Ringwald             (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3542bb0a72a6SMatthias Ringwald             break;
3543bb0a72a6SMatthias Ringwald 
3544bb0a72a6SMatthias Ringwald         default:
3545bb0a72a6SMatthias Ringwald 
3546a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
3547421cb104SMatthias Ringwald             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
354864e11ca9SMatthias Ringwald             if (l2cap_channel) {
354985aeef60SMatthias Ringwald                 // credit counting
355085aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming == 0){
355185aeef60SMatthias Ringwald                     log_error("LE Data Channel packet received but no incoming credits");
355285aeef60SMatthias Ringwald                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
355385aeef60SMatthias Ringwald                     break;
355485aeef60SMatthias Ringwald                 }
355585aeef60SMatthias Ringwald                 l2cap_channel->credits_incoming--;
355685aeef60SMatthias Ringwald 
355785aeef60SMatthias Ringwald                 // automatic credits
3558*c1ab6cc1SMatthias Ringwald                 if ((l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK) && l2cap_channel->automatic_credits){
355985aeef60SMatthias Ringwald                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
356085aeef60SMatthias Ringwald                 }
356185aeef60SMatthias Ringwald 
3562cd529728SMatthias Ringwald                 // first fragment
3563cd529728SMatthias Ringwald                 uint16_t pos = 0;
3564cd529728SMatthias Ringwald                 if (!l2cap_channel->receive_sdu_len){
3565bb98c113SMatthias Ringwald                     uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3566bb98c113SMatthias Ringwald                     if(sdu_len > l2cap_channel->local_mtu) break;   // SDU would be larger than our buffer
3567bb98c113SMatthias Ringwald                     l2cap_channel->receive_sdu_len = sdu_len;
3568cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_pos = 0;
3569cd529728SMatthias Ringwald                     pos  += 2;
3570cd529728SMatthias Ringwald                     size -= 2;
3571cd529728SMatthias Ringwald                 }
3572bb98c113SMatthias Ringwald                 uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
3573bb98c113SMatthias Ringwald                 uint16_t remaining_space = l2cap_channel->local_mtu - l2cap_channel->receive_sdu_pos;
3574bb98c113SMatthias Ringwald                 if (fragment_size > remaining_space) break;         // SDU would cause buffer overrun
3575bb98c113SMatthias Ringwald                 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], fragment_size);
3576cd529728SMatthias Ringwald                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
3577cd529728SMatthias Ringwald                 // done?
3578895ff4a5SMatthias Ringwald                 log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
3579cd529728SMatthias Ringwald                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
3580cd529728SMatthias Ringwald                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
3581cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = 0;
3582cd529728SMatthias Ringwald                 }
358363f0ac45SMatthias Ringwald             } else {
358463f0ac45SMatthias Ringwald                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
358564e11ca9SMatthias Ringwald             }
358664e11ca9SMatthias Ringwald #endif
35875652b5ffS[email protected]             break;
35885652b5ffS[email protected]     }
3589bb0a72a6SMatthias Ringwald #else
3590bb0a72a6SMatthias Ringwald     UNUSED(handle); // ok: no code
3591bb0a72a6SMatthias Ringwald     UNUSED(packet); // ok: no code
3592bb0a72a6SMatthias Ringwald     UNUSED(size);   // ok: no code
3593bb0a72a6SMatthias Ringwald #endif
3594bb0a72a6SMatthias Ringwald }
3595bb0a72a6SMatthias Ringwald 
3596bb0a72a6SMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
3597bb0a72a6SMatthias Ringwald     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
3598bb0a72a6SMatthias Ringwald     UNUSED(channel);        // ok: there is no channel
3599bb0a72a6SMatthias Ringwald 
3600adcfabadSMatthias Ringwald     // Assert full L2CAP header present
3601adcfabadSMatthias Ringwald     if (size < COMPLETE_L2CAP_HEADER) return;
3602adcfabadSMatthias Ringwald 
3603f16129ceSMatthias Ringwald     // Dispatch to Classic or LE handler (SCO packets are not dispatched to L2CAP)
3604bb0a72a6SMatthias Ringwald     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
3605bb0a72a6SMatthias Ringwald     hci_connection_t *conn = hci_connection_for_handle(handle);
3606bb0a72a6SMatthias Ringwald     if (!conn) return;
3607f16129ceSMatthias Ringwald     if (conn->address_type == BD_ADDR_TYPE_ACL){
3608bb0a72a6SMatthias Ringwald         l2cap_acl_classic_handler(handle, packet, size);
3609bb0a72a6SMatthias Ringwald     } else {
3610bb0a72a6SMatthias Ringwald         l2cap_acl_le_handler(handle, packet, size);
3611bb0a72a6SMatthias Ringwald     }
361200d93d79Smatthias.ringwald 
36131eb2563eS[email protected]     l2cap_run();
36142718e2e7Smatthias.ringwald }
361500d93d79Smatthias.ringwald 
361609e9d05bSMatthias Ringwald // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
361709e9d05bSMatthias Ringwald void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
3618fad84cafSMatthias Ringwald     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
3619fad84cafSMatthias Ringwald     if (!channel) return;
3620fad84cafSMatthias Ringwald     channel->packet_handler = the_packet_handler;
362109e9d05bSMatthias Ringwald }
362209e9d05bSMatthias Ringwald 
362309e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
362415ec09bbSmatthias.ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
362527a923d0Smatthias.ringwald void l2cap_finialize_channel_close(l2cap_channel_t * channel){
3626f62db1e3Smatthias.ringwald     channel->state = L2CAP_STATE_CLOSED;
362766a72640SMatthias Ringwald     l2cap_handle_channel_closed(channel);
3628f62db1e3Smatthias.ringwald     // discard channel
3629665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3630c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
3631c8e4258aSmatthias.ringwald }
363213aa3e4bSMatthias Ringwald #endif
36331e6aba47Smatthias.ringwald 
363413aa3e4bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
36358f2a52f4SMatthias Ringwald static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3636665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
3637665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, services);
3638665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
3639665d90f2SMatthias Ringwald         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
36409d9bbc01Smatthias.ringwald         if ( service->psm == psm){
36419d9bbc01Smatthias.ringwald             return service;
36429d9bbc01Smatthias.ringwald         };
36439d9bbc01Smatthias.ringwald     }
36449d9bbc01Smatthias.ringwald     return NULL;
36459d9bbc01Smatthias.ringwald }
364613aa3e4bSMatthias Ringwald #endif
36479d9bbc01Smatthias.ringwald 
364813aa3e4bSMatthias Ringwald #ifdef ENABLE_CLASSIC
36497192e786SMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
36507192e786SMatthias Ringwald     return l2cap_get_service_internal(&l2cap_services, psm);
36517192e786SMatthias Ringwald }
36527192e786SMatthias Ringwald 
3653be2053a6SMatthias 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){
3654be2053a6SMatthias Ringwald 
3655be2053a6SMatthias Ringwald     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
3656e0abb8e7S[email protected] 
36574bb582b6Smatthias.ringwald     // check for alread registered psm
36589d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
3659277abc2cSmatthias.ringwald     if (service) {
3660be2053a6SMatthias Ringwald         log_error("l2cap_register_service: PSM %u already registered", psm);
3661be2053a6SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
3662277abc2cSmatthias.ringwald     }
36639d9bbc01Smatthias.ringwald 
36644bb582b6Smatthias.ringwald     // alloc structure
3665bb69aaaeS[email protected]     service = btstack_memory_l2cap_service_get();
3666277abc2cSmatthias.ringwald     if (!service) {
3667be2053a6SMatthias Ringwald         log_error("l2cap_register_service: no memory for l2cap_service_t");
3668be2053a6SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
3669277abc2cSmatthias.ringwald     }
36709d9bbc01Smatthias.ringwald 
36719d9bbc01Smatthias.ringwald     // fill in
36729d9bbc01Smatthias.ringwald     service->psm = psm;
36739d9bbc01Smatthias.ringwald     service->mtu = mtu;
367405ae8de3SMatthias Ringwald     service->packet_handler = service_packet_handler;
3675df3354fcS[email protected]     service->required_security_level = security_level;
36769d9bbc01Smatthias.ringwald 
36779d9bbc01Smatthias.ringwald     // add to services list
3678665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
3679c0e866bfSmatthias.ringwald 
3680c0e866bfSmatthias.ringwald     // enable page scan
368115a95bd5SMatthias Ringwald     gap_connectable_control(1);
36825842b6d9Smatthias.ringwald 
3683c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
36849d9bbc01Smatthias.ringwald }
36859d9bbc01Smatthias.ringwald 
36867e8856ebSMatthias Ringwald uint8_t l2cap_unregister_service(uint16_t psm){
3687e0abb8e7S[email protected] 
3688e0abb8e7S[email protected]     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
3689e0abb8e7S[email protected] 
36909d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
36917e8856ebSMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3692665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
3693d3a9df87Smatthias.ringwald     btstack_memory_l2cap_service_free(service);
3694c0e866bfSmatthias.ringwald 
3695c0e866bfSmatthias.ringwald     // disable page scan when no services registered
36967e8856ebSMatthias Ringwald     if (btstack_linked_list_empty(&l2cap_services)) {
369715a95bd5SMatthias Ringwald         gap_connectable_control(0);
36989d9bbc01Smatthias.ringwald     }
3699c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
37007e8856ebSMatthias Ringwald }
370109e9d05bSMatthias Ringwald #endif
37029d9bbc01Smatthias.ringwald 
37037192e786SMatthias Ringwald 
3704cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
370583fd9c76SMatthias Ringwald 
370657be49d6SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
370757be49d6SMatthias Ringwald     if (!channel->waiting_for_can_send_now) return;
370857be49d6SMatthias Ringwald     if (channel->send_sdu_buffer) return;
370957be49d6SMatthias Ringwald     channel->waiting_for_can_send_now = 0;
3710895ff4a5SMatthias Ringwald     log_debug("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
371157be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
371257be49d6SMatthias Ringwald }
371357be49d6SMatthias Ringwald 
371457be49d6SMatthias Ringwald // 1BH2222
371557be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
371657be49d6SMatthias 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",
371757be49d6SMatthias Ringwald              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
371857be49d6SMatthias Ringwald     uint8_t event[19];
371957be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
372057be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
372157be49d6SMatthias Ringwald     event[2] = channel->address_type;
372257be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
372357be49d6SMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
372457be49d6SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
372557be49d6SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
372657be49d6SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
372757be49d6SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_mtu);
372857be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
372957be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
373057be49d6SMatthias Ringwald }
373157be49d6SMatthias Ringwald // 11BH22222
373257be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
373357be49d6SMatthias 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",
373457be49d6SMatthias Ringwald              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
373557be49d6SMatthias Ringwald              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
3736c99bb618SMatthias Ringwald     uint8_t event[23];
373757be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
373857be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
373957be49d6SMatthias Ringwald     event[2] = status;
374057be49d6SMatthias Ringwald     event[3] = channel->address_type;
374157be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[4]);
374257be49d6SMatthias Ringwald     little_endian_store_16(event, 10, channel->con_handle);
3743*c1ab6cc1SMatthias Ringwald     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
3744c99bb618SMatthias Ringwald     little_endian_store_16(event, 13, channel->psm);
3745c99bb618SMatthias Ringwald     little_endian_store_16(event, 15, channel->local_cid);
3746c99bb618SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_cid);
3747c99bb618SMatthias Ringwald     little_endian_store_16(event, 19, channel->local_mtu);
3748c99bb618SMatthias Ringwald     little_endian_store_16(event, 21, channel->remote_mtu);
374957be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
375057be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
375157be49d6SMatthias Ringwald }
375287050a0bSMatthias Ringwald // 2
375387050a0bSMatthias Ringwald static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel){
375487050a0bSMatthias Ringwald     log_info("L2CAP_EVENT_LE_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
375587050a0bSMatthias Ringwald     uint8_t event[4];
375687050a0bSMatthias Ringwald     event[0] = L2CAP_EVENT_LE_CHANNEL_CLOSED;
375787050a0bSMatthias Ringwald     event[1] = sizeof(event) - 2;
375887050a0bSMatthias Ringwald     little_endian_store_16(event, 2, channel->local_cid);
375987050a0bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
376087050a0bSMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
376187050a0bSMatthias Ringwald }
376287050a0bSMatthias Ringwald 
37636774d5c9SMatthias Ringwald static void l2cap_le_send_pdu(l2cap_channel_t *channel){
37646774d5c9SMatthias Ringwald     btstack_assert(channel != NULL);
37656774d5c9SMatthias Ringwald     btstack_assert(channel->send_pdu_buffer != NULL);
37666774d5c9SMatthias Ringwald     btstack_assert(channel->credits_outgoing > 0);
37676774d5c9SMatthias Ringwald 
37686774d5c9SMatthias Ringwald     // send part of SDU
37696774d5c9SMatthias Ringwald     hci_reserve_packet_buffer();
37706774d5c9SMatthias Ringwald     uint8_t * acl_buffer = hci_get_outgoing_packet_buffer();
37716774d5c9SMatthias Ringwald     uint8_t * l2cap_payload = acl_buffer + 8;
37726774d5c9SMatthias Ringwald     uint16_t pos = 0;
37736774d5c9SMatthias Ringwald     if (!channel->send_sdu_pos){
37746774d5c9SMatthias Ringwald         // store SDU len
37756774d5c9SMatthias Ringwald         channel->send_sdu_pos += 2;
37766774d5c9SMatthias Ringwald         little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
37776774d5c9SMatthias Ringwald         pos += 2;
37786774d5c9SMatthias Ringwald     }
37796774d5c9SMatthias Ringwald     uint16_t payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
37806774d5c9SMatthias Ringwald     log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
37816774d5c9SMatthias Ringwald     memcpy(&l2cap_payload[pos], &channel->send_sdu_buffer[channel->send_sdu_pos-2], payload_size); // -2 for virtual SDU len
37826774d5c9SMatthias Ringwald     pos += payload_size;
37836774d5c9SMatthias Ringwald     channel->send_sdu_pos += payload_size;
37846774d5c9SMatthias Ringwald     l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
37856774d5c9SMatthias Ringwald 
37866774d5c9SMatthias Ringwald     channel->credits_outgoing--;
37876774d5c9SMatthias Ringwald 
37886774d5c9SMatthias Ringwald     hci_send_acl_packet_buffer(8 + pos);
37896774d5c9SMatthias Ringwald 
3790*c1ab6cc1SMatthias Ringwald     if (channel->send_sdu_pos >= (channel->send_sdu_len + 2)){
37916774d5c9SMatthias Ringwald         channel->send_sdu_buffer = NULL;
37926774d5c9SMatthias Ringwald         // send done event
37936774d5c9SMatthias Ringwald         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
37946774d5c9SMatthias Ringwald         // inform about can send now
37956774d5c9SMatthias Ringwald         l2cap_le_notify_channel_can_send(channel);
37966774d5c9SMatthias Ringwald     }
37976774d5c9SMatthias Ringwald }
37986774d5c9SMatthias Ringwald 
379957be49d6SMatthias Ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
380057be49d6SMatthias Ringwald void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
380157be49d6SMatthias Ringwald     channel->state = L2CAP_STATE_CLOSED;
380257be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
380357be49d6SMatthias Ringwald     // discard channel
3804421cb104SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3805c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
380657be49d6SMatthias Ringwald }
380757be49d6SMatthias Ringwald 
3808e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
3809e7d0c9aaSMatthias Ringwald     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
38107192e786SMatthias Ringwald }
3811efedfb4cSMatthias Ringwald 
3812da144af5SMatthias Ringwald uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
38137192e786SMatthias Ringwald 
3814da144af5SMatthias Ringwald     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
38157192e786SMatthias Ringwald 
38167192e786SMatthias Ringwald     // check for alread registered psm
38177192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
38187192e786SMatthias Ringwald     if (service) {
3819da144af5SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
38207192e786SMatthias Ringwald     }
38217192e786SMatthias Ringwald 
38227192e786SMatthias Ringwald     // alloc structure
38237192e786SMatthias Ringwald     service = btstack_memory_l2cap_service_get();
38247192e786SMatthias Ringwald     if (!service) {
38257192e786SMatthias Ringwald         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
3826da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
38277192e786SMatthias Ringwald     }
38287192e786SMatthias Ringwald 
38297192e786SMatthias Ringwald     // fill in
38307192e786SMatthias Ringwald     service->psm = psm;
3831da144af5SMatthias Ringwald     service->mtu = 0;
38327192e786SMatthias Ringwald     service->packet_handler = packet_handler;
38337192e786SMatthias Ringwald     service->required_security_level = security_level;
38347192e786SMatthias Ringwald 
38357192e786SMatthias Ringwald     // add to services list
3836665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
38377192e786SMatthias Ringwald 
38387192e786SMatthias Ringwald     // done
38399dd26175SMilanka Ringwald     return ERROR_CODE_SUCCESS;
38407192e786SMatthias Ringwald }
38417192e786SMatthias Ringwald 
3842da144af5SMatthias Ringwald uint8_t l2cap_le_unregister_service(uint16_t psm) {
38437192e786SMatthias Ringwald     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
38447192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
38459367f9b0SMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3846da144af5SMatthias Ringwald 
3847665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
38487192e786SMatthias Ringwald     btstack_memory_l2cap_service_free(service);
3849c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
38507192e786SMatthias Ringwald }
3851da144af5SMatthias Ringwald 
3852da144af5SMatthias Ringwald uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
3853e7d0c9aaSMatthias Ringwald     // get channel
3854421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3855e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3856e7d0c9aaSMatthias Ringwald 
3857e7d0c9aaSMatthias Ringwald     // validate state
3858e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3859e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
3860e7d0c9aaSMatthias Ringwald     }
3861e7d0c9aaSMatthias Ringwald 
3862efedfb4cSMatthias Ringwald     // set state accept connection
386323017473SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
386423017473SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
386523017473SMatthias Ringwald     channel->local_mtu = mtu;
386685aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
386785aeef60SMatthias Ringwald     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
386885aeef60SMatthias Ringwald 
386985aeef60SMatthias Ringwald     // test
387063f0ac45SMatthias Ringwald     // channel->new_credits_incoming = 1;
3871e7d0c9aaSMatthias Ringwald 
3872e7d0c9aaSMatthias Ringwald     // go
3873e7d0c9aaSMatthias Ringwald     l2cap_run();
3874c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
3875da144af5SMatthias Ringwald }
3876da144af5SMatthias Ringwald 
3877da144af5SMatthias Ringwald /**
3878da144af5SMatthias Ringwald  * @brief Deny incoming LE Data Channel connection due to resource constraints
3879da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3880da144af5SMatthias Ringwald  */
3881da144af5SMatthias Ringwald 
3882da144af5SMatthias Ringwald uint8_t l2cap_le_decline_connection(uint16_t local_cid){
3883e7d0c9aaSMatthias Ringwald     // get channel
3884421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3885e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3886e7d0c9aaSMatthias Ringwald 
3887e7d0c9aaSMatthias Ringwald     // validate state
3888e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3889e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
3890e7d0c9aaSMatthias Ringwald     }
3891e7d0c9aaSMatthias Ringwald 
3892efedfb4cSMatthias Ringwald     // set state decline connection
3893e7d0c9aaSMatthias Ringwald     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
3894e7d0c9aaSMatthias Ringwald     channel->reason = 0x04; // no resources available
3895e7d0c9aaSMatthias Ringwald     l2cap_run();
3896c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
3897da144af5SMatthias Ringwald }
3898da144af5SMatthias Ringwald 
38997dafa750SMatthias Ringwald uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
3900da144af5SMatthias Ringwald     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
3901efedfb4cSMatthias Ringwald     uint16_t * out_local_cid) {
3902efedfb4cSMatthias Ringwald 
39037dafa750SMatthias Ringwald     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
3904da144af5SMatthias Ringwald 
39057dafa750SMatthias Ringwald 
39067dafa750SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
39077dafa750SMatthias Ringwald     if (!connection) {
39087dafa750SMatthias Ringwald         log_error("no hci_connection for handle 0x%04x", con_handle);
39097dafa750SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
39107dafa750SMatthias Ringwald     }
39117dafa750SMatthias Ringwald 
39125d18f623SMatthias 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);
3913da144af5SMatthias Ringwald     if (!channel) {
3914da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
3915da144af5SMatthias Ringwald     }
3916e7d0c9aaSMatthias Ringwald     log_info("l2cap_le_create_channel %p", channel);
3917da144af5SMatthias Ringwald 
3918da144af5SMatthias Ringwald     // store local_cid
3919da144af5SMatthias Ringwald     if (out_local_cid){
3920da144af5SMatthias Ringwald        *out_local_cid = channel->local_cid;
3921da144af5SMatthias Ringwald     }
3922da144af5SMatthias Ringwald 
39237dafa750SMatthias Ringwald     // provide buffer
39247dafa750SMatthias Ringwald     channel->con_handle = con_handle;
3925cd529728SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
39267dafa750SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
392785aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
392885aeef60SMatthias Ringwald     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
392985aeef60SMatthias Ringwald 
3930efedfb4cSMatthias Ringwald     // add to connections list
3931421cb104SMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
3932efedfb4cSMatthias Ringwald 
39337dafa750SMatthias Ringwald     // go
393463f0ac45SMatthias Ringwald     l2cap_run();
3935c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
3936da144af5SMatthias Ringwald }
3937da144af5SMatthias Ringwald 
3938da144af5SMatthias Ringwald /**
3939da144af5SMatthias Ringwald  * @brief Provide credtis for LE Data Channel
3940da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3941da144af5SMatthias Ringwald  * @param credits               Number additional credits for peer
3942da144af5SMatthias Ringwald  */
394364e11ca9SMatthias Ringwald uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
394463f0ac45SMatthias Ringwald 
3945421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
394663f0ac45SMatthias Ringwald     if (!channel) {
394763f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
394863f0ac45SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
394963f0ac45SMatthias Ringwald     }
395063f0ac45SMatthias Ringwald 
3951efedfb4cSMatthias Ringwald     // check state
395263f0ac45SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN){
395363f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
395463f0ac45SMatthias Ringwald     }
395563f0ac45SMatthias Ringwald 
395663f0ac45SMatthias Ringwald     // assert incoming credits + credits <= 0xffff
395763f0ac45SMatthias Ringwald     uint32_t total_credits = channel->credits_incoming;
395863f0ac45SMatthias Ringwald     total_credits += channel->new_credits_incoming;
395963f0ac45SMatthias Ringwald     total_credits += credits;
396063f0ac45SMatthias Ringwald     if (total_credits > 0xffff){
396163f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
396263f0ac45SMatthias Ringwald             channel->new_credits_incoming, credits);
396363f0ac45SMatthias Ringwald     }
396463f0ac45SMatthias Ringwald 
3965efedfb4cSMatthias Ringwald     // set credits_granted
396663f0ac45SMatthias Ringwald     channel->new_credits_incoming += credits;
396763f0ac45SMatthias Ringwald 
396863f0ac45SMatthias Ringwald     // go
396963f0ac45SMatthias Ringwald     l2cap_run();
39709dd26175SMilanka Ringwald     return ERROR_CODE_SUCCESS;
3971da144af5SMatthias Ringwald }
3972da144af5SMatthias Ringwald 
3973da144af5SMatthias Ringwald /**
3974da144af5SMatthias Ringwald  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
3975da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3976da144af5SMatthias Ringwald  */
397764e11ca9SMatthias Ringwald int l2cap_le_can_send_now(uint16_t local_cid){
3978421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
397944276248SMatthias Ringwald     if (!channel) {
398044276248SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
3981da144af5SMatthias Ringwald         return 0;
3982da144af5SMatthias Ringwald     }
3983da144af5SMatthias Ringwald 
398444276248SMatthias Ringwald     // check state
398544276248SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN) return 0;
398644276248SMatthias Ringwald 
398744276248SMatthias Ringwald     // check queue
398844276248SMatthias Ringwald     if (channel->send_sdu_buffer) return 0;
398944276248SMatthias Ringwald 
399044276248SMatthias Ringwald     // fine, go ahead
399144276248SMatthias Ringwald     return 1;
399244276248SMatthias Ringwald }
399344276248SMatthias Ringwald 
3994da144af5SMatthias Ringwald /**
3995da144af5SMatthias Ringwald  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
3996da144af5SMatthias Ringwald  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
3997da144af5SMatthias Ringwald  *       so packet handler should be ready to handle it
3998da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3999da144af5SMatthias Ringwald  */
400064e11ca9SMatthias Ringwald uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
4001421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
400244276248SMatthias Ringwald     if (!channel) {
400344276248SMatthias Ringwald         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
4004c8b2b785SMilanka Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
400544276248SMatthias Ringwald     }
400644276248SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
400744276248SMatthias Ringwald     l2cap_le_notify_channel_can_send(channel);
4008c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
4009da144af5SMatthias Ringwald }
4010da144af5SMatthias Ringwald 
4011da144af5SMatthias Ringwald /**
4012da144af5SMatthias Ringwald  * @brief Send data via LE Data Channel
4013da144af5SMatthias Ringwald  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
4014da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
4015da144af5SMatthias Ringwald  * @param data                  data to send
4016da144af5SMatthias Ringwald  * @param size                  data size
4017da144af5SMatthias Ringwald  */
401864e11ca9SMatthias Ringwald uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
401964e11ca9SMatthias Ringwald 
4020421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
402164e11ca9SMatthias Ringwald     if (!channel) {
402264e11ca9SMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4023828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
402464e11ca9SMatthias Ringwald     }
402564e11ca9SMatthias Ringwald 
402664e11ca9SMatthias Ringwald     if (len > channel->remote_mtu){
402764e11ca9SMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
402864e11ca9SMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
402964e11ca9SMatthias Ringwald     }
403064e11ca9SMatthias Ringwald 
40317f107edaSMatthias Ringwald     if (channel->send_sdu_buffer){
403264e11ca9SMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
403364e11ca9SMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
403464e11ca9SMatthias Ringwald     }
403564e11ca9SMatthias Ringwald 
40367f107edaSMatthias Ringwald     channel->send_sdu_buffer = data;
40377f107edaSMatthias Ringwald     channel->send_sdu_len    = len;
40387f107edaSMatthias Ringwald     channel->send_sdu_pos    = 0;
403964e11ca9SMatthias Ringwald 
40406774d5c9SMatthias Ringwald     l2cap_notify_channel_can_send();
4041c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
4042da144af5SMatthias Ringwald }
4043da144af5SMatthias Ringwald 
4044da144af5SMatthias Ringwald /**
4045da144af5SMatthias Ringwald  * @brief Disconnect from LE Data Channel
4046da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
4047da144af5SMatthias Ringwald  */
4048828a7f7aSMatthias Ringwald uint8_t l2cap_le_disconnect(uint16_t local_cid)
4049da144af5SMatthias Ringwald {
4050421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4051828a7f7aSMatthias Ringwald     if (!channel) {
4052828a7f7aSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4053828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4054828a7f7aSMatthias Ringwald     }
4055828a7f7aSMatthias Ringwald 
4056828a7f7aSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4057828a7f7aSMatthias Ringwald     l2cap_run();
4058c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
4059da144af5SMatthias Ringwald }
4060da144af5SMatthias Ringwald 
40617f02f414SMatthias Ringwald #endif
4062