xref: /btstack/src/l2cap.c (revision 6535961a1f105e850ecdf294c128b9fc982ee05a)
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);
380*6535961aSMatthias Ringwald     (void)memcpy(&acl_buffer[8 + 2],
381*6535961aSMatthias Ringwald                  &channel->tx_packets_data[index * channel->local_mps],
382*6535961aSMatthias Ringwald                  tx_state->len);
3831e1a46bbSMatthias Ringwald     // (re-)start retransmission timer on
3841e1a46bbSMatthias Ringwald     l2cap_ertm_start_retransmission_timer(channel);
385474f5c3fSMatthias Ringwald     // send
386474f5c3fSMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2 + tx_state->len);
387474f5c3fSMatthias Ringwald }
388474f5c3fSMatthias Ringwald 
389474f5c3fSMatthias Ringwald static void l2cap_ertm_store_fragment(l2cap_channel_t * channel, l2cap_segmentation_and_reassembly_t sar, uint16_t sdu_length, uint8_t * data, uint16_t len){
390474f5c3fSMatthias Ringwald     // get next index for storing packets
391474f5c3fSMatthias Ringwald     int index = channel->tx_write_index;
392474f5c3fSMatthias Ringwald 
393474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
394474f5c3fSMatthias Ringwald     tx_state->tx_seq = channel->next_tx_seq;
395474f5c3fSMatthias Ringwald     tx_state->sar = sar;
396474f5c3fSMatthias Ringwald     tx_state->retry_count = 0;
397474f5c3fSMatthias Ringwald 
3983b81f0d3SMatthias Ringwald     uint8_t * tx_packet = &channel->tx_packets_data[index * channel->local_mps];
399b90eac91SMatthias Ringwald     log_debug("index %u, local mps %u, remote mps %u, packet tx %p, len %u", index, channel->local_mps, channel->remote_mps, tx_packet, len);
400474f5c3fSMatthias Ringwald     int pos = 0;
401474f5c3fSMatthias Ringwald     if (sar == L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU){
402474f5c3fSMatthias Ringwald         little_endian_store_16(tx_packet, 0, sdu_length);
403474f5c3fSMatthias Ringwald         pos += 2;
404474f5c3fSMatthias Ringwald     }
405*6535961aSMatthias Ringwald     (void)memcpy(&tx_packet[pos], data, len);
406b90eac91SMatthias Ringwald     tx_state->len = pos + len;
407474f5c3fSMatthias Ringwald 
408474f5c3fSMatthias Ringwald     // update
409a8409e80SMatthias Ringwald     channel->num_stored_tx_frames++;
410474f5c3fSMatthias Ringwald     channel->next_tx_seq = l2cap_next_ertm_seq_nr(channel->next_tx_seq);
411474f5c3fSMatthias Ringwald     l2cap_ertm_next_tx_write_index(channel);
41294301352SMatthias Ringwald 
413a8409e80SMatthias Ringwald     log_info("l2cap_ertm_store_fragment: tx_read_index %u, tx_write_index %u, num stored %u", channel->tx_read_index, channel->tx_write_index, channel->num_stored_tx_frames);
41494301352SMatthias Ringwald 
415474f5c3fSMatthias Ringwald }
416474f5c3fSMatthias Ringwald 
417474f5c3fSMatthias Ringwald static int l2cap_ertm_send(l2cap_channel_t * channel, uint8_t * data, uint16_t len){
418474f5c3fSMatthias Ringwald     if (len > channel->remote_mtu){
419a8409e80SMatthias Ringwald         log_error("l2cap_ertm_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
420474f5c3fSMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
421474f5c3fSMatthias Ringwald     }
422474f5c3fSMatthias Ringwald 
423a8409e80SMatthias Ringwald     if (!l2cap_ertm_can_store_packet_now(channel)){
424a8409e80SMatthias Ringwald         log_error("l2cap_ertm_send cid 0x%02x, fragment store full", channel->local_cid);
425a8409e80SMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
426a8409e80SMatthias Ringwald     }
427a8409e80SMatthias Ringwald 
428474f5c3fSMatthias Ringwald     // check if it needs to get fragmented
429b90eac91SMatthias Ringwald     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
430b90eac91SMatthias Ringwald     if (len > effective_mps){
431474f5c3fSMatthias Ringwald         // fragmentation needed.
432474f5c3fSMatthias Ringwald         l2cap_segmentation_and_reassembly_t sar =  L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU;
433474f5c3fSMatthias Ringwald         int chunk_len;
434474f5c3fSMatthias Ringwald         while (len){
435474f5c3fSMatthias Ringwald             switch (sar){
436474f5c3fSMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
437b90eac91SMatthias Ringwald                     chunk_len = effective_mps - 2;    // sdu_length
438474f5c3fSMatthias Ringwald                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
439474f5c3fSMatthias Ringwald                     len -= chunk_len;
440474f5c3fSMatthias Ringwald                     sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU;
441474f5c3fSMatthias Ringwald                     break;
442474f5c3fSMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
443b90eac91SMatthias Ringwald                     chunk_len = effective_mps;
444474f5c3fSMatthias Ringwald                     if (chunk_len >= len){
445474f5c3fSMatthias Ringwald                         sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU;
446474f5c3fSMatthias Ringwald                         chunk_len = len;
447474f5c3fSMatthias Ringwald                     }
448474f5c3fSMatthias Ringwald                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
449474f5c3fSMatthias Ringwald                     len -= chunk_len;
450474f5c3fSMatthias Ringwald                     break;
451474f5c3fSMatthias Ringwald                 default:
452474f5c3fSMatthias Ringwald                     break;
453474f5c3fSMatthias Ringwald             }
454474f5c3fSMatthias Ringwald         }
455474f5c3fSMatthias Ringwald 
456474f5c3fSMatthias Ringwald     } else {
457474f5c3fSMatthias Ringwald         l2cap_ertm_store_fragment(channel, L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU, 0, data, len);
458474f5c3fSMatthias Ringwald     }
459474f5c3fSMatthias Ringwald 
460474f5c3fSMatthias Ringwald     // try to send
461d89ab698SMatthias Ringwald     l2cap_notify_channel_can_send();
462474f5c3fSMatthias Ringwald     return 0;
463474f5c3fSMatthias Ringwald }
464474f5c3fSMatthias Ringwald 
4657cbe539fSMatthias Ringwald static uint16_t l2cap_setup_options_ertm_request(l2cap_channel_t * channel, uint8_t * config_options){
466fcb125edSMatthias Ringwald     int pos = 0;
467fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
468fcb125edSMatthias Ringwald     config_options[pos++] = 9;      // length
469fcb125edSMatthias Ringwald     config_options[pos++] = (uint8_t) channel->mode;
470fcb125edSMatthias Ringwald     config_options[pos++] = channel->num_rx_buffers;    // == TxWindows size
471fcb125edSMatthias Ringwald     config_options[pos++] = channel->local_max_transmit;
472fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
473fcb125edSMatthias Ringwald     pos += 2;
474fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
475fcb125edSMatthias Ringwald     pos += 2;
476fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_mps);
477fcb125edSMatthias Ringwald     pos += 2;
4786574158aSMatthias Ringwald     //
479fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT;
480fcb125edSMatthias Ringwald     config_options[pos++] = 2;     // length
481fcb125edSMatthias Ringwald     little_endian_store_16(config_options, pos, channel->local_mtu);
482fcb125edSMatthias Ringwald     pos += 2;
483c425ea4aSMatthias Ringwald 
484c425ea4aSMatthias Ringwald     // Issue: iOS (e.g. 10.2) uses "No FCS" as default while Core 5.0 specifies "FCS" as default
485c425ea4aSMatthias Ringwald     // Workaround: try to actively negotiate FCS option
486fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
487fcb125edSMatthias Ringwald     config_options[pos++] = 1;     // length
488fcb125edSMatthias Ringwald     config_options[pos++] = channel->fcs_option;
489f2c70799Sandryblack     return pos; // 11+4+3=18
490474f5c3fSMatthias Ringwald }
491474f5c3fSMatthias Ringwald 
4927cbe539fSMatthias Ringwald static uint16_t l2cap_setup_options_ertm_response(l2cap_channel_t * channel, uint8_t * config_options){
493fcb125edSMatthias Ringwald     int pos = 0;
494fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
495fcb125edSMatthias Ringwald     config_options[pos++] = 9;      // length
496fcb125edSMatthias Ringwald     config_options[pos++] = (uint8_t) channel->mode;
4977cbe539fSMatthias Ringwald     // less or equal to remote tx window size
498fcb125edSMatthias Ringwald     config_options[pos++] = btstack_min(channel->num_tx_buffers, channel->remote_tx_window_size);
4997cbe539fSMatthias Ringwald     // max transmit in response shall be ignored -> use sender values
500fcb125edSMatthias Ringwald     config_options[pos++] = channel->remote_max_transmit;
5017cbe539fSMatthias Ringwald     // A value for the Retransmission time-out shall be sent in a positive Configuration Response
5027cbe539fSMatthias Ringwald     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
503fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
504fcb125edSMatthias Ringwald     pos += 2;
5057cbe539fSMatthias Ringwald     // A value for the Monitor time-out shall be sent in a positive Configuration Response
5067cbe539fSMatthias Ringwald     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
507fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
508fcb125edSMatthias Ringwald     pos += 2;
5097cbe539fSMatthias Ringwald     // less or equal to remote mps
510b90eac91SMatthias Ringwald     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
511b90eac91SMatthias Ringwald     little_endian_store_16( config_options, pos, effective_mps);
512fcb125edSMatthias Ringwald     pos += 2;
5136574158aSMatthias Ringwald     //
514fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
515fcb125edSMatthias Ringwald     config_options[pos++] = 2;     // length
516fcb125edSMatthias Ringwald     little_endian_store_16(config_options, pos, channel->remote_mtu);
517fcb125edSMatthias Ringwald     pos += 2;
518fcb125edSMatthias Ringwald #if 0
519d64e9771SMatthias Ringwald     //
520fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
521fcb125edSMatthias Ringwald     config_options[pos++] = 1;     // length
522fcb125edSMatthias Ringwald     config_options[pos++] = channel->fcs_option;
523fcb125edSMatthias Ringwald #endif
524f2c70799Sandryblack     return pos; // 11+4=15
5257cbe539fSMatthias Ringwald }
5267cbe539fSMatthias Ringwald 
527474f5c3fSMatthias Ringwald static int l2cap_ertm_send_supervisor_frame(l2cap_channel_t * channel, uint16_t control){
528474f5c3fSMatthias Ringwald     hci_reserve_packet_buffer();
529474f5c3fSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
530474f5c3fSMatthias Ringwald     log_info("S-Frame: control 0x%04x", control);
531474f5c3fSMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
532474f5c3fSMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2);
533474f5c3fSMatthias Ringwald }
534474f5c3fSMatthias Ringwald 
5355774a392SMatthias Ringwald static uint8_t l2cap_ertm_validate_local_config(l2cap_ertm_config_t * ertm_config){
536474f5c3fSMatthias Ringwald 
537474f5c3fSMatthias Ringwald     uint8_t result = ERROR_CODE_SUCCESS;
5389c0e62d3SMatthias Ringwald     if (ertm_config->max_transmit < 1){
539474f5c3fSMatthias Ringwald         log_error("max_transmit must be >= 1");
540474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
541474f5c3fSMatthias Ringwald     }
5429c0e62d3SMatthias Ringwald     if (ertm_config->retransmission_timeout_ms < 2000){
543474f5c3fSMatthias Ringwald         log_error("retransmission_timeout_ms must be >= 2000 ms");
544474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
545474f5c3fSMatthias Ringwald     }
5469c0e62d3SMatthias Ringwald     if (ertm_config->monitor_timeout_ms < 12000){
547474f5c3fSMatthias Ringwald         log_error("monitor_timeout_ms must be >= 12000 ms");
548474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
549474f5c3fSMatthias Ringwald     }
5509c0e62d3SMatthias Ringwald     if (ertm_config->local_mtu < 48){
551474f5c3fSMatthias Ringwald         log_error("local_mtu must be >= 48");
552474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
553474f5c3fSMatthias Ringwald     }
5549c0e62d3SMatthias Ringwald     if (ertm_config->num_rx_buffers < 1){
555474f5c3fSMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
556474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
557474f5c3fSMatthias Ringwald     }
5589c0e62d3SMatthias Ringwald     if (ertm_config->num_tx_buffers < 1){
559474f5c3fSMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
560474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
561474f5c3fSMatthias Ringwald     }
562474f5c3fSMatthias Ringwald     return result;
563474f5c3fSMatthias Ringwald }
564474f5c3fSMatthias Ringwald 
5659c0e62d3SMatthias Ringwald static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
566474f5c3fSMatthias Ringwald 
567474f5c3fSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
5689c0e62d3SMatthias Ringwald     channel->ertm_mandatory = ertm_config->ertm_mandatory;
5699c0e62d3SMatthias Ringwald     channel->local_max_transmit = ertm_config->max_transmit;
5709c0e62d3SMatthias Ringwald     channel->local_retransmission_timeout_ms = ertm_config->retransmission_timeout_ms;
5719c0e62d3SMatthias Ringwald     channel->local_monitor_timeout_ms = ertm_config->monitor_timeout_ms;
5729c0e62d3SMatthias Ringwald     channel->local_mtu = ertm_config->local_mtu;
5739c0e62d3SMatthias Ringwald     channel->num_rx_buffers = ertm_config->num_rx_buffers;
5749c0e62d3SMatthias Ringwald     channel->num_tx_buffers = ertm_config->num_tx_buffers;
575474f5c3fSMatthias Ringwald 
576c342091bSMatthias Ringwald     // align buffer to 16-byte boundary to assert l2cap_ertm_rx_packet_state_t is aligned
577474f5c3fSMatthias Ringwald     int bytes_till_alignment = 16 - (((uintptr_t) buffer) & 0x0f);
578474f5c3fSMatthias Ringwald     buffer += bytes_till_alignment;
579474f5c3fSMatthias Ringwald     size   -= bytes_till_alignment;
580474f5c3fSMatthias Ringwald 
581c342091bSMatthias Ringwald     // setup state buffers - use void cast to avoid -Wcast-align warning
582474f5c3fSMatthias Ringwald     uint32_t pos = 0;
583c342091bSMatthias Ringwald     channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) (void *) &buffer[pos];
5849c0e62d3SMatthias Ringwald     pos += ertm_config->num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
585c342091bSMatthias Ringwald     channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) (void *) &buffer[pos];
5869c0e62d3SMatthias Ringwald     pos += ertm_config->num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
587474f5c3fSMatthias Ringwald 
588474f5c3fSMatthias Ringwald     // setup reassembly buffer
589474f5c3fSMatthias Ringwald     channel->reassembly_buffer = &buffer[pos];
5909c0e62d3SMatthias Ringwald     pos += ertm_config->local_mtu;
591474f5c3fSMatthias Ringwald 
592474f5c3fSMatthias Ringwald     // divide rest of data equally
5939c0e62d3SMatthias Ringwald     channel->local_mps = (size - pos) / (ertm_config->num_rx_buffers + ertm_config->num_tx_buffers);
5940d3ee2efSMatthias Ringwald     log_info("Local MPS: %u", channel->local_mps);
595474f5c3fSMatthias Ringwald     channel->rx_packets_data = &buffer[pos];
5960d3ee2efSMatthias Ringwald     pos += ertm_config->num_rx_buffers * channel->local_mps;
597474f5c3fSMatthias Ringwald     channel->tx_packets_data = &buffer[pos];
5986574158aSMatthias Ringwald 
599c425ea4aSMatthias Ringwald     channel->fcs_option = ertm_config->fcs_option;
600474f5c3fSMatthias Ringwald }
601474f5c3fSMatthias Ringwald 
602474f5c3fSMatthias Ringwald uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
6039c0e62d3SMatthias Ringwald     l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
604474f5c3fSMatthias Ringwald 
6059c0e62d3SMatthias Ringwald     log_info("L2CAP_CREATE_ERTM_CHANNEL addr %s, psm 0x%x, local mtu %u", bd_addr_to_str(address), psm, ertm_config->local_mtu);
606474f5c3fSMatthias Ringwald 
607474f5c3fSMatthias Ringwald     // validate local config
6085774a392SMatthias Ringwald     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
609474f5c3fSMatthias Ringwald     if (result) return result;
610474f5c3fSMatthias Ringwald 
611f16129ceSMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, address, BD_ADDR_TYPE_ACL, psm, ertm_config->local_mtu, LEVEL_0);
612474f5c3fSMatthias Ringwald     if (!channel) {
613474f5c3fSMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
614474f5c3fSMatthias Ringwald     }
615474f5c3fSMatthias Ringwald 
616474f5c3fSMatthias Ringwald     // configure ERTM
6179c0e62d3SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
618474f5c3fSMatthias Ringwald 
619474f5c3fSMatthias Ringwald     // add to connections list
620474f5c3fSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
621474f5c3fSMatthias Ringwald 
622474f5c3fSMatthias Ringwald     // store local_cid
623474f5c3fSMatthias Ringwald     if (out_local_cid){
624474f5c3fSMatthias Ringwald        *out_local_cid = channel->local_cid;
625474f5c3fSMatthias Ringwald     }
626474f5c3fSMatthias Ringwald 
627474f5c3fSMatthias Ringwald     // check if hci connection is already usable
628f16129ceSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
629474f5c3fSMatthias Ringwald     if (conn){
630474f5c3fSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
631474f5c3fSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
632474f5c3fSMatthias Ringwald         // check if remote supported fearures are already received
633474f5c3fSMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
634474f5c3fSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
635474f5c3fSMatthias Ringwald         }
636474f5c3fSMatthias Ringwald     }
637474f5c3fSMatthias Ringwald 
638474f5c3fSMatthias Ringwald     l2cap_run();
639474f5c3fSMatthias Ringwald 
640474f5c3fSMatthias Ringwald     return 0;
641474f5c3fSMatthias Ringwald }
642474f5c3fSMatthias Ringwald 
643474f5c3fSMatthias Ringwald static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel){
644474f5c3fSMatthias Ringwald     if (l2cap_ertm_can_store_packet_now(channel)){
645474f5c3fSMatthias Ringwald         channel->waiting_for_can_send_now = 0;
646474f5c3fSMatthias Ringwald         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
647474f5c3fSMatthias Ringwald     }
648474f5c3fSMatthias Ringwald }
649474f5c3fSMatthias Ringwald 
6509c0e62d3SMatthias Ringwald uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
651474f5c3fSMatthias Ringwald 
652474f5c3fSMatthias Ringwald     log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
653f68b21d7SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
654474f5c3fSMatthias Ringwald     if (!channel) {
655474f5c3fSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
656474f5c3fSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
657474f5c3fSMatthias Ringwald     }
658474f5c3fSMatthias Ringwald 
659474f5c3fSMatthias Ringwald     // validate local config
6605774a392SMatthias Ringwald     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
661474f5c3fSMatthias Ringwald     if (result) return result;
662474f5c3fSMatthias Ringwald 
663474f5c3fSMatthias Ringwald     // configure L2CAP ERTM
6649c0e62d3SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
665474f5c3fSMatthias Ringwald 
666836ae835SMatthias Ringwald     // default: continue
667474f5c3fSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
668474f5c3fSMatthias Ringwald 
6698b7155e0SMatthias Ringwald     // verify remote ERTM support
670836ae835SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
671836ae835SMatthias Ringwald     if (connection == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
672836ae835SMatthias Ringwald 
673836ae835SMatthias Ringwald     if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
6748b7155e0SMatthias Ringwald         // ERTM not possible, select basic mode and release buffer
6758b7155e0SMatthias Ringwald         channel->mode = L2CAP_CHANNEL_MODE_BASIC;
6768b7155e0SMatthias Ringwald         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
677836ae835SMatthias Ringwald 
6788b7155e0SMatthias Ringwald         // bail if ERTM is mandatory
679836ae835SMatthias Ringwald         if (channel->ertm_mandatory){
680836ae835SMatthias Ringwald             // We chose 'no resources available' for "ERTM mandatory but you don't even know ERTM exists"
6818b7155e0SMatthias Ringwald             log_info("ERTM mandatory -> reject connection");
682836ae835SMatthias Ringwald             channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
683836ae835SMatthias Ringwald             channel->reason = 0x04; // no resources available
6848b7155e0SMatthias Ringwald         }  else {
6858b7155e0SMatthias Ringwald             log_info("ERTM not supported by remote -> use Basic mode");
686836ae835SMatthias Ringwald         }
687836ae835SMatthias Ringwald     }
688836ae835SMatthias Ringwald 
689474f5c3fSMatthias Ringwald     // process
690474f5c3fSMatthias Ringwald     l2cap_run();
691474f5c3fSMatthias Ringwald 
692474f5c3fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
693474f5c3fSMatthias Ringwald }
694474f5c3fSMatthias Ringwald 
695474f5c3fSMatthias Ringwald uint8_t l2cap_ertm_set_busy(uint16_t local_cid){
696f68b21d7SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
697474f5c3fSMatthias Ringwald     if (!channel) {
698474f5c3fSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
699474f5c3fSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
700474f5c3fSMatthias Ringwald     }
701474f5c3fSMatthias Ringwald     if (!channel->local_busy){
702474f5c3fSMatthias Ringwald         channel->local_busy = 1;
703474f5c3fSMatthias Ringwald         channel->send_supervisor_frame_receiver_not_ready = 1;
704474f5c3fSMatthias Ringwald         l2cap_run();
705474f5c3fSMatthias Ringwald     }
706474f5c3fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
707474f5c3fSMatthias Ringwald }
708474f5c3fSMatthias Ringwald 
709474f5c3fSMatthias Ringwald uint8_t l2cap_ertm_set_ready(uint16_t local_cid){
710f68b21d7SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
711474f5c3fSMatthias Ringwald     if (!channel) {
712474f5c3fSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
713474f5c3fSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
714474f5c3fSMatthias Ringwald     }
715474f5c3fSMatthias Ringwald     if (channel->local_busy){
716474f5c3fSMatthias Ringwald         channel->local_busy = 0;
717474f5c3fSMatthias Ringwald         channel->send_supervisor_frame_receiver_ready_poll = 1;
718474f5c3fSMatthias Ringwald         l2cap_run();
719474f5c3fSMatthias Ringwald     }
720474f5c3fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
721474f5c3fSMatthias Ringwald }
722474f5c3fSMatthias Ringwald 
7231e1a46bbSMatthias Ringwald // Process-ReqSeq
7241e1a46bbSMatthias Ringwald static void l2cap_ertm_process_req_seq(l2cap_channel_t * l2cap_channel, uint8_t req_seq){
725474f5c3fSMatthias Ringwald     int num_buffers_acked = 0;
726474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
72794301352SMatthias Ringwald     log_info("l2cap_ertm_process_req_seq: tx_read_index %u, tx_write_index %u, req_seq %u", l2cap_channel->tx_read_index, l2cap_channel->tx_write_index, req_seq);
728474f5c3fSMatthias Ringwald     while (1){
7291e1a46bbSMatthias Ringwald 
73094301352SMatthias Ringwald         // no unack packets left
73194301352SMatthias Ringwald         if (l2cap_channel->unacked_frames == 0) {
7321e1a46bbSMatthias Ringwald             // stop retransmission timer
7331e1a46bbSMatthias Ringwald             l2cap_ertm_stop_retransmission_timer(l2cap_channel);
7341e1a46bbSMatthias Ringwald             break;
7351e1a46bbSMatthias Ringwald         }
7361e1a46bbSMatthias Ringwald 
737474f5c3fSMatthias Ringwald         tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
738474f5c3fSMatthias Ringwald         // calc delta
739474f5c3fSMatthias Ringwald         int delta = (req_seq - tx_state->tx_seq) & 0x03f;
740474f5c3fSMatthias Ringwald         if (delta == 0) break;  // all packets acknowledged
741474f5c3fSMatthias Ringwald         if (delta > l2cap_channel->remote_tx_window_size) break;
742474f5c3fSMatthias Ringwald 
743474f5c3fSMatthias Ringwald         num_buffers_acked++;
744a8409e80SMatthias Ringwald         l2cap_channel->num_stored_tx_frames--;
74594301352SMatthias Ringwald         l2cap_channel->unacked_frames--;
746474f5c3fSMatthias Ringwald         log_info("RR seq %u => packet with tx_seq %u done", req_seq, tx_state->tx_seq);
747474f5c3fSMatthias Ringwald 
748474f5c3fSMatthias Ringwald         l2cap_channel->tx_read_index++;
749474f5c3fSMatthias Ringwald         if (l2cap_channel->tx_read_index >= l2cap_channel->num_rx_buffers){
750474f5c3fSMatthias Ringwald             l2cap_channel->tx_read_index = 0;
751474f5c3fSMatthias Ringwald         }
752474f5c3fSMatthias Ringwald     }
753474f5c3fSMatthias Ringwald     if (num_buffers_acked){
754a8409e80SMatthias Ringwald         log_info("num_buffers_acked %u", num_buffers_acked);
755474f5c3fSMatthias Ringwald     l2cap_ertm_notify_channel_can_send(l2cap_channel);
756474f5c3fSMatthias Ringwald }
757474f5c3fSMatthias Ringwald }
758474f5c3fSMatthias Ringwald 
759474f5c3fSMatthias Ringwald static l2cap_ertm_tx_packet_state_t * l2cap_ertm_get_tx_state(l2cap_channel_t * l2cap_channel, uint8_t tx_seq){
760474f5c3fSMatthias Ringwald     int i;
761474f5c3fSMatthias Ringwald     for (i=0;i<l2cap_channel->num_tx_buffers;i++){
762474f5c3fSMatthias Ringwald         l2cap_ertm_tx_packet_state_t * tx_state = &l2cap_channel->tx_packets_state[i];
763474f5c3fSMatthias Ringwald         if (tx_state->tx_seq == tx_seq) return tx_state;
764474f5c3fSMatthias Ringwald     }
765474f5c3fSMatthias Ringwald     return NULL;
766474f5c3fSMatthias Ringwald }
767474f5c3fSMatthias Ringwald 
768474f5c3fSMatthias Ringwald // @param delta number of frames in the future, >= 1
769122c2b05SMatthias Ringwald // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
7703d244bfaSMatthias Ringwald static void l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel_t * l2cap_channel, l2cap_segmentation_and_reassembly_t sar, int delta, const uint8_t * payload, uint16_t size){
771474f5c3fSMatthias Ringwald     log_info("Store SDU with delta %u", delta);
772474f5c3fSMatthias Ringwald     // get rx state for packet to store
773474f5c3fSMatthias Ringwald     int index = l2cap_channel->rx_store_index + delta - 1;
774474f5c3fSMatthias Ringwald     if (index > l2cap_channel->num_rx_buffers){
775474f5c3fSMatthias Ringwald         index -= l2cap_channel->num_rx_buffers;
776474f5c3fSMatthias Ringwald     }
777474f5c3fSMatthias Ringwald     log_info("Index of packet to store %u", index);
778474f5c3fSMatthias Ringwald     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
779474f5c3fSMatthias Ringwald     // check if buffer is free
780474f5c3fSMatthias Ringwald     if (rx_state->valid){
781474f5c3fSMatthias Ringwald         log_error("Packet buffer already used");
782474f5c3fSMatthias Ringwald         return;
783474f5c3fSMatthias Ringwald     }
784474f5c3fSMatthias Ringwald     rx_state->valid = 1;
785474f5c3fSMatthias Ringwald     rx_state->sar = sar;
786474f5c3fSMatthias Ringwald     rx_state->len = size;
787474f5c3fSMatthias Ringwald     uint8_t * rx_buffer = &l2cap_channel->rx_packets_data[index];
788*6535961aSMatthias Ringwald     (void)memcpy(rx_buffer, payload, size);
789474f5c3fSMatthias Ringwald }
790474f5c3fSMatthias Ringwald 
791122c2b05SMatthias Ringwald // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
7923d244bfaSMatthias Ringwald static void l2cap_ertm_handle_in_sequence_sdu(l2cap_channel_t * l2cap_channel, l2cap_segmentation_and_reassembly_t sar, const uint8_t * payload, uint16_t size){
793122c2b05SMatthias Ringwald     uint16_t reassembly_sdu_length;
794474f5c3fSMatthias Ringwald     switch (sar){
795474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
796122c2b05SMatthias Ringwald             // assert total packet size <= our mtu
797122c2b05SMatthias Ringwald             if (size > l2cap_channel->local_mtu) break;
798474f5c3fSMatthias Ringwald             // packet complete -> disapatch
7993d244bfaSMatthias Ringwald             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, (uint8_t*) payload, size);
800474f5c3fSMatthias Ringwald             break;
801474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
802122c2b05SMatthias Ringwald             // read SDU len
803122c2b05SMatthias Ringwald             reassembly_sdu_length = little_endian_read_16(payload, 0);
804474f5c3fSMatthias Ringwald             payload += 2;
805474f5c3fSMatthias Ringwald             size    -= 2;
806122c2b05SMatthias Ringwald             // assert reassembled size <= our mtu
807122c2b05SMatthias Ringwald             if (reassembly_sdu_length > l2cap_channel->local_mtu) break;
808122c2b05SMatthias Ringwald             // store start segment
809122c2b05SMatthias Ringwald             l2cap_channel->reassembly_sdu_length = reassembly_sdu_length;
810*6535961aSMatthias Ringwald             (void)memcpy(&l2cap_channel->reassembly_buffer[0], payload, size);
811474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos = size;
812474f5c3fSMatthias Ringwald             break;
813474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
814122c2b05SMatthias Ringwald             // assert size of reassembled data <= our mtu
815122c2b05SMatthias Ringwald             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
816122c2b05SMatthias Ringwald             // store continuation segment
817*6535961aSMatthias Ringwald             (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
818*6535961aSMatthias Ringwald                          payload, size);
819474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos += size;
820474f5c3fSMatthias Ringwald             break;
821474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
822122c2b05SMatthias Ringwald             // assert size of reassembled data <= our mtu
823122c2b05SMatthias Ringwald             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
824122c2b05SMatthias Ringwald             // store continuation segment
825*6535961aSMatthias Ringwald             (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
826*6535961aSMatthias Ringwald                          payload, size);
827474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos += size;
828122c2b05SMatthias Ringwald             // assert size of reassembled data matches announced sdu length
829122c2b05SMatthias Ringwald             if (l2cap_channel->reassembly_pos != l2cap_channel->reassembly_sdu_length) break;
830474f5c3fSMatthias Ringwald             // packet complete -> disapatch
831474f5c3fSMatthias Ringwald             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->reassembly_buffer, l2cap_channel->reassembly_pos);
832474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos = 0;
833474f5c3fSMatthias Ringwald             break;
834474f5c3fSMatthias Ringwald     }
835474f5c3fSMatthias Ringwald }
836474f5c3fSMatthias Ringwald 
837d89ab698SMatthias Ringwald static void l2cap_ertm_channel_send_information_frame(l2cap_channel_t * channel){
838d89ab698SMatthias Ringwald     channel->unacked_frames++;
839d89ab698SMatthias Ringwald     int index = channel->tx_send_index;
840d89ab698SMatthias Ringwald     channel->tx_send_index++;
841d89ab698SMatthias Ringwald     if (channel->tx_send_index >= channel->num_tx_buffers){
842d89ab698SMatthias Ringwald         channel->tx_send_index = 0;
843d89ab698SMatthias Ringwald     }
844d89ab698SMatthias Ringwald     l2cap_ertm_send_information_frame(channel, index, 0);   // final = 0
845d89ab698SMatthias Ringwald }
846d89ab698SMatthias Ringwald 
84785ddcd84SMatthias Ringwald #endif
84885ddcd84SMatthias Ringwald 
8496a5ffed8SMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
8506ddef68dSMilanka Ringwald static uint16_t l2cap_next_local_cid(void){
8516268fbfeSMilanka Ringwald     do {
8526268fbfeSMilanka Ringwald         if (local_source_cid == 0xffff) {
8536268fbfeSMilanka Ringwald             local_source_cid = 0x40;
8546268fbfeSMilanka Ringwald         } else {
8556268fbfeSMilanka Ringwald             local_source_cid++;
8566268fbfeSMilanka Ringwald         }
8576268fbfeSMilanka Ringwald     } while (l2cap_get_channel_for_local_cid(local_source_cid) != NULL);
8586268fbfeSMilanka Ringwald     return local_source_cid;
8596ddef68dSMilanka Ringwald }
8606a5ffed8SMatthias Ringwald #endif
8616ddef68dSMilanka Ringwald 
8626ddef68dSMilanka Ringwald static uint8_t l2cap_next_sig_id(void){
8636ddef68dSMilanka Ringwald     if (sig_seq_nr == 0xff) {
8646ddef68dSMilanka Ringwald         sig_seq_nr = 1;
8656ddef68dSMilanka Ringwald     } else {
8666ddef68dSMilanka Ringwald         sig_seq_nr++;
8676ddef68dSMilanka Ringwald     }
8686ddef68dSMilanka Ringwald     return sig_seq_nr;
8696ddef68dSMilanka Ringwald }
8706ddef68dSMilanka Ringwald 
87171de195eSMatthias Ringwald void l2cap_init(void){
8722b83fb7dSmatthias.ringwald     signaling_responses_pending = 0;
873808a48abSmatthias.ringwald 
874f5454fc6Smatthias.ringwald     l2cap_channels = NULL;
875fad84cafSMatthias Ringwald 
876fad84cafSMatthias Ringwald #ifdef ENABLE_CLASSIC
877f5454fc6Smatthias.ringwald     l2cap_services = NULL;
87809e9d05bSMatthias Ringwald     require_security_level2_for_outgoing_sdp = 0;
879fad84cafSMatthias Ringwald 
880fad84cafSMatthias Ringwald     // Setup Connectionless Channel
881fad84cafSMatthias Ringwald     l2cap_fixed_channel_connectionless.local_cid     = L2CAP_CID_CONNECTIONLESS_CHANNEL;
8827740e150SMatthias Ringwald     l2cap_fixed_channel_connectionless.channel_type  = L2CAP_CHANNEL_TYPE_CONNECTIONLESS;
883fad84cafSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_connectionless);
88409e9d05bSMatthias Ringwald #endif
885a3dc965aSMatthias Ringwald 
886a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
8877192e786SMatthias Ringwald     l2cap_le_services = NULL;
888a3dc965aSMatthias Ringwald #endif
889f5454fc6Smatthias.ringwald 
890d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
89133c40538SMatthias Ringwald     l2cap_event_packet_handler = NULL;
89225818320SMatthias Ringwald     l2cap_le_custom_max_mtu = 0;
893fad84cafSMatthias Ringwald 
894fad84cafSMatthias Ringwald     // Setup fixed ATT Channel
895fad84cafSMatthias Ringwald     l2cap_fixed_channel_att.local_cid    = L2CAP_CID_ATTRIBUTE_PROTOCOL;
8967740e150SMatthias Ringwald     l2cap_fixed_channel_att.channel_type = L2CAP_CHANNEL_TYPE_LE_FIXED;
897fad84cafSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_att);
898fad84cafSMatthias Ringwald 
899fad84cafSMatthias Ringwald     // Setup fixed SM Channel
900fad84cafSMatthias Ringwald     l2cap_fixed_channel_sm.local_cid     = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
9017740e150SMatthias Ringwald     l2cap_fixed_channel_sm.channel_type  = L2CAP_CHANNEL_TYPE_LE_FIXED;
902fad84cafSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_sm);
903d6ed9f9cSMatthias Ringwald #endif
904f5454fc6Smatthias.ringwald 
905fcadd0caSmatthias.ringwald     //
9062718e2e7Smatthias.ringwald     // register callback with HCI
907fcadd0caSmatthias.ringwald     //
908d9a7306aSMatthias Ringwald     hci_event_callback_registration.callback = &l2cap_hci_event_handler;
909fb37a842SMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
910fb37a842SMatthias Ringwald 
911d9a7306aSMatthias Ringwald     hci_register_acl_packet_handler(&l2cap_acl_handler);
912fb37a842SMatthias Ringwald 
913be005ed6SMatthias Ringwald #ifdef ENABLE_CLASSIC
91415a95bd5SMatthias Ringwald     gap_connectable_control(0); // no services yet
915be005ed6SMatthias Ringwald #endif
916fcadd0caSmatthias.ringwald }
917fcadd0caSmatthias.ringwald 
918ffbf8201SMatthias Ringwald void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
919d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
92033c40538SMatthias Ringwald     l2cap_event_packet_handler = handler;
921d6ed9f9cSMatthias Ringwald #else
9225774a392SMatthias Ringwald     UNUSED(handler);    // ok: no code
923d6ed9f9cSMatthias Ringwald #endif
9241e6aba47Smatthias.ringwald }
9251e6aba47Smatthias.ringwald 
92609e9d05bSMatthias Ringwald void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
927fad84cafSMatthias Ringwald     UNUSED(con_handle);  // ok: there is no con handle
9289ec2630cSMatthias Ringwald 
929f68b21d7SMatthias Ringwald     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
930fad84cafSMatthias Ringwald     if (!channel) return;
931fad84cafSMatthias Ringwald     channel->waiting_for_can_send_now = 1;
93209e9d05bSMatthias Ringwald     l2cap_notify_channel_can_send();
93309e9d05bSMatthias Ringwald }
93409e9d05bSMatthias Ringwald 
93509e9d05bSMatthias Ringwald int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
9365774a392SMatthias Ringwald     UNUSED(channel_id); // ok: only depends on Controller LE buffers
9379ec2630cSMatthias Ringwald 
93809e9d05bSMatthias Ringwald     return hci_can_send_acl_packet_now(con_handle);
93909e9d05bSMatthias Ringwald }
94009e9d05bSMatthias Ringwald 
94109e9d05bSMatthias Ringwald uint8_t *l2cap_get_outgoing_buffer(void){
94209e9d05bSMatthias Ringwald     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
94309e9d05bSMatthias Ringwald }
94409e9d05bSMatthias Ringwald 
9454e6fa3a2SMatthias Ringwald // only for L2CAP Basic Channels
94609e9d05bSMatthias Ringwald int l2cap_reserve_packet_buffer(void){
94709e9d05bSMatthias Ringwald     return hci_reserve_packet_buffer();
94809e9d05bSMatthias Ringwald }
94909e9d05bSMatthias Ringwald 
9504e6fa3a2SMatthias Ringwald // only for L2CAP Basic Channels
95109e9d05bSMatthias Ringwald void l2cap_release_packet_buffer(void){
95209e9d05bSMatthias Ringwald     hci_release_packet_buffer();
95309e9d05bSMatthias Ringwald }
95409e9d05bSMatthias Ringwald 
955f511cefaSMatthias Ringwald static void l2cap_setup_header(uint8_t * acl_buffer, hci_con_handle_t con_handle, uint8_t packet_boundary, uint16_t remote_cid, uint16_t len){
95609e9d05bSMatthias Ringwald     // 0 - Connection handle : PB=pb : BC=00
957f511cefaSMatthias Ringwald     little_endian_store_16(acl_buffer, 0, con_handle | (packet_boundary << 12) | (0 << 14));
95809e9d05bSMatthias Ringwald     // 2 - ACL length
95909e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 2,  len + 4);
96009e9d05bSMatthias Ringwald     // 4 - L2CAP packet length
96109e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 4,  len + 0);
96209e9d05bSMatthias Ringwald     // 6 - L2CAP channel DEST
96309e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 6,  remote_cid);
96409e9d05bSMatthias Ringwald }
96509e9d05bSMatthias Ringwald 
966f511cefaSMatthias Ringwald // assumption - only on LE connections
96709e9d05bSMatthias Ringwald int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
96809e9d05bSMatthias Ringwald 
96909e9d05bSMatthias Ringwald     if (!hci_is_packet_buffer_reserved()){
97009e9d05bSMatthias Ringwald         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
97109e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
97209e9d05bSMatthias Ringwald     }
97309e9d05bSMatthias Ringwald 
97409e9d05bSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
97509e9d05bSMatthias Ringwald         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
97609e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
97709e9d05bSMatthias Ringwald     }
97809e9d05bSMatthias Ringwald 
97909e9d05bSMatthias Ringwald     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
98009e9d05bSMatthias Ringwald 
98109e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
982f511cefaSMatthias Ringwald     l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
98309e9d05bSMatthias Ringwald     // send
98409e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len+8);
98509e9d05bSMatthias Ringwald }
98609e9d05bSMatthias Ringwald 
987f511cefaSMatthias Ringwald // assumption - only on LE connections
98809e9d05bSMatthias Ringwald int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
98909e9d05bSMatthias Ringwald 
99009e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(con_handle)){
99109e9d05bSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", cid);
99209e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
99309e9d05bSMatthias Ringwald     }
99409e9d05bSMatthias Ringwald 
99509e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
99609e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
99709e9d05bSMatthias Ringwald 
998*6535961aSMatthias Ringwald     (void)memcpy(&acl_buffer[8], data, len);
99909e9d05bSMatthias Ringwald 
100009e9d05bSMatthias Ringwald     return l2cap_send_prepared_connectionless(con_handle, cid, len);
100109e9d05bSMatthias Ringwald }
100209e9d05bSMatthias Ringwald 
100309e9d05bSMatthias Ringwald static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
1004d9d23054SMatthias Ringwald     log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
100509e9d05bSMatthias Ringwald     uint8_t event[4];
100609e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
100709e9d05bSMatthias Ringwald     event[1] = sizeof(event) - 2;
100809e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, channel);
100909e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
101009e9d05bSMatthias Ringwald     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
101109e9d05bSMatthias Ringwald }
101209e9d05bSMatthias Ringwald 
101309e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
101417a9b554SMatthias Ringwald static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
101558de5610Smatthias.ringwald     (* (channel->packet_handler))(type, channel->local_cid, data, size);
101658de5610Smatthias.ringwald }
101758de5610Smatthias.ringwald 
101844276248SMatthias Ringwald static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
101944276248SMatthias Ringwald     uint8_t event[4];
102044276248SMatthias Ringwald     event[0] = event_code;
102144276248SMatthias Ringwald     event[1] = sizeof(event) - 2;
102244276248SMatthias Ringwald     little_endian_store_16(event, 2, channel->local_cid);
102344276248SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
102444276248SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
102544276248SMatthias Ringwald }
102609e9d05bSMatthias Ringwald #endif
102744276248SMatthias Ringwald 
102809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
102958de5610Smatthias.ringwald void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
1030c9dc710bS[email protected]     log_info("L2CAP_EVENT_CHANNEL_OPENED status 0x%x addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x local_mtu %u, remote_mtu %u, flush_timeout %u",
1031fc64f94aSMatthias Ringwald              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
1032c9dc710bS[email protected]              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
10337f1690cfSMatthias Ringwald     uint8_t event[26];
103458de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
103558de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
103658de5610Smatthias.ringwald     event[2] = status;
1037724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
1038fc64f94aSMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
1039f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
1040f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
1041f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
1042f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 17, channel->local_mtu);
1043f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 19, channel->remote_mtu);
1044f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 21, channel->flush_timeout);
1045c1ab6cc1SMatthias Ringwald     event[23] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
10467f1690cfSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
10477f1690cfSMatthias Ringwald     log_info("ERTM mode %u, fcs enabled %u", channel->mode, channel->fcs_option);
10487f1690cfSMatthias Ringwald     event[24] = channel->mode;
10497f1690cfSMatthias Ringwald     event[25] = channel->fcs_option;
10507f1690cfSMatthias Ringwald 
10517f1690cfSMatthias Ringwald #else
10527f1690cfSMatthias Ringwald     event[24] = L2CAP_CHANNEL_MODE_BASIC;
10537f1690cfSMatthias Ringwald     event[25] = 0;
10547f1690cfSMatthias Ringwald #endif
105558de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
105617a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
105758de5610Smatthias.ringwald }
105858de5610Smatthias.ringwald 
105944276248SMatthias Ringwald static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
1060e0abb8e7S[email protected]     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
106144276248SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
106258de5610Smatthias.ringwald }
106358de5610Smatthias.ringwald 
106444276248SMatthias Ringwald static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
1065e0abb8e7S[email protected]     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
1066fc64f94aSMatthias Ringwald              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
106758de5610Smatthias.ringwald     uint8_t event[16];
106858de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
106958de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
1070724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[2]);
1071fc64f94aSMatthias Ringwald     little_endian_store_16(event,  8, channel->con_handle);
1072f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 10, channel->psm);
1073f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 12, channel->local_cid);
1074f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 14, channel->remote_cid);
107558de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
107617a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
10770af41d30Smatthias.ringwald }
1078f62db1e3Smatthias.ringwald 
107966a72640SMatthias Ringwald static void l2cap_handle_channel_open_failed(l2cap_channel_t * channel, uint8_t status){
108066a72640SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
108166a72640SMatthias Ringwald     // emit ertm buffer released, as it's not needed. if in basic mode, it was either not allocated or already released
108266a72640SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
108366a72640SMatthias Ringwald         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
108466a72640SMatthias Ringwald     }
108566a72640SMatthias Ringwald #endif
1086624873c3SMatthias Ringwald     l2cap_emit_channel_opened(channel, status);
1087624873c3SMatthias Ringwald }
1088624873c3SMatthias Ringwald 
108966a72640SMatthias Ringwald static void l2cap_handle_channel_closed(l2cap_channel_t * channel){
109066a72640SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
109166a72640SMatthias Ringwald     // emit ertm buffer released, as it's not needed anymore. if in basic mode, it was either not allocated or already released
109266a72640SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
109366a72640SMatthias Ringwald         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
109466a72640SMatthias Ringwald     }
109566a72640SMatthias Ringwald #endif
109666a72640SMatthias Ringwald     l2cap_emit_channel_closed(channel);
109766a72640SMatthias Ringwald }
1098dd3bf36fSMatthias Ringwald #endif
1099dd3bf36fSMatthias Ringwald 
1100dd3bf36fSMatthias Ringwald static l2cap_fixed_channel_t * l2cap_channel_item_by_cid(uint16_t cid){
1101dd3bf36fSMatthias Ringwald     btstack_linked_list_iterator_t it;
1102dd3bf36fSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1103dd3bf36fSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1104dd3bf36fSMatthias Ringwald         l2cap_fixed_channel_t * channel = (l2cap_fixed_channel_t*) btstack_linked_list_iterator_next(&it);
1105dd3bf36fSMatthias Ringwald         if (channel->local_cid == cid) {
1106dd3bf36fSMatthias Ringwald             return channel;
1107dd3bf36fSMatthias Ringwald         }
1108dd3bf36fSMatthias Ringwald     }
1109dd3bf36fSMatthias Ringwald     return NULL;
1110dd3bf36fSMatthias Ringwald }
111166a72640SMatthias Ringwald 
1112fad84cafSMatthias Ringwald // used for fixed channels in LE (ATT/SM) and Classic (Connectionless Channel). CID < 0x04
1113fad84cafSMatthias Ringwald static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid){
1114fad84cafSMatthias Ringwald     if (local_cid >= 0x40) return NULL;
1115fad84cafSMatthias Ringwald     return (l2cap_fixed_channel_t*) l2cap_channel_item_by_cid(local_cid);
1116fad84cafSMatthias Ringwald }
111724eb964eSMatthias Ringwald 
111824eb964eSMatthias Ringwald // used for Classic Channels + LE Data Channels. local_cid >= 0x40
111924eb964eSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
112024eb964eSMatthias Ringwald static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
112124eb964eSMatthias Ringwald     if (local_cid < 0x40) return NULL;
112224eb964eSMatthias Ringwald     return (l2cap_channel_t*) l2cap_channel_item_by_cid(local_cid);
112324eb964eSMatthias Ringwald }
11240b9d7e78SMatthias Ringwald 
112530725612SMatthias Ringwald void l2cap_request_can_send_now_event(uint16_t local_cid){
112630725612SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
112730725612SMatthias Ringwald     if (!channel) return;
112830725612SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
112996646001SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
113096646001SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
113196646001SMatthias Ringwald         l2cap_ertm_notify_channel_can_send(channel);
113296646001SMatthias Ringwald         return;
113396646001SMatthias Ringwald     }
113496646001SMatthias Ringwald #endif
113530725612SMatthias Ringwald     l2cap_notify_channel_can_send();
113630725612SMatthias Ringwald }
113730725612SMatthias Ringwald 
113896646001SMatthias Ringwald int  l2cap_can_send_packet_now(uint16_t local_cid){
113996646001SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
114096646001SMatthias Ringwald     if (!channel) return 0;
114196646001SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
114296646001SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
114396646001SMatthias Ringwald         return l2cap_ertm_can_store_packet_now(channel);
114496646001SMatthias Ringwald     }
114596646001SMatthias Ringwald #endif
11460b9d7e78SMatthias Ringwald     return hci_can_send_acl_packet_now(channel->con_handle);
11477856fb31S[email protected] }
11487856fb31S[email protected] 
114983e7cdd9SMatthias Ringwald int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
115083e7cdd9SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
115183e7cdd9SMatthias Ringwald     if (!channel) return 0;
11520b20b13bSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
11530b20b13bSMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
11540b20b13bSMatthias Ringwald         return 0;
11550b20b13bSMatthias Ringwald     }
11560b20b13bSMatthias Ringwald #endif
11570b9d7e78SMatthias Ringwald     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
115883e7cdd9SMatthias Ringwald }
11590b20b13bSMatthias Ringwald 
116096cbd662Smatthias.ringwald uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
116196cbd662Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
116296cbd662Smatthias.ringwald     if (channel) {
116396cbd662Smatthias.ringwald         return channel->remote_mtu;
116496cbd662Smatthias.ringwald     }
116596cbd662Smatthias.ringwald     return 0;
116696cbd662Smatthias.ringwald }
116724eb964eSMatthias Ringwald #endif
116896cbd662Smatthias.ringwald 
116924eb964eSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
1170fad84cafSMatthias Ringwald static int l2cap_is_dynamic_channel_type(l2cap_channel_type_t channel_type){
1171fad84cafSMatthias Ringwald     switch (channel_type){
1172fad84cafSMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CLASSIC:
1173fad84cafSMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
1174fad84cafSMatthias Ringwald             return 1;
1175fad84cafSMatthias Ringwald         default:
1176fad84cafSMatthias Ringwald             return 0;
1177fad84cafSMatthias Ringwald     }
1178fad84cafSMatthias Ringwald }
117924eb964eSMatthias Ringwald #endif
1180fad84cafSMatthias Ringwald 
118124eb964eSMatthias Ringwald #ifdef ENABLE_CLASSIC
1182fad84cafSMatthias Ringwald // RTX Timer only exist for dynamic channels
1183ec820d77SMatthias Ringwald static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
1184665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1185665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1186665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1187665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1188fad84cafSMatthias Ringwald         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
11895932bd7cS[email protected]         if (&channel->rtx == ts) {
11905932bd7cS[email protected]             return channel;
11915932bd7cS[email protected]         }
11925932bd7cS[email protected]     }
11935932bd7cS[email protected]     return NULL;
11945932bd7cS[email protected] }
11955932bd7cS[email protected] 
1196ec820d77SMatthias Ringwald static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
11975932bd7cS[email protected]     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
119895d2c8f4SMatthias Ringwald     if (!channel) return;
11995932bd7cS[email protected] 
12005932bd7cS[email protected]     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
12015932bd7cS[email protected] 
12025932bd7cS[email protected]     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
12035932bd7cS[email protected]     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
12045932bd7cS[email protected]     // notify client
120566a72640SMatthias Ringwald     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
12065932bd7cS[email protected] 
12075932bd7cS[email protected]     // discard channel
1208665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1209c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
12105932bd7cS[email protected] }
12115932bd7cS[email protected] 
121213aa3e4bSMatthias Ringwald #endif
121313aa3e4bSMatthias Ringwald 
121413aa3e4bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
12155932bd7cS[email protected] static void l2cap_stop_rtx(l2cap_channel_t * channel){
12165932bd7cS[email protected]     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
1217528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->rtx);
12185932bd7cS[email protected] }
121913aa3e4bSMatthias Ringwald #endif
122013aa3e4bSMatthias Ringwald 
122113aa3e4bSMatthias Ringwald #ifdef ENABLE_CLASSIC
12225932bd7cS[email protected] 
12235932bd7cS[email protected] static void l2cap_start_rtx(l2cap_channel_t * channel){
12245932bd7cS[email protected]     l2cap_stop_rtx(channel);
1225cb0ff06bS[email protected]     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
1226528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1227528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
1228528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
12295932bd7cS[email protected] }
12305932bd7cS[email protected] 
12315932bd7cS[email protected] static void l2cap_start_ertx(l2cap_channel_t * channel){
12325932bd7cS[email protected]     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
12335932bd7cS[email protected]     l2cap_stop_rtx(channel);
1234528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1235528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
1236528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
12375932bd7cS[email protected] }
12385932bd7cS[email protected] 
123971de195eSMatthias Ringwald void l2cap_require_security_level_2_for_outgoing_sdp(void){
1240ac301f95S[email protected]     require_security_level2_for_outgoing_sdp = 1;
1241ac301f95S[email protected] }
1242ac301f95S[email protected] 
1243df3354fcS[email protected] static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
124484e3541eSMilanka Ringwald     return (psm == BLUETOOTH_PSM_SDP) && (!require_security_level2_for_outgoing_sdp);
1245df3354fcS[email protected] }
12465932bd7cS[email protected] 
124763854e74SMatthias Ringwald static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1248a35252c8S[email protected]     if (!hci_can_send_acl_packet_now(handle)){
12499da54300S[email protected]         log_info("l2cap_send_signaling_packet, cannot send");
1250b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
1251b1d43497Smatthias.ringwald     }
1252b1d43497Smatthias.ringwald 
12539da54300S[email protected]     // log_info("l2cap_send_signaling_packet type %u", cmd);
12542a373862S[email protected]     hci_reserve_packet_buffer();
1255facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
125658de5610Smatthias.ringwald     va_list argptr;
125758de5610Smatthias.ringwald     va_start(argptr, identifier);
125870efece1S[email protected]     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
125958de5610Smatthias.ringwald     va_end(argptr);
12609da54300S[email protected]     // log_info("l2cap_send_signaling_packet con %u!", handle);
1261826f7347S[email protected]     return hci_send_acl_packet_buffer(len);
126258de5610Smatthias.ringwald }
126358de5610Smatthias.ringwald 
1264f511cefaSMatthias Ringwald // assumption - only on Classic connections
12654e6fa3a2SMatthias Ringwald // cannot be used for L2CAP ERTM
1266b1d43497Smatthias.ringwald int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
1267b1d43497Smatthias.ringwald 
1268c8b9416aS[email protected]     if (!hci_is_packet_buffer_reserved()){
1269c8b9416aS[email protected]         log_error("l2cap_send_prepared called without reserving packet first");
1270c8b9416aS[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
1271c8b9416aS[email protected]     }
1272c8b9416aS[email protected] 
127358de5610Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1274b1d43497Smatthias.ringwald     if (!channel) {
12759da54300S[email protected]         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
1276b1d43497Smatthias.ringwald         return -1;   // TODO: define error
12776218e6f1Smatthias.ringwald     }
12786218e6f1Smatthias.ringwald 
1279fc64f94aSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
12809da54300S[email protected]         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
1281a35252c8S[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
1282a35252c8S[email protected]     }
1283a35252c8S[email protected] 
1284fc64f94aSMatthias Ringwald     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
1285b1d43497Smatthias.ringwald 
128685ddcd84SMatthias Ringwald     int fcs_size = 0;
128785ddcd84SMatthias Ringwald 
128885ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
12896574158aSMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->fcs_option){
129085ddcd84SMatthias Ringwald         fcs_size = 2;
129185ddcd84SMatthias Ringwald     }
129285ddcd84SMatthias Ringwald #endif
129385ddcd84SMatthias Ringwald 
1294f511cefaSMatthias Ringwald     // set non-flushable packet boundary flag if supported on Controller
1295facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1296f511cefaSMatthias Ringwald     uint8_t packet_boundary_flag = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
129785ddcd84SMatthias Ringwald     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
129885ddcd84SMatthias Ringwald 
129985ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1300b72f6906SMatthias Ringwald     if (fcs_size){
130185ddcd84SMatthias Ringwald         // calculate FCS over l2cap data
130285ddcd84SMatthias Ringwald         uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
130385ddcd84SMatthias Ringwald         log_info("I-Frame: fcs 0x%04x", fcs);
130485ddcd84SMatthias Ringwald         little_endian_store_16(acl_buffer, 8 + len, fcs);
130558de5610Smatthias.ringwald     }
130685ddcd84SMatthias Ringwald #endif
130785ddcd84SMatthias Ringwald 
130885ddcd84SMatthias Ringwald     // send
130985ddcd84SMatthias Ringwald     return hci_send_acl_packet_buffer(len+8+fcs_size);
131085ddcd84SMatthias Ringwald }
131185ddcd84SMatthias Ringwald 
1312f511cefaSMatthias Ringwald // assumption - only on Classic connections
1313ce8f182eSMatthias Ringwald int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
1314a35252c8S[email protected]     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1315a35252c8S[email protected]     if (!channel) {
1316ce8f182eSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
1317a35252c8S[email protected]         return -1;   // TODO: define error
1318a35252c8S[email protected]     }
1319a35252c8S[email protected] 
1320f0fb4cd7SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1321f0fb4cd7SMatthias Ringwald     // send in ERTM
1322f0fb4cd7SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1323f0fb4cd7SMatthias Ringwald         return l2cap_ertm_send(channel, data, len);
1324f0fb4cd7SMatthias Ringwald     }
1325f0fb4cd7SMatthias Ringwald #endif
1326f0fb4cd7SMatthias Ringwald 
1327f0efaa57S[email protected]     if (len > channel->remote_mtu){
1328ce8f182eSMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
1329f0efaa57S[email protected]         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
1330f0efaa57S[email protected]     }
1331f0efaa57S[email protected] 
1332fc64f94aSMatthias Ringwald     if (!hci_can_send_acl_packet_now(channel->con_handle)){
1333ce8f182eSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
1334b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
1335b1d43497Smatthias.ringwald     }
1336b1d43497Smatthias.ringwald 
13372a373862S[email protected]     hci_reserve_packet_buffer();
1338facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1339*6535961aSMatthias Ringwald     (void)memcpy(&acl_buffer[8], data, len);
1340f0fb4cd7SMatthias Ringwald     return l2cap_send_prepared(local_cid, len);
1341b1d43497Smatthias.ringwald }
1342b1d43497Smatthias.ringwald 
1343fc64f94aSMatthias Ringwald int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
1344fc64f94aSMatthias Ringwald     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
13450e37e417S[email protected] }
13460e37e417S[email protected] 
134728ca2b46S[email protected] static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
134828ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
134928ca2b46S[email protected] }
135028ca2b46S[email protected] 
135128ca2b46S[email protected] static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
135228ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
135328ca2b46S[email protected] }
135409e9d05bSMatthias Ringwald #endif
135528ca2b46S[email protected] 
135628ca2b46S[email protected] 
135709e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
135863854e74SMatthias Ringwald static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
135909e9d05bSMatthias Ringwald 
136009e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(handle)){
136109e9d05bSMatthias Ringwald         log_info("l2cap_send_le_signaling_packet, cannot send");
136209e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
136309e9d05bSMatthias Ringwald     }
136409e9d05bSMatthias Ringwald 
136509e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
136609e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
136709e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
136809e9d05bSMatthias Ringwald     va_list argptr;
136909e9d05bSMatthias Ringwald     va_start(argptr, identifier);
137009e9d05bSMatthias Ringwald     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
137109e9d05bSMatthias Ringwald     va_end(argptr);
137209e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
137309e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len);
137409e9d05bSMatthias Ringwald }
137509e9d05bSMatthias Ringwald #endif
137609e9d05bSMatthias Ringwald 
137709e9d05bSMatthias Ringwald uint16_t l2cap_max_mtu(void){
137809e9d05bSMatthias Ringwald     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
137909e9d05bSMatthias Ringwald }
138009e9d05bSMatthias Ringwald 
13813e329ddfSandryblack #ifdef ENABLE_BLE
138209e9d05bSMatthias Ringwald uint16_t l2cap_max_le_mtu(void){
138325818320SMatthias Ringwald     if (l2cap_le_custom_max_mtu != 0) return l2cap_le_custom_max_mtu;
138409e9d05bSMatthias Ringwald     return l2cap_max_mtu();
138509e9d05bSMatthias Ringwald }
1386b1d43497Smatthias.ringwald 
138725818320SMatthias Ringwald void l2cap_set_max_le_mtu(uint16_t max_mtu){
138825818320SMatthias Ringwald     if (max_mtu < l2cap_max_mtu()){
138925818320SMatthias Ringwald         l2cap_le_custom_max_mtu = max_mtu;
139025818320SMatthias Ringwald     }
139125818320SMatthias Ringwald }
13923e329ddfSandryblack #endif
139325818320SMatthias Ringwald 
1394d2afdd38SMatthias Ringwald #ifdef ENABLE_CLASSIC
1395d2afdd38SMatthias Ringwald 
13966b99230fSMatthias Ringwald static uint16_t l2cap_setup_options_mtu(uint8_t * config_options, uint16_t mtu){
1397d64e9771SMatthias Ringwald     config_options[0] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
1398d2afdd38SMatthias Ringwald     config_options[1] = 2; // len param
13996b99230fSMatthias Ringwald     little_endian_store_16(config_options, 2, mtu);
1400d2afdd38SMatthias Ringwald     return 4;
1401d2afdd38SMatthias Ringwald }
1402d2afdd38SMatthias Ringwald 
1403450ad7ecSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
14046b99230fSMatthias Ringwald static int l2cap_ertm_mode(l2cap_channel_t * channel){
1405450ad7ecSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
14066b99230fSMatthias Ringwald     return ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE)
14076b99230fSMatthias Ringwald         &&  (connection->l2cap_state.extended_feature_mask & 0x08));
1408450ad7ecSMatthias Ringwald }
1409450ad7ecSMatthias Ringwald #endif
14106b99230fSMatthias Ringwald 
14116b99230fSMatthias Ringwald static uint16_t l2cap_setup_options_request(l2cap_channel_t * channel, uint8_t * config_options){
14126b99230fSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1413313d3a26SMatthias Ringwald     // use ERTM options if supported by remote and channel ready to use it
1414313d3a26SMatthias Ringwald     if (l2cap_ertm_mode(channel) && channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
14157cbe539fSMatthias Ringwald         return l2cap_setup_options_ertm_request(channel, config_options);
14166b99230fSMatthias Ringwald     }
14176b99230fSMatthias Ringwald #endif
14186b99230fSMatthias Ringwald     uint16_t mtu = channel->local_mtu;
14196b99230fSMatthias Ringwald     return l2cap_setup_options_mtu(config_options, mtu);
14206b99230fSMatthias Ringwald }
14216b99230fSMatthias Ringwald 
1422b8134563SMatthias Ringwald static uint16_t l2cap_setup_options_mtu_response(l2cap_channel_t * channel, uint8_t * config_options){
142332717978SMatthias Ringwald     uint16_t mtu = btstack_min(channel->local_mtu, channel->remote_mtu);
14246b99230fSMatthias Ringwald     return l2cap_setup_options_mtu(config_options, mtu);
14256dca2a0cSMatthias Ringwald }
14266dca2a0cSMatthias Ringwald 
14271b9cb13dSMatthias Ringwald static uint32_t l2cap_extended_features_mask(void){
14281b9cb13dSMatthias Ringwald     // extended features request supported, features: fixed channels, unicast connectionless data reception
14291b9cb13dSMatthias Ringwald     uint32_t features = 0x280;
14301b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
143154901195SMatthias Ringwald     features |= 0x0028;
14321b9cb13dSMatthias Ringwald #endif
14331b9cb13dSMatthias Ringwald     return features;
14341b9cb13dSMatthias Ringwald }
1435d2afdd38SMatthias Ringwald #endif
14361b9cb13dSMatthias Ringwald 
14378158c421Smatthias.ringwald // MARK: L2CAP_RUN
14382cd0be45Smatthias.ringwald // process outstanding signaling tasks
14397f02f414SMatthias Ringwald static void l2cap_run(void){
14402b83fb7dSmatthias.ringwald 
144122c29ab4SMatthias Ringwald     // log_info("l2cap_run: entered");
144222c29ab4SMatthias Ringwald 
14432b83fb7dSmatthias.ringwald     // check pending signaling responses
14442b83fb7dSmatthias.ringwald     while (signaling_responses_pending){
14452b83fb7dSmatthias.ringwald 
14462b83fb7dSmatthias.ringwald         hci_con_handle_t handle = signaling_responses[0].handle;
1447a35252c8S[email protected] 
1448a35252c8S[email protected]         if (!hci_can_send_acl_packet_now(handle)) break;
1449a35252c8S[email protected] 
14502b83fb7dSmatthias.ringwald         uint8_t  sig_id        = signaling_responses[0].sig_id;
1451e74c5f58SMatthias Ringwald         uint8_t  response_code = signaling_responses[0].code;
145263a7246aSmatthias.ringwald         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
1453b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
14545774a392SMatthias Ringwald         uint16_t info_type     = signaling_responses[0].data;  // INFORMATION_REQUEST
1455b3264428SMatthias Ringwald         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
1456b3264428SMatthias Ringwald #endif
145709e9d05bSMatthias Ringwald 
1458f53da564S[email protected]         // remove first item before sending (to avoid sending response mutliple times)
1459f53da564S[email protected]         signaling_responses_pending--;
1460f53da564S[email protected]         int i;
1461f53da564S[email protected]         for (i=0; i < signaling_responses_pending; i++){
1462*6535961aSMatthias Ringwald             (void)memcpy(&signaling_responses[i],
1463*6535961aSMatthias Ringwald                          &signaling_responses[i + 1],
1464*6535961aSMatthias Ringwald                          sizeof(l2cap_signaling_response_t));
1465f53da564S[email protected]         }
1466f53da564S[email protected] 
1467f53da564S[email protected]         switch (response_code){
146809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
14692b360848Smatthias.ringwald             case CONNECTION_REQUEST:
1470e74c5f58SMatthias Ringwald                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
14712bd8b7e7S[email protected]                 // also disconnect if result is 0x0003 - security blocked
14724d816277S[email protected]                 if (result == 0x0003){
14732bd8b7e7S[email protected]                     hci_disconnect_security_block(handle);
14744d816277S[email protected]                 }
14752b360848Smatthias.ringwald                 break;
14762b83fb7dSmatthias.ringwald             case ECHO_REQUEST:
14772b83fb7dSmatthias.ringwald                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
14782b83fb7dSmatthias.ringwald                 break;
14792b83fb7dSmatthias.ringwald             case INFORMATION_REQUEST:
14803e64cb44SMatthias Ringwald                 switch (info_type){
14813e64cb44SMatthias Ringwald                     case L2CAP_INFO_TYPE_CONNECTIONLESS_MTU: {
14823b0484b3S[email protected]                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
14833e64cb44SMatthias Ringwald                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(connectionless_mtu), &connectionless_mtu);
14843b0484b3S[email protected]                         }
1485202c8a4cSMatthias Ringwald                         break;
14863e64cb44SMatthias Ringwald                     case L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED: {
14871b9cb13dSMatthias Ringwald                             uint32_t features = l2cap_extended_features_mask();
14883e64cb44SMatthias Ringwald                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(features), &features);
14893b0484b3S[email protected]                         }
1490202c8a4cSMatthias Ringwald                         break;
14913e64cb44SMatthias Ringwald                     case L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED: {
14923b0484b3S[email protected]                             uint8_t map[8];
14933b0484b3S[email protected]                             memset(map, 0, 8);
1494288636a2SMatthias Ringwald                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
14953e64cb44SMatthias Ringwald                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(map), &map);
14963b0484b3S[email protected]                         }
1497202c8a4cSMatthias Ringwald                         break;
14983b0484b3S[email protected]                     default:
14992b83fb7dSmatthias.ringwald                         // all other types are not supported
15003e64cb44SMatthias Ringwald                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 1, 0, NULL);
15013b0484b3S[email protected]                         break;
15022b83fb7dSmatthias.ringwald                 }
15032b83fb7dSmatthias.ringwald                 break;
150463a7246aSmatthias.ringwald             case COMMAND_REJECT:
15055ca8d57bS[email protected]                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
150663f0ac45SMatthias Ringwald                 break;
150709e9d05bSMatthias Ringwald #endif
1508a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
150963f0ac45SMatthias Ringwald             case LE_CREDIT_BASED_CONNECTION_REQUEST:
151063f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
151163f0ac45SMatthias Ringwald                 break;
151270efece1S[email protected]             case COMMAND_REJECT_LE:
151370efece1S[email protected]                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
151463a7246aSmatthias.ringwald                 break;
151570efece1S[email protected] #endif
15162b83fb7dSmatthias.ringwald             default:
15172b83fb7dSmatthias.ringwald                 // should not happen
15182b83fb7dSmatthias.ringwald                 break;
15192b83fb7dSmatthias.ringwald         }
15202b83fb7dSmatthias.ringwald     }
15212b83fb7dSmatthias.ringwald 
1522959f646aSMatthias Ringwald #if defined(ENABLE_CLASSIC) || defined(ENABLE_BLE)
1523665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
15245774a392SMatthias Ringwald #endif
152509e9d05bSMatthias Ringwald 
15261b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
15271b9cb13dSMatthias Ringwald     // send l2cap information request if neccessary
15281b9cb13dSMatthias Ringwald     hci_connections_get_iterator(&it);
15291b9cb13dSMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
15301b9cb13dSMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
15311b9cb13dSMatthias Ringwald         if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST){
153293d791b2SMatthias Ringwald             if (!hci_can_send_acl_packet_now(connection->con_handle)) break;
15331b9cb13dSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
15341b9cb13dSMatthias Ringwald             uint8_t sig_id = l2cap_next_sig_id();
15353e64cb44SMatthias Ringwald             uint8_t info_type = L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED;
15361b9cb13dSMatthias Ringwald             l2cap_send_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
15371b9cb13dSMatthias Ringwald             return;
15381b9cb13dSMatthias Ringwald         }
15391b9cb13dSMatthias Ringwald     }
15401b9cb13dSMatthias Ringwald #endif
15411b9cb13dSMatthias Ringwald 
154209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1543f2c70799Sandryblack #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1544f2c70799Sandryblack     uint8_t  config_options[18];
1545f2c70799Sandryblack #else
154643ec931dSMatthias Ringwald     uint8_t  config_options[10];
1547f2c70799Sandryblack #endif
1548665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1549665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1550baf94f06S[email protected] 
1551665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1552421cb104SMatthias Ringwald 
1553421cb104SMatthias Ringwald         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CLASSIC) continue;
1554421cb104SMatthias Ringwald 
155522c29ab4SMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
15562cd0be45Smatthias.ringwald         switch (channel->state){
15572cd0be45Smatthias.ringwald 
1558df3354fcS[email protected]             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1559ad671560S[email protected]             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
1560fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1561a00031e2S[email protected]                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
1562ad671560S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
1563fc64f94aSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
1564ad671560S[email protected]                 }
1565ad671560S[email protected]                 break;
1566ad671560S[email protected] 
156702b22dc4Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1568baf94f06S[email protected]                 if (!hci_can_send_command_packet_now()) break;
156964472d52Smatthias.ringwald                 // send connection request - set state first
157064472d52Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
157102b22dc4Smatthias.ringwald                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
1572*6535961aSMatthias Ringwald                 (void)memcpy(l2cap_outgoing_classic_addr, channel->address, 6);
15738f8108aaSmatthias.ringwald                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
157402b22dc4Smatthias.ringwald                 break;
157502b22dc4Smatthias.ringwald 
1576e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
1577fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
157822c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1579fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
1580e7ff783cSmatthias.ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1581665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1582c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
1583e7ff783cSmatthias.ringwald                 break;
1584e7ff783cSmatthias.ringwald 
1585552d92a1Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
1586fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1587fa8473a4Smatthias.ringwald                 channel->state = L2CAP_STATE_CONFIG;
158828ca2b46S[email protected]                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1589fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
1590552d92a1Smatthias.ringwald                 break;
1591552d92a1Smatthias.ringwald 
15926fdcc387Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
1593fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
15946fdcc387Smatthias.ringwald                 // success, start l2cap handshake
1595b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
15966fdcc387Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
1597fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
15985932bd7cS[email protected]                 l2cap_start_rtx(channel);
15996fdcc387Smatthias.ringwald                 break;
16006fdcc387Smatthias.ringwald 
1601fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
1602fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
160361c3f6deSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
160461c3f6deSMatthias Ringwald                     // fallback to basic mode if ERTM requested but not not supported by remote
160561c3f6deSMatthias Ringwald                      if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
160661c3f6deSMatthias Ringwald                         if (!l2cap_ertm_mode(channel)){
160761c3f6deSMatthias Ringwald                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
160861c3f6deSMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
160961c3f6deSMatthias Ringwald                         }
161061c3f6deSMatthias Ringwald                     }
161161c3f6deSMatthias Ringwald #endif
161273cf2b3dSmatthias.ringwald                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
161363a7246aSmatthias.ringwald                     uint16_t flags = 0;
161428ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
161563a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
161663a7246aSmatthias.ringwald                         flags = 1;
161763a7246aSmatthias.ringwald                     } else {
161828ca2b46S[email protected]                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
161963a7246aSmatthias.ringwald                     }
162063a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
1621ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1622fc64f94aSMatthias 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);
1623ac8f1300SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1624ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
1625ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1626ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1627b8134563SMatthias Ringwald                         uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1628ac8f1300SMatthias 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);
1629b8134563SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM){
1630b8134563SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
1631b8134563SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1632b8134563SMatthias Ringwald                         uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1633b8134563SMatthias 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);
1634ac8f1300SMatthias Ringwald #endif
1635ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
163663a7246aSmatthias.ringwald                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1637b8134563SMatthias Ringwald                         uint16_t options_size = l2cap_setup_options_mtu_response(channel, config_options);
1638ac8f1300SMatthias 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);
163963a7246aSmatthias.ringwald                     } else {
1640ac8f1300SMatthias Ringwald                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
164163a7246aSmatthias.ringwald                     }
164263a7246aSmatthias.ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1643fa8473a4Smatthias.ringwald                 }
164473cf2b3dSmatthias.ringwald                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
164528ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
164628ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
1647b1988dceSmatthias.ringwald                     channel->local_sig_id = l2cap_next_sig_id();
16486b99230fSMatthias Ringwald                     uint16_t options_size = l2cap_setup_options_request(channel, config_options);
16496dca2a0cSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options);
16505932bd7cS[email protected]                     l2cap_start_rtx(channel);
1651fa8473a4Smatthias.ringwald                 }
1652fa8473a4Smatthias.ringwald                 if (l2cap_channel_ready_for_open(channel)){
1653552d92a1Smatthias.ringwald                     channel->state = L2CAP_STATE_OPEN;
1654552d92a1Smatthias.ringwald                     l2cap_emit_channel_opened(channel, 0);  // success
1655fa8473a4Smatthias.ringwald                 }
1656552d92a1Smatthias.ringwald                 break;
1657552d92a1Smatthias.ringwald 
1658e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1659fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
166022c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1661fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
16625932bd7cS[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 :)
1663756102d3Smatthias.ringwald                 l2cap_finialize_channel_close(channel);  // -- remove from list
166464cb054cSMatthias Ringwald                 channel = NULL;
1665e7ff783cSmatthias.ringwald                 break;
1666e7ff783cSmatthias.ringwald 
1667e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1668fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1669b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
16702cd0be45Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1671fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
16722cd0be45Smatthias.ringwald                 break;
16732cd0be45Smatthias.ringwald             default:
16742cd0be45Smatthias.ringwald                 break;
16752cd0be45Smatthias.ringwald         }
167638f62777SMatthias Ringwald 
167738f62777SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
167864cb054cSMatthias Ringwald 
16799700d53bSMilanka Ringwald         // handle channel finalize on L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE
168064cb054cSMatthias Ringwald         if (!channel) continue;
16819700d53bSMilanka Ringwald 
16829700d53bSMilanka Ringwald         // ERTM mode
16839700d53bSMilanka Ringwald         if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
16849700d53bSMilanka Ringwald 
16859700d53bSMilanka Ringwald             // check if we can still send
1686e0780573SMatthias Ringwald             if (channel->con_handle == HCI_CON_HANDLE_INVALID) continue;
168738f62777SMatthias Ringwald             if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
1688675e6881SMatthias Ringwald 
1689d84e866fSMatthias Ringwald             if (channel->send_supervisor_frame_receiver_ready){
169078cd8a22SMatthias Ringwald                 channel->send_supervisor_frame_receiver_ready = 0;
1691d2afdd38SMatthias Ringwald                 log_info("Send S-Frame: RR %u, final %u", channel->req_seq, channel->set_final_bit_after_packet_with_poll_bit_set);
1692d2afdd38SMatthias 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);
1693d2afdd38SMatthias Ringwald                 channel->set_final_bit_after_packet_with_poll_bit_set = 0;
169438f62777SMatthias Ringwald                 l2cap_ertm_send_supervisor_frame(channel, control);
1695675e6881SMatthias Ringwald                 continue;
169638f62777SMatthias Ringwald             }
169762041d70SMatthias Ringwald             if (channel->send_supervisor_frame_receiver_ready_poll){
169878cd8a22SMatthias Ringwald                 channel->send_supervisor_frame_receiver_ready_poll = 0;
169962041d70SMatthias Ringwald                 log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
170062041d70SMatthias Ringwald                 uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
170162041d70SMatthias Ringwald                 l2cap_ertm_send_supervisor_frame(channel, control);
170262041d70SMatthias Ringwald                 continue;
170362041d70SMatthias Ringwald             }
17048f1c9639SMatthias Ringwald             if (channel->send_supervisor_frame_receiver_not_ready){
170578cd8a22SMatthias Ringwald                 channel->send_supervisor_frame_receiver_not_ready = 0;
17068f1c9639SMatthias Ringwald                 log_info("Send S-Frame: RNR %u", channel->req_seq);
17078f1c9639SMatthias Ringwald                 uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
17088f1c9639SMatthias Ringwald                 l2cap_ertm_send_supervisor_frame(channel, control);
17098f1c9639SMatthias Ringwald                 continue;
17108f1c9639SMatthias Ringwald             }
1711c7309e8dSMatthias Ringwald             if (channel->send_supervisor_frame_reject){
1712c7309e8dSMatthias Ringwald                 channel->send_supervisor_frame_reject = 0;
1713c7309e8dSMatthias Ringwald                 log_info("Send S-Frame: REJ %u", channel->req_seq);
1714c7309e8dSMatthias Ringwald                 uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 0, 0, channel->req_seq);
1715c7309e8dSMatthias Ringwald                 l2cap_ertm_send_supervisor_frame(channel, control);
1716c7309e8dSMatthias Ringwald                 continue;
1717c7309e8dSMatthias Ringwald             }
1718df2191a7SMatthias Ringwald             if (channel->send_supervisor_frame_selective_reject){
1719df2191a7SMatthias Ringwald                 channel->send_supervisor_frame_selective_reject = 0;
1720df2191a7SMatthias Ringwald                 log_info("Send S-Frame: SREJ %u", channel->expected_tx_seq);
1721f85ade6bSMatthias 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);
1722f85ade6bSMatthias Ringwald                 channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1723df2191a7SMatthias Ringwald                 l2cap_ertm_send_supervisor_frame(channel, control);
1724df2191a7SMatthias Ringwald                 continue;
1725df2191a7SMatthias Ringwald             }
17267b7901d8SMatthias Ringwald 
17277b7901d8SMatthias Ringwald             if (channel->srej_active){
17287b7901d8SMatthias Ringwald                 int i;
17297b7901d8SMatthias Ringwald                 for (i=0;i<channel->num_tx_buffers;i++){
17307b7901d8SMatthias Ringwald                     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
17317b7901d8SMatthias Ringwald                     if (tx_state->retransmission_requested) {
17327b7901d8SMatthias Ringwald                         tx_state->retransmission_requested = 0;
1733d2afdd38SMatthias Ringwald                         uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set;
1734d2afdd38SMatthias Ringwald                         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1735d2afdd38SMatthias Ringwald                         l2cap_ertm_send_information_frame(channel, i, final);
17367b7901d8SMatthias Ringwald                         break;
17377b7901d8SMatthias Ringwald                     }
17387b7901d8SMatthias Ringwald                 }
17397b7901d8SMatthias Ringwald                 if (i == channel->num_tx_buffers){
17407b7901d8SMatthias Ringwald                     // no retransmission request found
17417b7901d8SMatthias Ringwald                     channel->srej_active = 0;
17427b7901d8SMatthias Ringwald                 } else {
17437b7901d8SMatthias Ringwald                     // packet was sent
17447b7901d8SMatthias Ringwald                     continue;
17457b7901d8SMatthias Ringwald                 }
17467b7901d8SMatthias Ringwald             }
17479700d53bSMilanka Ringwald         }
174838f62777SMatthias Ringwald #endif
174938f62777SMatthias Ringwald 
17502cd0be45Smatthias.ringwald     }
175109e9d05bSMatthias Ringwald #endif
1752da886c03S[email protected] 
1753cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1754421cb104SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1755efedfb4cSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1756b5803aafSMatthias Ringwald         uint16_t mps;
1757efedfb4cSMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1758421cb104SMatthias Ringwald 
1759421cb104SMatthias Ringwald         if (channel->channel_type != L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL) continue;
1760421cb104SMatthias Ringwald 
1761efedfb4cSMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1762efedfb4cSMatthias Ringwald         switch (channel->state){
17635cb87675SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
17645cb87675SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
17655cb87675SMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
17665cb87675SMatthias Ringwald                 // le psm, source cid, mtu, mps, initial credits
17671b8b8d05SMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
176863f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
176963f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
1770b5803aafSMatthias Ringwald                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
1771b5803aafSMatthias 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);
17725cb87675SMatthias Ringwald                 break;
177323017473SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
177423017473SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
177523017473SMatthias Ringwald                 // TODO: support larger MPS
177623017473SMatthias Ringwald                 channel->state = L2CAP_STATE_OPEN;
177763f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
177863f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
1779b5803aafSMatthias Ringwald                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
1780b5803aafSMatthias 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);
178164e11ca9SMatthias Ringwald                 // notify client
178244276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0);
178323017473SMatthias Ringwald                 break;
1784e7d0c9aaSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
1785e7d0c9aaSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1786e7d0c9aaSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
178763f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
1788e7d0c9aaSMatthias Ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1789e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1790c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
1791e7d0c9aaSMatthias Ringwald                 break;
17927f107edaSMatthias Ringwald             case L2CAP_STATE_OPEN:
179385aeef60SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
179485aeef60SMatthias Ringwald 
179585aeef60SMatthias Ringwald                 // send credits
179685aeef60SMatthias Ringwald                 if (channel->new_credits_incoming){
179785aeef60SMatthias Ringwald                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
179885aeef60SMatthias Ringwald                     channel->local_sig_id = l2cap_next_sig_id();
179985aeef60SMatthias Ringwald                     uint16_t new_credits = channel->new_credits_incoming;
180085aeef60SMatthias Ringwald                     channel->new_credits_incoming = 0;
180185aeef60SMatthias Ringwald                     channel->credits_incoming += new_credits;
180285aeef60SMatthias Ringwald                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
18036774d5c9SMatthias Ringwald                 }
180485aeef60SMatthias Ringwald                 break;
180585aeef60SMatthias Ringwald 
1806828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1807828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1808828a7f7aSMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
1809828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1810828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1811828a7f7aSMatthias Ringwald                 break;
1812828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1813828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1814828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1815828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1816828a7f7aSMatthias Ringwald                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
1817828a7f7aSMatthias Ringwald                 break;
1818efedfb4cSMatthias Ringwald             default:
1819efedfb4cSMatthias Ringwald                 break;
1820efedfb4cSMatthias Ringwald         }
1821efedfb4cSMatthias Ringwald     }
182209e9d05bSMatthias Ringwald #endif
1823efedfb4cSMatthias Ringwald 
182409e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
1825da886c03S[email protected]     // send l2cap con paramter update if necessary
1826da886c03S[email protected]     hci_connections_get_iterator(&it);
1827665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
1828665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1829c1ab6cc1SMatthias Ringwald         if ((connection->address_type != BD_ADDR_TYPE_LE_PUBLIC) && (connection->address_type != BD_ADDR_TYPE_LE_RANDOM)) continue;
1830b68d7bc3SMatthias Ringwald         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
1831da886c03S[email protected]         switch (connection->le_con_parameter_update_state){
1832b68d7bc3SMatthias Ringwald             case CON_PARAMETER_UPDATE_SEND_REQUEST:
1833b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1834fe8aebe6SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, l2cap_next_sig_id(),
1835b68d7bc3SMatthias Ringwald                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
1836b68d7bc3SMatthias Ringwald                 break;
1837da886c03S[email protected]             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
1838b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
1839b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
1840da886c03S[email protected]                 break;
1841da886c03S[email protected]             case CON_PARAMETER_UPDATE_DENY:
1842b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1843b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
1844da886c03S[email protected]                 break;
1845da886c03S[email protected]             default:
1846da886c03S[email protected]                 break;
1847da886c03S[email protected]         }
1848da886c03S[email protected]     }
18494d7157c3S[email protected] #endif
1850da886c03S[email protected] 
185122c29ab4SMatthias Ringwald     // log_info("l2cap_run: exit");
18522cd0be45Smatthias.ringwald }
18532cd0be45Smatthias.ringwald 
185409e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1855fc64f94aSMatthias Ringwald static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
1856505f1c30SMatthias Ringwald     if ((channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE) || (channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION)) {
1857e5ac0afcSMatthias Ringwald         log_info("connection complete con_handle %04x - for channel %p cid 0x%04x", (int) con_handle, channel, channel->local_cid);
18582df5dadcS[email protected]         // success, start l2cap handshake
1859fc64f94aSMatthias Ringwald         channel->con_handle = con_handle;
18602df5dadcS[email protected]         // check remote SSP feature first
18612df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
18622df5dadcS[email protected]     }
18632df5dadcS[email protected] }
18642df5dadcS[email protected] 
18651b9cb13dSMatthias Ringwald static void l2cap_ready_to_connect(l2cap_channel_t * channel){
18661b9cb13dSMatthias Ringwald 
18671b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
186827e0774aSMatthias Ringwald     // assumption: outgoing connection
18691b9cb13dSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
18701b9cb13dSMatthias Ringwald     if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
18711b9cb13dSMatthias Ringwald         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
18721b9cb13dSMatthias Ringwald         channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
18731b9cb13dSMatthias Ringwald         return;
18741b9cb13dSMatthias Ringwald     }
18751b9cb13dSMatthias Ringwald #endif
18761b9cb13dSMatthias Ringwald 
18771b9cb13dSMatthias Ringwald     // fine, go ahead
18781b9cb13dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
18791b9cb13dSMatthias Ringwald }
18801b9cb13dSMatthias Ringwald 
18812df5dadcS[email protected] static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
18822df5dadcS[email protected]     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
18832df5dadcS[email protected] 
18842df5dadcS[email protected]     // we have been waiting for remote supported features, if both support SSP,
1885ac301f95S[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));
1886fc64f94aSMatthias Ringwald     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
18872df5dadcS[email protected]         // request security level 2
18882df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
1889dfce2622SMilanka Ringwald         channel->required_security_level = LEVEL_2;
1890fc64f94aSMatthias Ringwald         gap_request_security_level(channel->con_handle, LEVEL_2);
18912df5dadcS[email protected]         return;
18922df5dadcS[email protected]     }
18931b9cb13dSMatthias Ringwald 
18941b9cb13dSMatthias Ringwald     l2cap_ready_to_connect(channel);
18952df5dadcS[email protected] }
189609e9d05bSMatthias Ringwald #endif
18972df5dadcS[email protected] 
189809e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
18995d18f623SMatthias 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,
1900da144af5SMatthias Ringwald     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
1901da144af5SMatthias Ringwald 
1902da144af5SMatthias Ringwald     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1903da144af5SMatthias Ringwald     if (!channel) {
1904da144af5SMatthias Ringwald         return NULL;
1905da144af5SMatthias Ringwald     }
1906da144af5SMatthias Ringwald 
1907da144af5SMatthias Ringwald     // fill in
1908da144af5SMatthias Ringwald     channel->packet_handler = packet_handler;
19095d18f623SMatthias Ringwald     channel->channel_type   = channel_type;
1910da144af5SMatthias Ringwald     bd_addr_copy(channel->address, address);
1911da144af5SMatthias Ringwald     channel->address_type = address_type;
1912da144af5SMatthias Ringwald     channel->psm = psm;
1913da144af5SMatthias Ringwald     channel->local_mtu  = local_mtu;
1914b37a9357SMatthias Ringwald     channel->remote_mtu = L2CAP_DEFAULT_MTU;
1915da144af5SMatthias Ringwald     channel->required_security_level = security_level;
1916da144af5SMatthias Ringwald 
1917da144af5SMatthias Ringwald     //
1918da144af5SMatthias Ringwald     channel->local_cid = l2cap_next_local_cid();
1919e0780573SMatthias Ringwald     channel->con_handle = HCI_CON_HANDLE_INVALID;
1920da144af5SMatthias Ringwald 
1921da144af5SMatthias Ringwald     // set initial state
1922da144af5SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
1923da144af5SMatthias Ringwald     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
1924da144af5SMatthias Ringwald     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
1925da144af5SMatthias Ringwald     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
192638f62777SMatthias Ringwald 
1927c45d6b2cSMatthias Ringwald     log_info("create channel %p, local_cid 0x%04x", channel, channel->local_cid);
1928e5ac0afcSMatthias Ringwald 
1929da144af5SMatthias Ringwald     return channel;
1930da144af5SMatthias Ringwald }
1931c45d6b2cSMatthias Ringwald 
1932c45d6b2cSMatthias Ringwald static void l2cap_free_channel_entry(l2cap_channel_t * channel){
1933c45d6b2cSMatthias Ringwald     log_info("free channel %p, local_cid 0x%04x", channel, channel->local_cid);
19348f4dd6c1SMatthias Ringwald     // assert all timers are stopped
1935b5bab9c8SMatthias Ringwald     l2cap_stop_rtx(channel);
19368f4dd6c1SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
19378f4dd6c1SMatthias Ringwald     l2cap_ertm_stop_retransmission_timer(channel);
19388f4dd6c1SMatthias Ringwald     l2cap_ertm_stop_monitor_timer(channel);
19398f4dd6c1SMatthias Ringwald #endif
1940b5bab9c8SMatthias Ringwald     // free  memory
1941c45d6b2cSMatthias Ringwald     btstack_memory_l2cap_channel_free(channel);
1942c45d6b2cSMatthias Ringwald }
194309e9d05bSMatthias Ringwald #endif
194409e9d05bSMatthias Ringwald 
194509e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1946da144af5SMatthias Ringwald 
19479077cb15SMatthias Ringwald /**
19489077cb15SMatthias Ringwald  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
19499077cb15SMatthias Ringwald  * @param packet_handler
19509077cb15SMatthias Ringwald  * @param address
19519077cb15SMatthias Ringwald  * @param psm
19529077cb15SMatthias Ringwald  * @param mtu
19539077cb15SMatthias Ringwald  * @param local_cid
19549077cb15SMatthias Ringwald  */
19559077cb15SMatthias Ringwald 
19569d139fbaSMatthias 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){
19579d139fbaSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
19589d139fbaSMatthias Ringwald     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1959da144af5SMatthias Ringwald 
19609d139fbaSMatthias 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);
1961da144af5SMatthias Ringwald 
1962f16129ceSMatthias 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);
1963fc64f94aSMatthias Ringwald     if (!channel) {
19649077cb15SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
19659077cb15SMatthias Ringwald     }
19669077cb15SMatthias Ringwald 
19671b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
19681b9cb13dSMatthias Ringwald     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
19691b9cb13dSMatthias Ringwald #endif
19701b9cb13dSMatthias Ringwald 
19719077cb15SMatthias Ringwald     // add to connections list
1972fc64f94aSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
19739077cb15SMatthias Ringwald 
19749077cb15SMatthias Ringwald     // store local_cid
19759077cb15SMatthias Ringwald     if (out_local_cid){
1976fc64f94aSMatthias Ringwald        *out_local_cid = channel->local_cid;
19779077cb15SMatthias Ringwald     }
19789077cb15SMatthias Ringwald 
19799077cb15SMatthias Ringwald     // check if hci connection is already usable
1980f16129ceSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
19819077cb15SMatthias Ringwald     if (conn){
1982e5ac0afcSMatthias Ringwald         log_info("l2cap_create_channel, hci connection 0x%04x already exists", conn->con_handle);
1983fc64f94aSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
19849077cb15SMatthias Ringwald         // check if remote supported fearures are already received
19859077cb15SMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
1986fc64f94aSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
19879077cb15SMatthias Ringwald         }
19889077cb15SMatthias Ringwald     }
19899077cb15SMatthias Ringwald 
19909077cb15SMatthias Ringwald     l2cap_run();
19919077cb15SMatthias Ringwald 
1992c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
19939077cb15SMatthias Ringwald }
19949077cb15SMatthias Ringwald 
19951ea99aafSMilanka Ringwald void l2cap_disconnect(uint16_t local_cid, uint8_t reason){
1996e0abb8e7S[email protected]     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
1997b35f641cSmatthias.ringwald     // find channel for local_cid
1998b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1999f62db1e3Smatthias.ringwald     if (channel) {
2000e7ff783cSmatthias.ringwald         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2001f62db1e3Smatthias.ringwald     }
20022cd0be45Smatthias.ringwald     // process
20032cd0be45Smatthias.ringwald     l2cap_run();
200443625864Smatthias.ringwald }
20051e6aba47Smatthias.ringwald 
2006afde0c52Smatthias.ringwald static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
2007ceec418aSMatthias Ringwald     // mark all channels before emitting open events as these could trigger new connetion requests to the same device
2008665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
2009665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2010665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2011665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2012fad84cafSMatthias Ringwald         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2013058e3d6bSMatthias Ringwald         if (bd_addr_cmp( channel->address, address) != 0) continue;
2014c22aecc9S[email protected]         // channel for this address found
2015c22aecc9S[email protected]         switch (channel->state){
2016c22aecc9S[email protected]             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2017c22aecc9S[email protected]             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2018ceec418aSMatthias Ringwald                 channel->state = L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD;
2019c22aecc9S[email protected]                 break;
2020c22aecc9S[email protected]             default:
2021c22aecc9S[email protected]                 break;
2022afde0c52Smatthias.ringwald         }
2023afde0c52Smatthias.ringwald     }
2024ceec418aSMatthias Ringwald     // emit and free marked entries. restart loop to deal with list changes
2025ceec418aSMatthias Ringwald     int done = 0;
2026ceec418aSMatthias Ringwald     while (!done) {
2027ceec418aSMatthias Ringwald         done = 1;
2028ceec418aSMatthias Ringwald         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2029ceec418aSMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
2030ceec418aSMatthias Ringwald             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2031fad84cafSMatthias Ringwald             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2032ceec418aSMatthias Ringwald             if (channel->state == L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD){
2033ceec418aSMatthias Ringwald                 done = 0;
2034ceec418aSMatthias Ringwald                 // failure, forward error code
203566a72640SMatthias Ringwald                 l2cap_handle_channel_open_failed(channel, status);
2036ceec418aSMatthias Ringwald                 // discard channel
2037ceec418aSMatthias Ringwald                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2038c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
2039ceec418aSMatthias Ringwald                 break;
2040ceec418aSMatthias Ringwald             }
2041ceec418aSMatthias Ringwald         }
2042ceec418aSMatthias Ringwald     }
2043ceec418aSMatthias Ringwald 
2044afde0c52Smatthias.ringwald }
2045afde0c52Smatthias.ringwald 
2046afde0c52Smatthias.ringwald static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
2047665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
2048665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2049665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2050665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2051fad84cafSMatthias Ringwald         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2052058e3d6bSMatthias Ringwald         if ( ! bd_addr_cmp( channel->address, address) ){
20532df5dadcS[email protected]             l2cap_handle_connection_complete(handle, channel);
2054afde0c52Smatthias.ringwald         }
2055afde0c52Smatthias.ringwald     }
20566fdcc387Smatthias.ringwald     // process
20576fdcc387Smatthias.ringwald     l2cap_run();
2058afde0c52Smatthias.ringwald }
205909e9d05bSMatthias Ringwald #endif
2060b448a0e7Smatthias.ringwald 
20616774d5c9SMatthias Ringwald static bool l2cap_channel_ready_to_send(l2cap_channel_t * channel){
20626774d5c9SMatthias Ringwald     switch (channel->channel_type){
20636774d5c9SMatthias Ringwald #ifdef ENABLE_CLASSIC
20646774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CLASSIC:
20656774d5c9SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2066d89ab698SMatthias Ringwald             // send if we have more data and remote windows isn't full yet
2067d89ab698SMatthias Ringwald             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2068d89ab698SMatthias Ringwald                 if (channel->unacked_frames >= btstack_min(channel->num_stored_tx_frames, channel->remote_tx_window_size)) return false;
20696774d5c9SMatthias Ringwald                 return hci_can_send_acl_classic_packet_now() != 0;
2070d89ab698SMatthias Ringwald             }
2071d89ab698SMatthias Ringwald #endif
2072d89ab698SMatthias Ringwald             if (!channel->waiting_for_can_send_now) return false;
2073d89ab698SMatthias Ringwald             return (hci_can_send_acl_classic_packet_now() != 0);
20746774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
20756774d5c9SMatthias Ringwald             if (!channel->waiting_for_can_send_now) return false;
20766774d5c9SMatthias Ringwald             return hci_can_send_acl_classic_packet_now() != 0;
20776774d5c9SMatthias Ringwald #endif
20786774d5c9SMatthias Ringwald #ifdef ENABLE_BLE
20796774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_FIXED:
20806774d5c9SMatthias Ringwald             if (!channel->waiting_for_can_send_now) return false;
20816774d5c9SMatthias Ringwald             return hci_can_send_acl_le_packet_now() != 0;
20826774d5c9SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
20836774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
20846774d5c9SMatthias Ringwald             if (channel->send_sdu_buffer == NULL) return false;
20856774d5c9SMatthias Ringwald             if (channel->credits_outgoing == 0) return false;
20866774d5c9SMatthias Ringwald             return hci_can_send_acl_le_packet_now() != 0;
20876774d5c9SMatthias Ringwald #endif
20886774d5c9SMatthias Ringwald #endif
20896774d5c9SMatthias Ringwald         default:
20906774d5c9SMatthias Ringwald             return false;
20916774d5c9SMatthias Ringwald     }
20926774d5c9SMatthias Ringwald }
20936774d5c9SMatthias Ringwald 
20946774d5c9SMatthias Ringwald static void l2cap_channel_trigger_send(l2cap_channel_t * channel){
20956774d5c9SMatthias Ringwald     switch (channel->channel_type){
2096d89ab698SMatthias Ringwald #ifdef ENABLE_CLASSIC
2097d89ab698SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CLASSIC:
2098d89ab698SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2099d89ab698SMatthias Ringwald             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2100d89ab698SMatthias Ringwald                 l2cap_ertm_channel_send_information_frame(channel);
2101d89ab698SMatthias Ringwald                 return;
2102d89ab698SMatthias Ringwald             }
2103d89ab698SMatthias Ringwald #endif
2104d89ab698SMatthias Ringwald             channel->waiting_for_can_send_now = 0;
2105d89ab698SMatthias Ringwald             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2106d89ab698SMatthias Ringwald             break;
2107d89ab698SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
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;
2111d89ab698SMatthias Ringwald #endif
21126774d5c9SMatthias Ringwald #ifdef ENABLE_BLE
2113d89ab698SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_FIXED:
2114d89ab698SMatthias Ringwald             channel->waiting_for_can_send_now = 0;
2115d89ab698SMatthias Ringwald             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2116d89ab698SMatthias Ringwald             break;
21176774d5c9SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
21186774d5c9SMatthias Ringwald         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
21196774d5c9SMatthias Ringwald             l2cap_le_send_pdu(channel);
21206774d5c9SMatthias Ringwald             break;
21216774d5c9SMatthias Ringwald #endif
21226774d5c9SMatthias Ringwald #endif
21236774d5c9SMatthias Ringwald         default:
21246774d5c9SMatthias Ringwald             break;
21256774d5c9SMatthias Ringwald     }
21266774d5c9SMatthias Ringwald }
21276774d5c9SMatthias Ringwald 
212833c40538SMatthias Ringwald static void l2cap_notify_channel_can_send(void){
21296774d5c9SMatthias Ringwald     bool done = false;
21307740e150SMatthias Ringwald     while (!done){
21316774d5c9SMatthias Ringwald         done = true;
213233c40538SMatthias Ringwald         btstack_linked_list_iterator_t it;
213333c40538SMatthias Ringwald         btstack_linked_list_iterator_init(&it, &l2cap_channels);
213433c40538SMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
213533c40538SMatthias Ringwald             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
21366774d5c9SMatthias Ringwald             bool ready = l2cap_channel_ready_to_send(channel);
21376774d5c9SMatthias Ringwald             if (!ready) continue;
21386774d5c9SMatthias Ringwald 
21396774d5c9SMatthias Ringwald             // requeue channel for fairness
21407740e150SMatthias Ringwald             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
21417740e150SMatthias Ringwald             btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
21426774d5c9SMatthias Ringwald 
21436774d5c9SMatthias Ringwald             // trigger sending
21446774d5c9SMatthias Ringwald             l2cap_channel_trigger_send(channel);
21456774d5c9SMatthias Ringwald 
21467740e150SMatthias Ringwald             // exit inner loop as we just broke the iterator, but try again
21476774d5c9SMatthias Ringwald             done = false;
21487740e150SMatthias Ringwald             break;
21497740e150SMatthias Ringwald         }
215033c40538SMatthias Ringwald     }
215133c40538SMatthias Ringwald }
215233c40538SMatthias Ringwald 
21532053036dSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
21542053036dSMatthias Ringwald 
21552053036dSMatthias Ringwald static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){
21562053036dSMatthias Ringwald     // open cannot fail for for incoming connections
21572053036dSMatthias Ringwald     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0;
21582053036dSMatthias Ringwald 
21592053036dSMatthias Ringwald     // check state
21602053036dSMatthias Ringwald     switch (channel->state){
21612053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
21622053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
21632053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES:
21642053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
21652053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
21662053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES:
21672053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
21682053036dSMatthias Ringwald         case L2CAP_STATE_CONFIG:
21692053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
21702053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
21712053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE:
2172ceec418aSMatthias Ringwald         case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD:
21732053036dSMatthias Ringwald             return 1;
21742053036dSMatthias Ringwald 
21752053036dSMatthias Ringwald         case L2CAP_STATE_OPEN:
21762053036dSMatthias Ringwald         case L2CAP_STATE_CLOSED:
21772053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES:
21782053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
21792053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY:
21802053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
21812053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
21822053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
21832053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
21842053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
21852053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
21862053036dSMatthias Ringwald         case L2CAP_STATE_INVALID:
21872053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
21882053036dSMatthias Ringwald             return 0;
21896aa7d794SMatthias Ringwald         // no default here, to get a warning about new states
21902053036dSMatthias Ringwald     }
21916aa7d794SMatthias Ringwald     // still, the compiler insists on a return value
21926aa7d794SMatthias Ringwald     return 0;
21932053036dSMatthias Ringwald }
219413aa3e4bSMatthias Ringwald #endif
21952053036dSMatthias Ringwald 
219613aa3e4bSMatthias Ringwald #ifdef ENABLE_CLASSIC
21972053036dSMatthias Ringwald static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){
21982053036dSMatthias Ringwald     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
219966a72640SMatthias Ringwald         l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
22002053036dSMatthias Ringwald     } else {
220166a72640SMatthias Ringwald         l2cap_handle_channel_closed(channel);
22022053036dSMatthias Ringwald     }
2203c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
22042053036dSMatthias Ringwald }
22052053036dSMatthias Ringwald #endif
22062053036dSMatthias Ringwald 
22072cf36df7SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
22082cf36df7SMatthias Ringwald static void l2cap_handle_hci_le_disconnect_event(l2cap_channel_t * channel){
22092cf36df7SMatthias Ringwald     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
22102cf36df7SMatthias Ringwald         l2cap_emit_le_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
22112cf36df7SMatthias Ringwald     } else {
22122cf36df7SMatthias Ringwald         l2cap_emit_le_channel_closed(channel);
22132cf36df7SMatthias Ringwald     }
2214c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
22152cf36df7SMatthias Ringwald }
22162cf36df7SMatthias Ringwald #endif
22172053036dSMatthias Ringwald 
2218d9a7306aSMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
2219afde0c52Smatthias.ringwald 
22205774a392SMatthias Ringwald     UNUSED(packet_type); // ok: registered with hci_event_callback_registration
22215774a392SMatthias Ringwald     UNUSED(cid);         // ok: there is no channel
22225774a392SMatthias Ringwald     UNUSED(size);        // ok: fixed format events read from HCI buffer
22239ec2630cSMatthias Ringwald 
22245774a392SMatthias Ringwald #ifdef ENABLE_CLASSIC
2225afde0c52Smatthias.ringwald     bd_addr_t address;
22262d00edd4Smatthias.ringwald     int hci_con_used;
22275774a392SMatthias Ringwald #endif
22285774a392SMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
22295774a392SMatthias Ringwald     hci_con_handle_t handle;
223009e9d05bSMatthias Ringwald     btstack_linked_list_iterator_t it;
22315774a392SMatthias Ringwald #endif
2232afde0c52Smatthias.ringwald 
22330e2df43fSMatthias Ringwald     switch(hci_event_packet_get_type(packet)){
2234afde0c52Smatthias.ringwald 
223509e9d05bSMatthias Ringwald         // Notify channel packet handler if they can send now
223609e9d05bSMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
223709e9d05bSMatthias Ringwald         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
2238eea99214SMatthias Ringwald         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
223909e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
224009e9d05bSMatthias Ringwald             l2cap_notify_channel_can_send();
224109e9d05bSMatthias Ringwald             break;
224209e9d05bSMatthias Ringwald 
224309e9d05bSMatthias Ringwald         case HCI_EVENT_COMMAND_STATUS:
2244ece97caeSMatthias Ringwald #ifdef ENABLE_CLASSIC
2245ece97caeSMatthias Ringwald             // check command status for create connection for errors
2246ece97caeSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
2247ece97caeSMatthias Ringwald                 // cache outgoing address and reset
2248*6535961aSMatthias Ringwald                 (void)memcpy(address, l2cap_outgoing_classic_addr, 6);
2249ece97caeSMatthias Ringwald                 memset(l2cap_outgoing_classic_addr, 0, 6);
2250ece97caeSMatthias Ringwald                 // error => outgoing connection failed
2251ece97caeSMatthias Ringwald                 uint8_t status = hci_event_command_status_get_status(packet);
2252ece97caeSMatthias Ringwald                 if (status){
2253ece97caeSMatthias Ringwald                     l2cap_handle_connection_failed_for_addr(address, status);
2254ece97caeSMatthias Ringwald                 }
2255ece97caeSMatthias Ringwald             }
2256ece97caeSMatthias Ringwald #endif
225709e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
225809e9d05bSMatthias Ringwald             break;
225909e9d05bSMatthias Ringwald 
226009e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2261afde0c52Smatthias.ringwald         // handle connection complete events
2262afde0c52Smatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
2263724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], address);
2264afde0c52Smatthias.ringwald             if (packet[2] == 0){
2265f8fbdce0SMatthias Ringwald                 handle = little_endian_read_16(packet, 3);
2266afde0c52Smatthias.ringwald                 l2cap_handle_connection_success_for_addr(address, handle);
2267afde0c52Smatthias.ringwald             } else {
2268afde0c52Smatthias.ringwald                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
2269afde0c52Smatthias.ringwald             }
2270afde0c52Smatthias.ringwald             break;
2271afde0c52Smatthias.ringwald 
2272afde0c52Smatthias.ringwald         // handle successful create connection cancel command
2273afde0c52Smatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
2274073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
2275afde0c52Smatthias.ringwald                 if (packet[5] == 0){
2276724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[6], address);
2277afde0c52Smatthias.ringwald                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
2278afde0c52Smatthias.ringwald                     l2cap_handle_connection_failed_for_addr(address, 0x16);
227903cfbabcSmatthias.ringwald                 }
22801e6aba47Smatthias.ringwald             }
228139d59809Smatthias.ringwald             l2cap_run();    // try sending signaling packets first
228239d59809Smatthias.ringwald             break;
228309e9d05bSMatthias Ringwald #endif
228427a923d0Smatthias.ringwald 
22852053036dSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
22861e6aba47Smatthias.ringwald         // handle disconnection complete events
2287afde0c52Smatthias.ringwald         case HCI_EVENT_DISCONNECTION_COMPLETE:
2288d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
22892053036dSMatthias Ringwald             // send l2cap open failed or closed events for all channels on this handle and free them
2290665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2291665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2292665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2293fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2294fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
2295665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
2296421cb104SMatthias Ringwald                 switch(channel->channel_type){
2297421cb104SMatthias Ringwald #ifdef ENABLE_CLASSIC
2298421cb104SMatthias Ringwald                     case L2CAP_CHANNEL_TYPE_CLASSIC:
22992053036dSMatthias Ringwald                         l2cap_handle_hci_disconnect_event(channel);
2300421cb104SMatthias Ringwald                         break;
230109e9d05bSMatthias Ringwald #endif
2302a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2303421cb104SMatthias Ringwald                     case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
23042cf36df7SMatthias Ringwald                         l2cap_handle_hci_le_disconnect_event(channel);
2305afde0c52Smatthias.ringwald                         break;
23062053036dSMatthias Ringwald #endif
2307421cb104SMatthias Ringwald                     default:
2308421cb104SMatthias Ringwald                         break;
2309421cb104SMatthias Ringwald                 }
2310421cb104SMatthias Ringwald             }
23119909e5e4SMatthias Ringwald             break;
2312421cb104SMatthias Ringwald #endif
2313fcadd0caSmatthias.ringwald 
23149909e5e4SMatthias Ringwald 
2315ee091cf1Smatthias.ringwald         // HCI Connection Timeouts
231609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2317afde0c52Smatthias.ringwald         case L2CAP_EVENT_TIMEOUT_CHECK:
2318f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
2319bd04d84aSMatthias Ringwald             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
232080ca58a0Smatthias.ringwald             if (hci_authentication_active_for_handle(handle)) break;
23212d00edd4Smatthias.ringwald             hci_con_used = 0;
2322665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2323665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2324665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2325fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2326fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
23272d00edd4Smatthias.ringwald                 hci_con_used = 1;
2328c22aecc9S[email protected]                 break;
2329ee091cf1Smatthias.ringwald             }
23302d00edd4Smatthias.ringwald             if (hci_con_used) break;
2331d94d3cafS[email protected]             if (!hci_can_send_command_packet_now()) break;
23329edc8742Smatthias.ringwald             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
2333afde0c52Smatthias.ringwald             break;
2334ee091cf1Smatthias.ringwald 
2335df3354fcS[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2336f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
2337665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2338665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2339665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2340fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2341fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
2342e5ac0afcSMatthias Ringwald                 log_info("remote supported features, channel %p, cid %04x - state %u", channel, channel->local_cid, channel->state);
23432df5dadcS[email protected]                 l2cap_handle_remote_supported_features_received(channel);
2344df3354fcS[email protected]             }
2345c22aecc9S[email protected]             break;
2346df3354fcS[email protected] 
23475611a760SMatthias Ringwald         case GAP_EVENT_SECURITY_LEVEL:
2348f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
2349e5ac0afcSMatthias Ringwald             log_info("l2cap - security level update for handle 0x%04x", handle);
2350665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2351665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2352665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2353fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2354fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
23555533f01eS[email protected] 
2356e569dfd9SMatthias Ringwald                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
23575533f01eS[email protected]                 gap_security_level_t required_level = channel->required_security_level;
23585533f01eS[email protected] 
2359e5ac0afcSMatthias Ringwald                 log_info("channel %p, cid %04x - state %u: actual %u >= required %u?", channel, channel->local_cid, channel->state, actual_level, required_level);
2360dfce2622SMilanka Ringwald 
2361df3354fcS[email protected]                 switch (channel->state){
2362df3354fcS[email protected]                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
23635533f01eS[email protected]                         if (actual_level >= required_level){
236452606043SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
236552606043SMatthias Ringwald                             // we need to know if ERTM is supported before sending a config response
236652606043SMatthias Ringwald                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
236752606043SMatthias Ringwald                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
236852606043SMatthias Ringwald                             channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
236952606043SMatthias Ringwald #else
2370f85a9399S[email protected]                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
237144276248SMatthias Ringwald                             l2cap_emit_incoming_connection(channel);
237252606043SMatthias Ringwald #endif
23731eb2563eS[email protected]                         } else {
2374775ecc36SMatthias Ringwald                             channel->reason = 0x0003; // security block
23751eb2563eS[email protected]                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
23761eb2563eS[email protected]                         }
2377df3354fcS[email protected]                         break;
2378df3354fcS[email protected] 
2379df3354fcS[email protected]                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
23805533f01eS[email protected]                         if (actual_level >= required_level){
23811b9cb13dSMatthias Ringwald                             l2cap_ready_to_connect(channel);
2382df3354fcS[email protected]                         } else {
2383df3354fcS[email protected]                             // disconnnect, authentication not good enough
2384df3354fcS[email protected]                             hci_disconnect_security_block(handle);
2385df3354fcS[email protected]                         }
2386df3354fcS[email protected]                         break;
2387df3354fcS[email protected] 
2388df3354fcS[email protected]                     default:
2389df3354fcS[email protected]                         break;
2390df3354fcS[email protected]                 }
2391f85a9399S[email protected]             }
2392f85a9399S[email protected]             break;
239309e9d05bSMatthias Ringwald #endif
2394f85a9399S[email protected] 
2395afde0c52Smatthias.ringwald         default:
2396afde0c52Smatthias.ringwald             break;
2397afde0c52Smatthias.ringwald     }
2398afde0c52Smatthias.ringwald 
2399bd63148eS[email protected]     l2cap_run();
24001e6aba47Smatthias.ringwald }
24011e6aba47Smatthias.ringwald 
2402e74c5f58SMatthias 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){
24034cf56b4aSmatthias.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."
24042b360848Smatthias.ringwald     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
24052b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].handle = handle;
24062b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].code = code;
24072b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].sig_id = sig_id;
2408e74c5f58SMatthias Ringwald         signaling_responses[signaling_responses_pending].cid = cid;
24092b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].data = data;
24102b360848Smatthias.ringwald         signaling_responses_pending++;
24112b360848Smatthias.ringwald         l2cap_run();
24122b360848Smatthias.ringwald     }
24132b360848Smatthias.ringwald }
24142b360848Smatthias.ringwald 
241509e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
241609e9d05bSMatthias Ringwald static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
241709e9d05bSMatthias Ringwald     channel->remote_sig_id = identifier;
241809e9d05bSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
241909e9d05bSMatthias Ringwald     l2cap_run();
242009e9d05bSMatthias Ringwald }
242109e9d05bSMatthias Ringwald 
2422b35f641cSmatthias.ringwald static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
2423645658c9Smatthias.ringwald 
24249da54300S[email protected]     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
2425645658c9Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
2426645658c9Smatthias.ringwald     if (!service) {
2427645658c9Smatthias.ringwald         // 0x0002 PSM not supported
2428e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2429645658c9Smatthias.ringwald         return;
2430645658c9Smatthias.ringwald     }
2431645658c9Smatthias.ringwald 
24325061f3afS[email protected]     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
2433645658c9Smatthias.ringwald     if (!hci_connection) {
24342b360848Smatthias.ringwald         //
24359da54300S[email protected]         log_error("no hci_connection for handle %u", handle);
2436645658c9Smatthias.ringwald         return;
2437645658c9Smatthias.ringwald     }
24382bd8b7e7S[email protected] 
2439645658c9Smatthias.ringwald     // alloc structure
24409da54300S[email protected]     // log_info("l2cap_handle_connection_request register channel");
2441f16129ceSMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, hci_connection->address, BD_ADDR_TYPE_ACL,
2442da144af5SMatthias Ringwald     psm, service->mtu, service->required_security_level);
24432b360848Smatthias.ringwald     if (!channel){
24442b360848Smatthias.ringwald         // 0x0004 No resources available
2445e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
24462b360848Smatthias.ringwald         return;
24472b360848Smatthias.ringwald     }
2448da144af5SMatthias Ringwald 
2449fc64f94aSMatthias Ringwald     channel->con_handle = handle;
2450b35f641cSmatthias.ringwald     channel->remote_cid = source_cid;
2451b1988dceSmatthias.ringwald     channel->remote_sig_id = sig_id;
2452645658c9Smatthias.ringwald 
2453f53da564S[email protected]     // limit local mtu to max acl packet length - l2cap header
24542985cb84Smatthias.ringwald     if (channel->local_mtu > l2cap_max_mtu()) {
24552985cb84Smatthias.ringwald         channel->local_mtu = l2cap_max_mtu();
24569775e25bSmatthias.ringwald     }
24579775e25bSmatthias.ringwald 
2458645658c9Smatthias.ringwald     // set initial state
2459df3354fcS[email protected]     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
2460a24785d0SMatthias Ringwald     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
2461e405ae81Smatthias.ringwald 
2462645658c9Smatthias.ringwald     // add to connections list
2463665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
2464645658c9Smatthias.ringwald 
2465f85a9399S[email protected]     // assert security requirements
24661eb2563eS[email protected]     gap_request_security_level(handle, channel->required_security_level);
2467e405ae81Smatthias.ringwald }
2468645658c9Smatthias.ringwald 
2469ce8f182eSMatthias Ringwald void l2cap_accept_connection(uint16_t local_cid){
2470e0abb8e7S[email protected]     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
2471b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2472e405ae81Smatthias.ringwald     if (!channel) {
2473ce8f182eSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
2474e405ae81Smatthias.ringwald         return;
2475e405ae81Smatthias.ringwald     }
2476e405ae81Smatthias.ringwald 
247743ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
247843ec931dSMatthias Ringwald     // configure L2CAP Basic mode
247943ec931dSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
248043ec931dSMatthias Ringwald #endif
248143ec931dSMatthias Ringwald 
2482552d92a1Smatthias.ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
2483e405ae81Smatthias.ringwald 
2484552d92a1Smatthias.ringwald     // process
2485552d92a1Smatthias.ringwald     l2cap_run();
2486e405ae81Smatthias.ringwald }
2487645658c9Smatthias.ringwald 
24887ef6a7bbSMatthias Ringwald void l2cap_decline_connection(uint16_t local_cid){
24897ef6a7bbSMatthias Ringwald     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
2490b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
2491e405ae81Smatthias.ringwald     if (!channel) {
2492ce8f182eSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
2493e405ae81Smatthias.ringwald         return;
2494e405ae81Smatthias.ringwald     }
2495e7ff783cSmatthias.ringwald     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
24967ef6a7bbSMatthias Ringwald     channel->reason = 0x04; // no resources available
2497e7ff783cSmatthias.ringwald     l2cap_run();
2498645658c9Smatthias.ringwald }
2499645658c9Smatthias.ringwald 
2500e9cfb251SMatthias Ringwald // @pre command len is valid, see check in l2cap_signaling_handler_channel
25017f02f414SMatthias Ringwald static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
2502b1988dceSmatthias.ringwald 
2503fcb125edSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2504fcb125edSMatthias Ringwald     uint8_t use_fcs = 1;
2505fcb125edSMatthias Ringwald #endif
2506fcb125edSMatthias Ringwald 
2507b1988dceSmatthias.ringwald     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2508b1988dceSmatthias.ringwald 
2509f8fbdce0SMatthias Ringwald     uint16_t flags = little_endian_read_16(command, 6);
251063a7246aSmatthias.ringwald     if (flags & 1) {
251163a7246aSmatthias.ringwald         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
251263a7246aSmatthias.ringwald     }
251363a7246aSmatthias.ringwald 
25142784b77dSmatthias.ringwald     // accept the other's configuration options
2515f8fbdce0SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
25163de7c0caSmatthias.ringwald     uint16_t pos     = 8;
25173de7c0caSmatthias.ringwald     while (pos < end_pos){
251863a7246aSmatthias.ringwald         uint8_t option_hint = command[pos] >> 7;
251963a7246aSmatthias.ringwald         uint8_t option_type = command[pos] & 0x7f;
25203844aeadSMatthias Ringwald         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
252163a7246aSmatthias.ringwald         pos++;
25221dc511deSmatthias.ringwald         uint8_t length = command[pos++];
25231dc511deSmatthias.ringwald         // MTU { type(8): 1, len(8):2, MTU(16) }
2524c1ab6cc1SMatthias Ringwald         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) && (length == 2)){
2525f8fbdce0SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, pos);
25263844aeadSMatthias Ringwald             log_info("Remote MTU %u", channel->remote_mtu);
25279d139fbaSMatthias Ringwald             if (channel->remote_mtu > l2cap_max_mtu()){
25289d139fbaSMatthias Ringwald                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
25299d139fbaSMatthias Ringwald                 channel->remote_mtu = l2cap_max_mtu();
25309d139fbaSMatthias Ringwald             }
253163a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
253263a7246aSmatthias.ringwald         }
25330fe7a9d0S[email protected]         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
2534e53a3388SMatthias Ringwald         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT) && (length == 2)){
2535f8fbdce0SMatthias Ringwald             channel->flush_timeout = little_endian_read_16(command, pos);
25363844aeadSMatthias Ringwald             log_info("Flush timeout: %u ms", channel->flush_timeout);
25370fe7a9d0S[email protected]         }
2538f2fa388dSMatthias Ringwald 
25396dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
25406dca2a0cSMatthias Ringwald         // Retransmission and Flow Control Option
2541671fb338SMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
25423232a1c6SMatthias Ringwald             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
2543ac8f1300SMatthias Ringwald             switch(channel->mode){
2544ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
254525cd60d3SMatthias Ringwald                     // Store remote config
2546bbc0a9e7SMatthias Ringwald                     channel->remote_tx_window_size = command[pos+1];
2547bbc0a9e7SMatthias Ringwald                     channel->remote_max_transmit   = command[pos+2];
2548bbc0a9e7SMatthias Ringwald                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
2549bbc0a9e7SMatthias Ringwald                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
25503844aeadSMatthias Ringwald                     channel->remote_mps = little_endian_read_16(command, pos + 7);
25513844aeadSMatthias Ringwald                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
2552bbc0a9e7SMatthias Ringwald                         channel->remote_tx_window_size,
2553bbc0a9e7SMatthias Ringwald                         channel->remote_max_transmit,
2554bbc0a9e7SMatthias Ringwald                         channel->remote_retransmission_timeout_ms,
25553844aeadSMatthias Ringwald                         channel->remote_monitor_timeout_ms,
25563844aeadSMatthias Ringwald                         channel->remote_mps);
255725cd60d3SMatthias Ringwald                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
255825cd60d3SMatthias Ringwald                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
255925cd60d3SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2560ac8f1300SMatthias Ringwald                     } else {
2561b8134563SMatthias Ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2562ac8f1300SMatthias Ringwald                     }
2563ac8f1300SMatthias Ringwald                     break;
2564ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
2565ac8f1300SMatthias Ringwald                     switch (mode){
2566ac8f1300SMatthias Ringwald                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2567ac8f1300SMatthias Ringwald                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
2568ac8f1300SMatthias Ringwald                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
2569ac8f1300SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2570ac8f1300SMatthias Ringwald                             }
2571ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
2572ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
2573ac8f1300SMatthias Ringwald                             break;
2574ac8f1300SMatthias Ringwald                         default: // case L2CAP_CHANNEL_MODE_BASIC:
2575ac8f1300SMatthias Ringwald                             // TODO store and evaluate configuration
2576b8134563SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2577ac8f1300SMatthias Ringwald                             break;
2578ac8f1300SMatthias Ringwald                     }
2579ac8f1300SMatthias Ringwald                     break;
2580ac8f1300SMatthias Ringwald                 default:
2581ac8f1300SMatthias Ringwald                     break;
2582ac8f1300SMatthias Ringwald             }
25833232a1c6SMatthias Ringwald         }
25846574158aSMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
2585fcb125edSMatthias Ringwald             use_fcs = command[pos];
25866574158aSMatthias Ringwald         }
25876dca2a0cSMatthias Ringwald #endif
258863a7246aSmatthias.ringwald         // check for unknown options
2589505f1c30SMatthias Ringwald         if ((option_hint == 0) && ((option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) || (option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE))){
2590c177a91cS[email protected]             log_info("l2cap cid %u, unknown options", channel->local_cid);
259163a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
25921dc511deSmatthias.ringwald         }
25931dc511deSmatthias.ringwald         pos += length;
25941dc511deSmatthias.ringwald     }
2595fcb125edSMatthias Ringwald 
2596fcb125edSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2597fcb125edSMatthias Ringwald         // "FCS" has precedence over "No FCS"
2598fcb125edSMatthias Ringwald         uint8_t update = channel->fcs_option || use_fcs;
2599fcb125edSMatthias Ringwald         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
2600fcb125edSMatthias Ringwald         channel->fcs_option = update;
260167f8f607SMatthias Ringwald         // If ERTM mandatory, but remote didn't send Retransmission and Flowcontrol options -> disconnect
260267f8f607SMatthias Ringwald         if (((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM) == 0) & (channel->ertm_mandatory)){
260367f8f607SMatthias Ringwald             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
260467f8f607SMatthias Ringwald         }
2605fcb125edSMatthias Ringwald #endif
26062784b77dSmatthias.ringwald }
26072784b77dSmatthias.ringwald 
2608e9cfb251SMatthias Ringwald // @pre command len is valid, see check in l2cap_signaling_handler_channel
2609f2fa388dSMatthias Ringwald static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
2610f2fa388dSMatthias Ringwald     log_info("l2cap_signaling_handle_configure_response");
26113232a1c6SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
26123232a1c6SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2613f2fa388dSMatthias Ringwald     uint16_t pos     = 10;
26143232a1c6SMatthias Ringwald     while (pos < end_pos){
26153232a1c6SMatthias Ringwald         uint8_t option_hint = command[pos] >> 7;
26163232a1c6SMatthias Ringwald         uint8_t option_type = command[pos] & 0x7f;
2617fcb125edSMatthias Ringwald         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
26183232a1c6SMatthias Ringwald         pos++;
26193232a1c6SMatthias Ringwald         uint8_t length = command[pos++];
26203232a1c6SMatthias Ringwald 
26213232a1c6SMatthias Ringwald         // Retransmission and Flow Control Option
2622671fb338SMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2623ac8f1300SMatthias Ringwald             switch (channel->mode){
2624ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2625f2fa388dSMatthias Ringwald                     if (channel->ertm_mandatory){
2626ac8f1300SMatthias Ringwald                         // ??
2627f2fa388dSMatthias Ringwald                     } else {
2628ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
2629ac8f1300SMatthias Ringwald                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
263066a72640SMatthias Ringwald                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
2631f2fa388dSMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
26323232a1c6SMatthias Ringwald                         }
26333232a1c6SMatthias Ringwald                     }
2634ac8f1300SMatthias Ringwald                     break;
2635ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
2636ac8f1300SMatthias Ringwald                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2637ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
2638ac8f1300SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2639ac8f1300SMatthias Ringwald                     }
2640ac8f1300SMatthias Ringwald                     break;
2641ac8f1300SMatthias Ringwald                 default:
2642ac8f1300SMatthias Ringwald                     break;
26433232a1c6SMatthias Ringwald             }
2644f2fa388dSMatthias Ringwald         }
26453232a1c6SMatthias Ringwald 
26463232a1c6SMatthias Ringwald         // check for unknown options
2647671fb338SMatthias Ringwald         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
26483232a1c6SMatthias Ringwald             log_info("l2cap cid %u, unknown options", channel->local_cid);
26493232a1c6SMatthias Ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
26503232a1c6SMatthias Ringwald         }
26513232a1c6SMatthias Ringwald 
26523232a1c6SMatthias Ringwald         pos += length;
26533232a1c6SMatthias Ringwald     }
2654688f9764SMatthias Ringwald #else
26555774a392SMatthias Ringwald     UNUSED(channel);  // ok: no code
26565774a392SMatthias Ringwald     UNUSED(result);   // ok: no code
26575774a392SMatthias Ringwald     UNUSED(command);  // ok: no code
26583232a1c6SMatthias Ringwald #endif
26593232a1c6SMatthias Ringwald }
26603232a1c6SMatthias Ringwald 
2661fa8473a4Smatthias.ringwald static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
26629da54300S[email protected]     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
266373cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
266473cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
2665019f9b43SMatthias Ringwald     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
2666019f9b43SMatthias Ringwald     if (channel->state == L2CAP_STATE_OPEN) return 0;
2667fa8473a4Smatthias.ringwald     return 1;
2668fa8473a4Smatthias.ringwald }
2669fa8473a4Smatthias.ringwald 
2670fa8473a4Smatthias.ringwald 
2671e9cfb251SMatthias Ringwald // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
26727f02f414SMatthias Ringwald static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
26731e6aba47Smatthias.ringwald 
267400d93d79Smatthias.ringwald     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
267500d93d79Smatthias.ringwald     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2676e9cfb251SMatthias Ringwald     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
267738e5900eSmatthias.ringwald     uint16_t result = 0;
26781e6aba47Smatthias.ringwald 
26799da54300S[email protected]     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
2680b35f641cSmatthias.ringwald 
26819a011532Smatthias.ringwald     // handle DISCONNECT REQUESTS seperately
26829a011532Smatthias.ringwald     if (code == DISCONNECTION_REQUEST){
26839a011532Smatthias.ringwald         switch (channel->state){
2684fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
26859a011532Smatthias.ringwald             case L2CAP_STATE_OPEN:
26862b83fb7dSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
26879a011532Smatthias.ringwald             case L2CAP_STATE_WAIT_DISCONNECT:
26889a011532Smatthias.ringwald                 l2cap_handle_disconnect_request(channel, identifier);
26899a011532Smatthias.ringwald                 break;
26909a011532Smatthias.ringwald 
26919a011532Smatthias.ringwald             default:
26929a011532Smatthias.ringwald                 // ignore in other states
26939a011532Smatthias.ringwald                 break;
26949a011532Smatthias.ringwald         }
26959a011532Smatthias.ringwald         return;
26969a011532Smatthias.ringwald     }
26979a011532Smatthias.ringwald 
269856081214Smatthias.ringwald     // @STATEMACHINE(l2cap)
26991e6aba47Smatthias.ringwald     switch (channel->state) {
27001e6aba47Smatthias.ringwald 
27011e6aba47Smatthias.ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
27021e6aba47Smatthias.ringwald             switch (code){
27031e6aba47Smatthias.ringwald                 case CONNECTION_RESPONSE:
2704e9cfb251SMatthias Ringwald                     if (cmd_len < 8){
2705e9cfb251SMatthias Ringwald                         // command imcomplete
2706e9cfb251SMatthias Ringwald                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2707e9cfb251SMatthias Ringwald                         break;
2708e9cfb251SMatthias Ringwald                     }
27095932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2710f8fbdce0SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
271138e5900eSmatthias.ringwald                     switch (result) {
271238e5900eSmatthias.ringwald                         case 0:
2713169f8b28Smatthias.ringwald                             // successful connection
2714f8fbdce0SMatthias Ringwald                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2715fa8473a4Smatthias.ringwald                             channel->state = L2CAP_STATE_CONFIG;
271628ca2b46S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
271738e5900eSmatthias.ringwald                             break;
271838e5900eSmatthias.ringwald                         case 1:
27195932bd7cS[email protected]                             // connection pending. get some coffee, but start the ERTX
27205932bd7cS[email protected]                             l2cap_start_ertx(channel);
272138e5900eSmatthias.ringwald                             break;
272238e5900eSmatthias.ringwald                         default:
2723eb920dbeSmatthias.ringwald                             // channel closed
2724eb920dbeSmatthias.ringwald                             channel->state = L2CAP_STATE_CLOSED;
2725f32b992eSmatthias.ringwald                             // map l2cap connection response result to BTstack status enumeration
272666a72640SMatthias Ringwald                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
2727eb920dbeSmatthias.ringwald 
2728eb920dbeSmatthias.ringwald                             // drop link key if security block
2729c1ab6cc1SMatthias Ringwald                             if ((L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result) == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
273015a95bd5SMatthias Ringwald                                 gap_drop_link_key_for_bd_addr(channel->address);
2731eb920dbeSmatthias.ringwald                             }
2732eb920dbeSmatthias.ringwald 
2733eb920dbeSmatthias.ringwald                             // discard channel
2734665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2735c45d6b2cSMatthias Ringwald                             l2cap_free_channel_entry(channel);
273638e5900eSmatthias.ringwald                             break;
27371e6aba47Smatthias.ringwald                     }
27381e6aba47Smatthias.ringwald                     break;
273938e5900eSmatthias.ringwald 
274038e5900eSmatthias.ringwald                 default:
27411e6aba47Smatthias.ringwald                     //@TODO: implement other signaling packets
274238e5900eSmatthias.ringwald                     break;
27431e6aba47Smatthias.ringwald             }
27441e6aba47Smatthias.ringwald             break;
27451e6aba47Smatthias.ringwald 
2746fa8473a4Smatthias.ringwald         case L2CAP_STATE_CONFIG:
2747ae280e73Smatthias.ringwald             switch (code) {
2748ae280e73Smatthias.ringwald                 case CONFIGURE_REQUEST:
2749e9cfb251SMatthias Ringwald                     if (cmd_len < 4){
2750e9cfb251SMatthias Ringwald                         // command incomplete
2751e9cfb251SMatthias Ringwald                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2752e9cfb251SMatthias Ringwald                         break;
2753e9cfb251SMatthias Ringwald                     }
275428ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
2755ae280e73Smatthias.ringwald                     l2cap_signaling_handle_configure_request(channel, command);
275663a7246aSmatthias.ringwald                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
275763a7246aSmatthias.ringwald                         // only done if continuation not set
275863a7246aSmatthias.ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
275963a7246aSmatthias.ringwald                     }
2760ae280e73Smatthias.ringwald                     break;
27611e6aba47Smatthias.ringwald                 case CONFIGURE_RESPONSE:
2762e9cfb251SMatthias Ringwald                     if (cmd_len < 6){
2763e9cfb251SMatthias Ringwald                         // command incomplete
2764e9cfb251SMatthias Ringwald                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2765e9cfb251SMatthias Ringwald                         break;
2766e9cfb251SMatthias Ringwald                     }
2767e9cfb251SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
27685932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2769f2fa388dSMatthias Ringwald                     l2cap_signaling_handle_configure_response(channel, result, command);
27705932bd7cS[email protected]                     switch (result){
27715932bd7cS[email protected]                         case 0: // success
27725932bd7cS[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
27735932bd7cS[email protected]                             break;
27745932bd7cS[email protected]                         case 4: // pending
27755932bd7cS[email protected]                             l2cap_start_ertx(channel);
27765932bd7cS[email protected]                             break;
27775932bd7cS[email protected]                         default:
2778a32d6a03SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2779a32d6a03SMatthias Ringwald                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
2780a32d6a03SMatthias Ringwald                                 // remote does not offer ertm but it's required
2781a32d6a03SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2782a32d6a03SMatthias Ringwald                                 break;
2783a32d6a03SMatthias Ringwald                             }
2784a32d6a03SMatthias Ringwald #endif
2785fe9d8984S[email protected]                             // retry on negative result
2786fe9d8984S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2787fe9d8984S[email protected]                             break;
2788fe9d8984S[email protected]                     }
27895a67bd4aSmatthias.ringwald                     break;
27905a67bd4aSmatthias.ringwald                 default:
27915a67bd4aSmatthias.ringwald                     break;
27921e6aba47Smatthias.ringwald             }
2793fa8473a4Smatthias.ringwald             if (l2cap_channel_ready_for_open(channel)){
27942e4c1850SMatthias Ringwald 
27952e4c1850SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
27962e4c1850SMatthias Ringwald                 // assert that packet can be stored in fragment buffers in ertm
27972e4c1850SMatthias Ringwald                 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
27982e4c1850SMatthias Ringwald                     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
27992e4c1850SMatthias Ringwald                     uint16_t usable_mtu = channel->num_tx_buffers == 1 ? effective_mps : channel->num_tx_buffers * effective_mps - 2;
28002e4c1850SMatthias Ringwald                     if (usable_mtu < channel->remote_mtu){
28012e4c1850SMatthias Ringwald                         log_info("Remote MTU %u > max storable ERTM packet, only using MTU = %u", channel->remote_mtu, usable_mtu);
28022e4c1850SMatthias Ringwald                         channel->remote_mtu = usable_mtu;
28032e4c1850SMatthias Ringwald                     }
28042e4c1850SMatthias Ringwald                 }
28052e4c1850SMatthias Ringwald #endif
2806fa8473a4Smatthias.ringwald                 // for open:
28075a67bd4aSmatthias.ringwald                 channel->state = L2CAP_STATE_OPEN;
2808fa8473a4Smatthias.ringwald                 l2cap_emit_channel_opened(channel, 0);
2809c8e4258aSmatthias.ringwald             }
2810c8e4258aSmatthias.ringwald             break;
2811f62db1e3Smatthias.ringwald 
2812f62db1e3Smatthias.ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
2813f62db1e3Smatthias.ringwald             switch (code) {
2814f62db1e3Smatthias.ringwald                 case DISCONNECTION_RESPONSE:
281527a923d0Smatthias.ringwald                     l2cap_finialize_channel_close(channel);
281627a923d0Smatthias.ringwald                     break;
28175a67bd4aSmatthias.ringwald                 default:
28185a67bd4aSmatthias.ringwald                     //@TODO: implement other signaling packets
28195a67bd4aSmatthias.ringwald                     break;
282027a923d0Smatthias.ringwald             }
282127a923d0Smatthias.ringwald             break;
282284836b65Smatthias.ringwald 
282384836b65Smatthias.ringwald         case L2CAP_STATE_CLOSED:
282484836b65Smatthias.ringwald             // @TODO handle incoming requests
282584836b65Smatthias.ringwald             break;
282684836b65Smatthias.ringwald 
282784836b65Smatthias.ringwald         case L2CAP_STATE_OPEN:
282884836b65Smatthias.ringwald             //@TODO: implement other signaling packets, e.g. re-configure
282984836b65Smatthias.ringwald             break;
283010642e45Smatthias.ringwald         default:
283110642e45Smatthias.ringwald             break;
283227a923d0Smatthias.ringwald     }
28339da54300S[email protected]     // log_info("new state %u", channel->state);
283427a923d0Smatthias.ringwald }
283527a923d0Smatthias.ringwald 
283600d93d79Smatthias.ringwald 
2837ed2ed8e1SMatthias Ringwald // @pre command len is valid, see check in l2cap_acl_classic_handler
28387f02f414SMatthias Ringwald static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
283900d93d79Smatthias.ringwald 
28401b9cb13dSMatthias Ringwald     btstack_linked_list_iterator_t it;
28411b9cb13dSMatthias Ringwald 
284200d93d79Smatthias.ringwald     // get code, signalind identifier and command len
284300d93d79Smatthias.ringwald     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
284400d93d79Smatthias.ringwald     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
28450493bf3aSMatthias Ringwald     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
284600d93d79Smatthias.ringwald 
28471b9cb13dSMatthias Ringwald     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
2848505f1c30SMatthias Ringwald     if ((code < 1) || (code == ECHO_RESPONSE) || (code > INFORMATION_RESPONSE)){
2849e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
285000d93d79Smatthias.ringwald         return;
285100d93d79Smatthias.ringwald     }
285200d93d79Smatthias.ringwald 
285300d93d79Smatthias.ringwald     // general commands without an assigned channel
285400d93d79Smatthias.ringwald     switch(code) {
285500d93d79Smatthias.ringwald 
28560493bf3aSMatthias Ringwald         case CONNECTION_REQUEST:
28570493bf3aSMatthias Ringwald             if (cmd_len == 4){
2858f8fbdce0SMatthias Ringwald                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2859f8fbdce0SMatthias Ringwald                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
286000d93d79Smatthias.ringwald                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
28610493bf3aSMatthias Ringwald             } else {
28620493bf3aSMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
286300d93d79Smatthias.ringwald             }
28640493bf3aSMatthias Ringwald             return;
286500d93d79Smatthias.ringwald 
28662b360848Smatthias.ringwald         case ECHO_REQUEST:
2867e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
28682b83fb7dSmatthias.ringwald             return;
286900d93d79Smatthias.ringwald 
28700493bf3aSMatthias Ringwald         case INFORMATION_REQUEST:
28710493bf3aSMatthias Ringwald             if (cmd_len == 2) {
28723e64cb44SMatthias Ringwald                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
28733e64cb44SMatthias Ringwald                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
28740493bf3aSMatthias Ringwald             } else {
28750493bf3aSMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
287600d93d79Smatthias.ringwald             }
28770493bf3aSMatthias Ringwald             return;
287800d93d79Smatthias.ringwald 
28791b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
28801b9cb13dSMatthias Ringwald         case INFORMATION_RESPONSE: {
28811b9cb13dSMatthias Ringwald             hci_connection_t * connection = hci_connection_for_handle(handle);
28821b9cb13dSMatthias Ringwald             if (!connection) return;
28830defadfbSMatthias Ringwald             if (connection->l2cap_state.information_state != L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE) return;
28840defadfbSMatthias Ringwald 
28850defadfbSMatthias Ringwald             // get extended features from response if valid
28860defadfbSMatthias Ringwald             connection->l2cap_state.extended_feature_mask = 0;
28870defadfbSMatthias Ringwald             if (cmd_len >= 6) {
28881b9cb13dSMatthias Ringwald                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
28891b9cb13dSMatthias Ringwald                 uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
28900defadfbSMatthias Ringwald                 if (result == 0 && info_type == L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) {
28911b9cb13dSMatthias Ringwald                     connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
28920defadfbSMatthias Ringwald                 }
28930defadfbSMatthias Ringwald             }
28940defadfbSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
2895543b84e4SMatthias Ringwald             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
28960defadfbSMatthias Ringwald 
28971b9cb13dSMatthias Ringwald             // trigger connection request
28981b9cb13dSMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
28991b9cb13dSMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
29001b9cb13dSMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2901fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2902543b84e4SMatthias Ringwald                 if (channel->con_handle != handle) continue;
2903f8ecb114SMatthias Ringwald 
2904f8ecb114SMatthias Ringwald                 // incoming connection: ask user for channel configuration, esp. if ertm will be mandatory
2905f8ecb114SMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
2906f8ecb114SMatthias Ringwald                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2907f8ecb114SMatthias Ringwald                     l2cap_emit_incoming_connection(channel);
2908f8ecb114SMatthias Ringwald                     continue;
2909f8ecb114SMatthias Ringwald                 }
2910f8ecb114SMatthias Ringwald 
2911f8ecb114SMatthias Ringwald                 // outgoing connection
2912f8ecb114SMatthias Ringwald                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
2913f8ecb114SMatthias Ringwald 
2914dae3b2abSMatthias Ringwald                     // if ERTM was requested, but is not listed in extended feature mask:
2915543b84e4SMatthias Ringwald                     if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2916dae3b2abSMatthias Ringwald 
2917f073f086SMatthias Ringwald                         if (channel->ertm_mandatory){
2918dae3b2abSMatthias Ringwald                             // bail if ERTM is mandatory
2919543b84e4SMatthias Ringwald                             channel->state = L2CAP_STATE_CLOSED;
2920543b84e4SMatthias Ringwald                             // map l2cap connection response result to BTstack status enumeration
292166a72640SMatthias Ringwald                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
2922543b84e4SMatthias Ringwald                             // discard channel
2923543b84e4SMatthias Ringwald                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2924c45d6b2cSMatthias Ringwald                             l2cap_free_channel_entry(channel);
2925543b84e4SMatthias Ringwald                             continue;
2926dae3b2abSMatthias Ringwald 
2927f073f086SMatthias Ringwald                         } else {
2928f073f086SMatthias Ringwald                             // fallback to Basic mode
292966a72640SMatthias Ringwald                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
2930f073f086SMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2931f073f086SMatthias Ringwald                         }
2932dae3b2abSMatthias Ringwald                     }
2933f8ecb114SMatthias Ringwald 
293452606043SMatthias Ringwald                     // respond to connection request
2935f8ecb114SMatthias Ringwald                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
2936f8ecb114SMatthias Ringwald                     continue;
293752606043SMatthias Ringwald                 }
29381b9cb13dSMatthias Ringwald             }
29391b9cb13dSMatthias Ringwald             return;
29401b9cb13dSMatthias Ringwald         }
29411b9cb13dSMatthias Ringwald #endif
29421b9cb13dSMatthias Ringwald 
294300d93d79Smatthias.ringwald         default:
294400d93d79Smatthias.ringwald             break;
294500d93d79Smatthias.ringwald     }
294600d93d79Smatthias.ringwald 
294700d93d79Smatthias.ringwald     // Get potential destination CID
2948f8fbdce0SMatthias Ringwald     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
294900d93d79Smatthias.ringwald 
295000d93d79Smatthias.ringwald     // Find channel for this sig_id and connection handle
2951665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2952665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2953665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2954fad84cafSMatthias Ringwald         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2955fc64f94aSMatthias Ringwald         if (channel->con_handle != handle) continue;
295600d93d79Smatthias.ringwald         if (code & 1) {
2957b1988dceSmatthias.ringwald             // match odd commands (responses) by previous signaling identifier
2958b1988dceSmatthias.ringwald             if (channel->local_sig_id == sig_id) {
295900d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
29604e32727eSmatthias.ringwald                 break;
296100d93d79Smatthias.ringwald             }
296200d93d79Smatthias.ringwald         } else {
2963b1988dceSmatthias.ringwald             // match even commands (requests) by local channel id
296400d93d79Smatthias.ringwald             if (channel->local_cid == dest_cid) {
296500d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
29664e32727eSmatthias.ringwald                 break;
296700d93d79Smatthias.ringwald             }
296800d93d79Smatthias.ringwald         }
296900d93d79Smatthias.ringwald     }
297000d93d79Smatthias.ringwald }
297109e9d05bSMatthias Ringwald #endif
297200d93d79Smatthias.ringwald 
2973e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
297409e9d05bSMatthias Ringwald 
297509e9d05bSMatthias Ringwald static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
297609e9d05bSMatthias Ringwald     uint8_t event[6];
297709e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
297809e9d05bSMatthias Ringwald     event[1] = 4;
297909e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
298009e9d05bSMatthias Ringwald     little_endian_store_16(event, 4, result);
298109e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
298209e9d05bSMatthias Ringwald     if (!l2cap_event_packet_handler) return;
298309e9d05bSMatthias Ringwald     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
298409e9d05bSMatthias Ringwald }
298509e9d05bSMatthias Ringwald 
2986c48b2a2cSMatthias Ringwald // @returns valid
2987c48b2a2cSMatthias Ringwald static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
2988e7d0c9aaSMatthias Ringwald     hci_connection_t * connection;
2989c48b2a2cSMatthias Ringwald     uint16_t result;
2990f299206dSMatthias Ringwald     uint8_t  event[12];
299183fd9c76SMatthias Ringwald 
2992cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2993a3dc965aSMatthias Ringwald     btstack_linked_list_iterator_t it;
2994a3dc965aSMatthias Ringwald     l2cap_channel_t * channel;
2995a3dc965aSMatthias Ringwald     uint16_t local_cid;
299683fd9c76SMatthias Ringwald     uint16_t le_psm;
299763f0ac45SMatthias Ringwald     uint16_t new_credits;
299863f0ac45SMatthias Ringwald     uint16_t credits_before;
2999e7d0c9aaSMatthias Ringwald     l2cap_service_t * service;
300011cae19eSMilanka Ringwald     uint16_t source_cid;
300183fd9c76SMatthias Ringwald #endif
300200d93d79Smatthias.ringwald 
30031b8b8d05SMatthias Ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3004adcfabadSMatthias Ringwald     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
30051fcd10b7SMatthias Ringwald     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
30061b8b8d05SMatthias Ringwald 
30071b8b8d05SMatthias Ringwald     switch (code){
300800d93d79Smatthias.ringwald 
3009c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_REQUEST:
3010adcfabadSMatthias Ringwald             // check size
30111fcd10b7SMatthias Ringwald             if (len < 8) return 0;
3012e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
3013da886c03S[email protected]             if (connection){
30146d91fb6cSMatthias Ringwald                 if (connection->role != HCI_ROLE_MASTER){
30156d91fb6cSMatthias Ringwald                     // reject command without notifying upper layer when not in master role
3016c48b2a2cSMatthias Ringwald                     return 0;
30176d91fb6cSMatthias Ringwald                 }
3018a4c06b28SMatthias Ringwald                 le_connection_parameter_range_t existing_range;
30194ced4e8cSMatthias Ringwald                 gap_get_connection_parameter_range(&existing_range);
3020d5e694a3SMatthias Ringwald                 uint16_t le_conn_interval_min   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3021d5e694a3SMatthias Ringwald                 uint16_t le_conn_interval_max   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3022d5e694a3SMatthias Ringwald                 uint16_t le_conn_latency        = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3023d5e694a3SMatthias Ringwald                 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
3024da886c03S[email protected] 
302573cd8a2aSMatthias 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);
3026da886c03S[email protected]                 if (update_parameter){
3027da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
3028da886c03S[email protected]                     connection->le_conn_interval_min = le_conn_interval_min;
3029da886c03S[email protected]                     connection->le_conn_interval_max = le_conn_interval_max;
3030da886c03S[email protected]                     connection->le_conn_latency = le_conn_latency;
3031da886c03S[email protected]                     connection->le_supervision_timeout = le_supervision_timeout;
3032da886c03S[email protected]                 } else {
3033da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
3034da886c03S[email protected]                 }
3035c48b2a2cSMatthias Ringwald                 connection->le_con_param_update_identifier = sig_id;
3036da886c03S[email protected]             }
3037da886c03S[email protected] 
303833c40538SMatthias Ringwald             if (!l2cap_event_packet_handler) break;
3039c48b2a2cSMatthias Ringwald 
3040c48b2a2cSMatthias Ringwald             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
3041c48b2a2cSMatthias Ringwald             event[1] = 8;
3042f299206dSMatthias Ringwald             little_endian_store_16(event, 2, handle);
3043*6535961aSMatthias Ringwald             (void)memcpy(&event[4], &command[4], 8);
3044c48b2a2cSMatthias Ringwald             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
304533c40538SMatthias Ringwald             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
3046ccf076adS[email protected]             break;
3047c48b2a2cSMatthias Ringwald 
30481fcd10b7SMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
30491fcd10b7SMatthias Ringwald             // check size
30501fcd10b7SMatthias Ringwald             if (len < 2) return 0;
30511fcd10b7SMatthias Ringwald             result = little_endian_read_16(command, 4);
30521fcd10b7SMatthias Ringwald             l2cap_emit_connection_parameter_update_response(handle, result);
30531fcd10b7SMatthias Ringwald             break;
30541fcd10b7SMatthias Ringwald 
3055a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
3056a3dc965aSMatthias Ringwald 
305763f0ac45SMatthias Ringwald         case COMMAND_REJECT:
305863f0ac45SMatthias Ringwald             // Find channel for this sig_id and connection handle
305963f0ac45SMatthias Ringwald             channel = NULL;
3060421cb104SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
306163f0ac45SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
306263f0ac45SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3063fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
306463f0ac45SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
306563f0ac45SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
306663f0ac45SMatthias Ringwald                 channel = a_channel;
306763f0ac45SMatthias Ringwald                 break;
306863f0ac45SMatthias Ringwald             }
306963f0ac45SMatthias Ringwald             if (!channel) break;
307063f0ac45SMatthias Ringwald 
307163f0ac45SMatthias Ringwald             // if received while waiting for le connection response, assume legacy device
307263f0ac45SMatthias Ringwald             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
307363f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
307463f0ac45SMatthias Ringwald                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
307544276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0x0002);
307663f0ac45SMatthias Ringwald 
307763f0ac45SMatthias Ringwald                 // discard channel
3078421cb104SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3079c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
308063f0ac45SMatthias Ringwald                 break;
308163f0ac45SMatthias Ringwald             }
308263f0ac45SMatthias Ringwald             break;
308363f0ac45SMatthias Ringwald 
3084e7d0c9aaSMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_REQUEST:
3085adcfabadSMatthias Ringwald             // check size
3086adcfabadSMatthias Ringwald             if (len < 10) return 0;
3087e7d0c9aaSMatthias Ringwald 
3088e7d0c9aaSMatthias Ringwald             // get hci connection, bail if not found (must not happen)
3089e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
3090e7d0c9aaSMatthias Ringwald             if (!connection) return 0;
3091e7d0c9aaSMatthias Ringwald 
3092e7d0c9aaSMatthias Ringwald             // check if service registered
3093e7d0c9aaSMatthias Ringwald             le_psm  = little_endian_read_16(command, 4);
3094e7d0c9aaSMatthias Ringwald             service = l2cap_le_get_service(le_psm);
309511cae19eSMilanka Ringwald             source_cid = little_endian_read_16(command, 6);
3096e7d0c9aaSMatthias Ringwald 
3097e7d0c9aaSMatthias Ringwald             if (service){
3098e7d0c9aaSMatthias Ringwald                 if (source_cid < 0x40){
3099e7d0c9aaSMatthias Ringwald                     // 0x0009 Connection refused - Invalid Source CID
3100e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
3101e7d0c9aaSMatthias Ringwald                     return 1;
3102e7d0c9aaSMatthias Ringwald                 }
3103e7d0c9aaSMatthias Ringwald 
3104e7d0c9aaSMatthias Ringwald                 // go through list of channels for this ACL connection and check if we get a match
3105421cb104SMatthias Ringwald                 btstack_linked_list_iterator_init(&it, &l2cap_channels);
3106e7d0c9aaSMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&it)){
31071b8b8d05SMatthias Ringwald                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3108fad84cafSMatthias Ringwald                     if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
31091b8b8d05SMatthias Ringwald                     if (a_channel->con_handle != handle) continue;
31101b8b8d05SMatthias Ringwald                     if (a_channel->remote_cid != source_cid) continue;
3111e7d0c9aaSMatthias Ringwald                     // 0x000a Connection refused - Source CID already allocated
3112e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
3113e7d0c9aaSMatthias Ringwald                     return 1;
3114e7d0c9aaSMatthias Ringwald                 }
3115e7d0c9aaSMatthias Ringwald 
311683fd9c76SMatthias Ringwald                 // security: check encryption
311783fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_2){
31189c6e867eSMatthias Ringwald                     if (gap_encryption_key_size(handle) == 0){
311983fd9c76SMatthias Ringwald                         // 0x0008 Connection refused - insufficient encryption
3120e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
312183fd9c76SMatthias Ringwald                         return 1;
312283fd9c76SMatthias Ringwald                     }
312383fd9c76SMatthias Ringwald                     // anything less than 16 byte key size is insufficient
31249c6e867eSMatthias Ringwald                     if (gap_encryption_key_size(handle) < 16){
312583fd9c76SMatthias Ringwald                         // 0x0007 Connection refused – insufficient encryption key size
3126e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
312783fd9c76SMatthias Ringwald                         return 1;
312883fd9c76SMatthias Ringwald                     }
312983fd9c76SMatthias Ringwald                 }
313083fd9c76SMatthias Ringwald 
313183fd9c76SMatthias Ringwald                 // security: check authencation
313283fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_3){
31339c6e867eSMatthias Ringwald                     if (!gap_authenticated(handle)){
313483fd9c76SMatthias Ringwald                         // 0x0005 Connection refused – insufficient authentication
3135e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
313683fd9c76SMatthias Ringwald                         return 1;
313783fd9c76SMatthias Ringwald                     }
313883fd9c76SMatthias Ringwald                 }
313983fd9c76SMatthias Ringwald 
314083fd9c76SMatthias Ringwald                 // security: check authorization
314183fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_4){
31429c6e867eSMatthias Ringwald                     if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
314383fd9c76SMatthias Ringwald                         // 0x0006 Connection refused – insufficient authorization
3144e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
314583fd9c76SMatthias Ringwald                         return 1;
314683fd9c76SMatthias Ringwald                     }
314783fd9c76SMatthias Ringwald                 }
3148e7d0c9aaSMatthias Ringwald 
3149e7d0c9aaSMatthias Ringwald                 // allocate channel
31505d18f623SMatthias Ringwald                 channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL, connection->address,
3151e7d0c9aaSMatthias Ringwald                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
3152e7d0c9aaSMatthias Ringwald                 if (!channel){
3153e7d0c9aaSMatthias Ringwald                     // 0x0004 Connection refused – no resources available
3154e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
3155e7d0c9aaSMatthias Ringwald                     return 1;
3156e7d0c9aaSMatthias Ringwald                 }
3157e7d0c9aaSMatthias Ringwald 
3158e7d0c9aaSMatthias Ringwald                 channel->con_handle = handle;
3159e7d0c9aaSMatthias Ringwald                 channel->remote_cid = source_cid;
3160e7d0c9aaSMatthias Ringwald                 channel->remote_sig_id = sig_id;
31617f107edaSMatthias Ringwald                 channel->remote_mtu = little_endian_read_16(command, 8);
31627f107edaSMatthias Ringwald                 channel->remote_mps = little_endian_read_16(command, 10);
31637f107edaSMatthias Ringwald                 channel->credits_outgoing = little_endian_read_16(command, 12);
3164e7d0c9aaSMatthias Ringwald 
3165e7d0c9aaSMatthias Ringwald                 // set initial state
3166e7d0c9aaSMatthias Ringwald                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
3167c99bb618SMatthias Ringwald                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
3168e7d0c9aaSMatthias Ringwald 
3169e7d0c9aaSMatthias Ringwald                 // add to connections list
3170421cb104SMatthias Ringwald                 btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
3171e7d0c9aaSMatthias Ringwald 
3172e7d0c9aaSMatthias Ringwald                 // post connection request event
317344276248SMatthias Ringwald                 l2cap_emit_le_incoming_connection(channel);
3174e7d0c9aaSMatthias Ringwald 
3175e7d0c9aaSMatthias Ringwald             } else {
3176e7d0c9aaSMatthias Ringwald                 // Connection refused – LE_PSM not supported
3177e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
3178e7d0c9aaSMatthias Ringwald             }
3179e7d0c9aaSMatthias Ringwald             break;
31801b8b8d05SMatthias Ringwald 
31811b8b8d05SMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
3182adcfabadSMatthias Ringwald             // check size
3183adcfabadSMatthias Ringwald             if (len < 10) return 0;
3184adcfabadSMatthias Ringwald 
31851b8b8d05SMatthias Ringwald             // Find channel for this sig_id and connection handle
31861b8b8d05SMatthias Ringwald             channel = NULL;
3187421cb104SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
31881b8b8d05SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
31891b8b8d05SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3190fad84cafSMatthias Ringwald                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
31911b8b8d05SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
31921b8b8d05SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
31931b8b8d05SMatthias Ringwald                 channel = a_channel;
31941b8b8d05SMatthias Ringwald                 break;
31951b8b8d05SMatthias Ringwald             }
31961b8b8d05SMatthias Ringwald             if (!channel) break;
31971b8b8d05SMatthias Ringwald 
31981b8b8d05SMatthias Ringwald             // cid + 0
31991b8b8d05SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
32001b8b8d05SMatthias Ringwald             if (result){
32011b8b8d05SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
32021b8b8d05SMatthias Ringwald                 // map l2cap connection response result to BTstack status enumeration
320344276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, result);
32041b8b8d05SMatthias Ringwald 
32051b8b8d05SMatthias Ringwald                 // discard channel
3206421cb104SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3207c45d6b2cSMatthias Ringwald                 l2cap_free_channel_entry(channel);
32081b8b8d05SMatthias Ringwald                 break;
32091b8b8d05SMatthias Ringwald             }
32101b8b8d05SMatthias Ringwald 
32111b8b8d05SMatthias Ringwald             // success
32121b8b8d05SMatthias Ringwald             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
32131b8b8d05SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
32141b8b8d05SMatthias Ringwald             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
32151b8b8d05SMatthias Ringwald             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
32161b8b8d05SMatthias Ringwald             channel->state = L2CAP_STATE_OPEN;
321744276248SMatthias Ringwald             l2cap_emit_le_channel_opened(channel, result);
32181b8b8d05SMatthias Ringwald             break;
32191b8b8d05SMatthias Ringwald 
322085aeef60SMatthias Ringwald         case LE_FLOW_CONTROL_CREDIT:
3221adcfabadSMatthias Ringwald             // check size
3222adcfabadSMatthias Ringwald             if (len < 4) return 0;
3223adcfabadSMatthias Ringwald 
322485aeef60SMatthias Ringwald             // find channel
322585aeef60SMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3226421cb104SMatthias Ringwald             channel = l2cap_get_channel_for_local_cid(local_cid);
322763f0ac45SMatthias Ringwald             if (!channel) {
322863f0ac45SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
322963f0ac45SMatthias Ringwald                 break;
323063f0ac45SMatthias Ringwald             }
323163f0ac45SMatthias Ringwald             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
323263f0ac45SMatthias Ringwald             credits_before = channel->credits_outgoing;
323363f0ac45SMatthias Ringwald             channel->credits_outgoing += new_credits;
323463f0ac45SMatthias Ringwald             // check for credit overrun
323563f0ac45SMatthias Ringwald             if (credits_before > channel->credits_outgoing){
323663f0ac45SMatthias Ringwald                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
323763f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
323863f0ac45SMatthias Ringwald                 break;
323963f0ac45SMatthias Ringwald             }
324063f0ac45SMatthias Ringwald             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
324185aeef60SMatthias Ringwald             break;
324285aeef60SMatthias Ringwald 
3243828a7f7aSMatthias Ringwald         case DISCONNECTION_REQUEST:
3244adcfabadSMatthias Ringwald 
3245adcfabadSMatthias Ringwald             // check size
3246adcfabadSMatthias Ringwald             if (len < 4) return 0;
3247adcfabadSMatthias Ringwald 
3248828a7f7aSMatthias Ringwald             // find channel
3249828a7f7aSMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3250421cb104SMatthias Ringwald             channel = l2cap_get_channel_for_local_cid(local_cid);
325163f34e00SMatthias Ringwald             if (!channel) {
325263f34e00SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
325363f34e00SMatthias Ringwald                 break;
325463f34e00SMatthias Ringwald             }
3255828a7f7aSMatthias Ringwald             channel->remote_sig_id = sig_id;
3256828a7f7aSMatthias Ringwald             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
3257828a7f7aSMatthias Ringwald             break;
3258828a7f7aSMatthias Ringwald 
3259a3dc965aSMatthias Ringwald #endif
3260a3dc965aSMatthias Ringwald 
326163f0ac45SMatthias Ringwald         case DISCONNECTION_RESPONSE:
326263f0ac45SMatthias Ringwald             break;
326363f0ac45SMatthias Ringwald 
3264c48b2a2cSMatthias Ringwald         default:
3265c48b2a2cSMatthias Ringwald             // command unknown -> reject command
3266c48b2a2cSMatthias Ringwald             return 0;
3267ccf076adS[email protected]     }
3268c48b2a2cSMatthias Ringwald     return 1;
3269c48b2a2cSMatthias Ringwald }
3270e7d0c9aaSMatthias Ringwald #endif
3271c48b2a2cSMatthias Ringwald 
3272bb0a72a6SMatthias Ringwald static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3273bb0a72a6SMatthias Ringwald #ifdef ENABLE_CLASSIC
327409e9d05bSMatthias Ringwald     l2cap_channel_t * l2cap_channel;
3275fad84cafSMatthias Ringwald     l2cap_fixed_channel_t * l2cap_fixed_channel;
327609e9d05bSMatthias Ringwald 
3277c48b2a2cSMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3278c48b2a2cSMatthias Ringwald     switch (channel_id) {
3279c48b2a2cSMatthias Ringwald 
3280c48b2a2cSMatthias Ringwald         case L2CAP_CID_SIGNALING: {
3281eaeabfdaSMatthias Ringwald             uint32_t command_offset = 8;
3282eaeabfdaSMatthias Ringwald             while ((command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET) < size) {
3283ed2ed8e1SMatthias Ringwald                 // assert signaling command is fully inside packet
3284ed2ed8e1SMatthias Ringwald                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3285eaeabfdaSMatthias Ringwald                 uint32_t next_command_offset = command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
3286ed2ed8e1SMatthias Ringwald                 if (next_command_offset > size){
3287ed2ed8e1SMatthias Ringwald                     log_error("l2cap signaling command len invalid -> drop");
3288ed2ed8e1SMatthias Ringwald                     break;
3289ed2ed8e1SMatthias Ringwald                 }
3290ed2ed8e1SMatthias Ringwald                 // handle signaling command
3291c48b2a2cSMatthias Ringwald                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
3292ed2ed8e1SMatthias Ringwald                 // go to next command
3293eaeabfdaSMatthias Ringwald                 command_offset = next_command_offset;
3294c48b2a2cSMatthias Ringwald             }
3295c48b2a2cSMatthias Ringwald             break;
3296c48b2a2cSMatthias Ringwald         }
3297c48b2a2cSMatthias Ringwald         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
3298fad84cafSMatthias Ringwald             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL);
3299fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel) break;
3300fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel->packet_handler) break;
3301fad84cafSMatthias Ringwald             (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3302c48b2a2cSMatthias Ringwald             break;
33031bbc0b23S[email protected] 
330409e9d05bSMatthias Ringwald         default:
330500d93d79Smatthias.ringwald             // Find channel for this channel_id and connection handle
330664e11ca9SMatthias Ringwald             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
3307d1fd2a88SMatthias Ringwald             if (l2cap_channel) {
330827e0774aSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
330927e0774aSMatthias Ringwald                 if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
331027e0774aSMatthias Ringwald 
33116574158aSMatthias Ringwald                     int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
331207c7de86SMatthias Ringwald 
33136574158aSMatthias Ringwald                     // assert control + FCS fields are inside
33146574158aSMatthias Ringwald                     if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) break;
33156574158aSMatthias Ringwald 
33166574158aSMatthias Ringwald                     if (l2cap_channel->fcs_option){
3317fcb125edSMatthias Ringwald                         // verify FCS (required if one side requested it)
331827e0774aSMatthias Ringwald                         uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
331927e0774aSMatthias Ringwald                         uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
3320e288be62SMatthias Ringwald 
3321e288be62SMatthias Ringwald #ifdef L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL
3322e288be62SMatthias Ringwald                         // simulate fcs error
3323e288be62SMatthias Ringwald                         static int counter = 0;
3324e288be62SMatthias Ringwald                         if (++counter == L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL) {
3325e288be62SMatthias Ringwald                             log_info("Simulate fcs error");
3326e288be62SMatthias Ringwald                             fcs_calculated++;
3327e288be62SMatthias Ringwald                             counter = 0;
3328e288be62SMatthias Ringwald                         }
3329e288be62SMatthias Ringwald #endif
3330e288be62SMatthias Ringwald 
33316574158aSMatthias Ringwald                         if (fcs_calculated == fcs_packet){
33326574158aSMatthias Ringwald                             log_info("Packet FCS 0x%04x verified", fcs_packet);
33336574158aSMatthias Ringwald                         } else {
333427e0774aSMatthias Ringwald                             log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
3335ef2faf56SMatthias Ringwald                             // ERTM State Machine in Bluetooth Spec does not handle 'I-Frame with invalid FCS'
333627e0774aSMatthias Ringwald                             break;
333727e0774aSMatthias Ringwald                         }
33386574158aSMatthias Ringwald                     }
333927e0774aSMatthias Ringwald 
334027e0774aSMatthias Ringwald                     // switch on packet type
334127e0774aSMatthias Ringwald                     uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
334238f62777SMatthias Ringwald                     uint8_t  req_seq = (control >> 8) & 0x3f;
33432bea1b8dSMatthias Ringwald                     int final = (control >> 7) & 0x01;
334427e0774aSMatthias Ringwald                     if (control & 1){
334527e0774aSMatthias Ringwald                         // S-Frame
334678cd8a22SMatthias Ringwald                         int poll  = (control >> 4) & 0x01;
3347bdbe2e49SMatthias Ringwald                         l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
33489ffcbce4SMatthias Ringwald                         log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
33497b7901d8SMatthias Ringwald                         l2cap_ertm_tx_packet_state_t * tx_state;
3350bdbe2e49SMatthias Ringwald                         switch (s){
3351bdbe2e49SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
33529ffcbce4SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
33531e1a46bbSMatthias Ringwald                                 l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
33543233d8abSMatthias Ringwald                                 if (poll && final){
33553233d8abSMatthias Ringwald                                     // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
33563233d8abSMatthias Ringwald                                     log_error("P=F=1 in S-Frame");
33573233d8abSMatthias Ringwald                                     break;
33583233d8abSMatthias Ringwald                                 }
335978cd8a22SMatthias Ringwald                                 if (poll){
3360f85ade6bSMatthias Ringwald                                     // check if we did request selective retransmission before <==> we have stored SDU segments
3361f85ade6bSMatthias Ringwald                                     int i;
3362f85ade6bSMatthias Ringwald                                     int num_stored_out_of_order_packets = 0;
3363f85ade6bSMatthias Ringwald                                     for (i=0;i<l2cap_channel->num_rx_buffers;i++){
3364f85ade6bSMatthias Ringwald                                         int index = l2cap_channel->rx_store_index + i;
3365f85ade6bSMatthias Ringwald                                         if (index >= l2cap_channel->num_rx_buffers){
3366f85ade6bSMatthias Ringwald                                             index -= l2cap_channel->num_rx_buffers;
3367f85ade6bSMatthias Ringwald                                         }
3368f85ade6bSMatthias Ringwald                                         l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3369f85ade6bSMatthias Ringwald                                         if (!rx_state->valid) continue;
3370f85ade6bSMatthias Ringwald                                         num_stored_out_of_order_packets++;
3371f85ade6bSMatthias Ringwald                                     }
3372f85ade6bSMatthias Ringwald                                     if (num_stored_out_of_order_packets){
3373f85ade6bSMatthias Ringwald                                         l2cap_channel->send_supervisor_frame_selective_reject = 1;
3374f85ade6bSMatthias Ringwald                                     } else {
3375d2afdd38SMatthias Ringwald                                         l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
337678cd8a22SMatthias Ringwald                                     }
3377f85ade6bSMatthias Ringwald                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
3378f85ade6bSMatthias Ringwald                                 }
33793233d8abSMatthias Ringwald                                 if (final){
3380550189ffSMatthias Ringwald                                     // Stop-MonitorTimer
3381550189ffSMatthias Ringwald                                     l2cap_ertm_stop_monitor_timer(l2cap_channel);
3382550189ffSMatthias Ringwald                                     // If UnackedFrames > 0 then Start-RetransTimer
338394301352SMatthias Ringwald                                     if (l2cap_channel->unacked_frames){
3384550189ffSMatthias Ringwald                                         l2cap_ertm_start_retransmission_timer(l2cap_channel);
3385550189ffSMatthias Ringwald                                     }
33863233d8abSMatthias Ringwald                                     // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3387ef2faf56SMatthias Ringwald                                     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
33883233d8abSMatthias Ringwald                                 }
3389bdbe2e49SMatthias Ringwald                                 break;
33909ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
33919ffcbce4SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
33921e1a46bbSMatthias Ringwald                                 l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3393600cf12dSMatthias Ringwald                                 // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
3394ef2faf56SMatthias Ringwald                                 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
33959ffcbce4SMatthias Ringwald                                 break;
33969ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
33979ffcbce4SMatthias Ringwald                                 log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
33989ffcbce4SMatthias Ringwald                                 break;
33999ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
34007b7901d8SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
34017b7901d8SMatthias Ringwald                                 if (poll){
34021e1a46bbSMatthias Ringwald                                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
34037b7901d8SMatthias Ringwald                                 }
34047b7901d8SMatthias Ringwald                                 // find requested i-frame
34057b7901d8SMatthias Ringwald                                 tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
34067b7901d8SMatthias Ringwald                                 if (tx_state){
34077b7901d8SMatthias Ringwald                                     log_info("Retransmission for tx_seq %u requested", req_seq);
3408d2afdd38SMatthias Ringwald                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
34097b7901d8SMatthias Ringwald                                     tx_state->retransmission_requested = 1;
34107b7901d8SMatthias Ringwald                                     l2cap_channel->srej_active = 1;
34117b7901d8SMatthias Ringwald                                 }
34129ffcbce4SMatthias Ringwald                                 break;
3413bdbe2e49SMatthias Ringwald                             default:
3414bdbe2e49SMatthias Ringwald                                 break;
3415bdbe2e49SMatthias Ringwald                         }
341627e0774aSMatthias Ringwald                         break;
341727e0774aSMatthias Ringwald                     } else {
341827e0774aSMatthias Ringwald                         // I-Frame
341927e0774aSMatthias Ringwald                         // get control
342027e0774aSMatthias Ringwald                         l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
342138f62777SMatthias Ringwald                         uint8_t tx_seq = (control >> 1) & 0x3f;
342238f62777SMatthias Ringwald                         log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
3423e8e9809fSMatthias Ringwald                         log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
342438f62777SMatthias Ringwald                         log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
34251e1a46bbSMatthias Ringwald                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
342611b576c5SMatthias Ringwald                         if (final){
342711b576c5SMatthias Ringwald                             // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3428ef2faf56SMatthias Ringwald                             l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
342911b576c5SMatthias Ringwald                         }
343007c7de86SMatthias Ringwald 
343107c7de86SMatthias Ringwald                         // get SDU
3432826c39d0SMatthias Ringwald                         const uint8_t * payload_data = &packet[COMPLETE_L2CAP_HEADER+2];
3433826c39d0SMatthias Ringwald                         uint16_t        payload_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
343407c7de86SMatthias Ringwald 
343507c7de86SMatthias Ringwald                         // assert SDU size is smaller or equal to our buffers
3436826c39d0SMatthias Ringwald                         uint16_t max_payload_size = 0;
3437826c39d0SMatthias Ringwald                         switch (sar){
3438826c39d0SMatthias Ringwald                             case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
3439826c39d0SMatthias Ringwald                             case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
3440826c39d0SMatthias Ringwald                                 // SDU Length + MPS
3441826c39d0SMatthias Ringwald                                 max_payload_size = l2cap_channel->local_mps + 2;
3442826c39d0SMatthias Ringwald                                 break;
3443826c39d0SMatthias Ringwald                             case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
3444826c39d0SMatthias Ringwald                             case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
3445826c39d0SMatthias Ringwald                                 max_payload_size = l2cap_channel->local_mps;
3446826c39d0SMatthias Ringwald                                 break;
3447826c39d0SMatthias Ringwald                         }
3448826c39d0SMatthias Ringwald                         if (payload_len > max_payload_size){
3449826c39d0SMatthias Ringwald                             log_info("payload len %u > max payload %u -> drop packet", payload_len, max_payload_size);
3450826c39d0SMatthias Ringwald                             break;
3451826c39d0SMatthias Ringwald                         }
345207c7de86SMatthias Ringwald 
345338f62777SMatthias Ringwald                         // check ordering
345438f62777SMatthias Ringwald                         if (l2cap_channel->expected_tx_seq == tx_seq){
345538f62777SMatthias Ringwald                             log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
345638f62777SMatthias Ringwald                             l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3457f85ade6bSMatthias Ringwald                             l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3458d48432d4SMatthias Ringwald 
3459e32be409SMatthias Ringwald                             // process SDU
3460826c39d0SMatthias Ringwald                             l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, payload_data, payload_len);
3461d48432d4SMatthias Ringwald 
346270734707SMatthias Ringwald                             // process stored segments
346370734707SMatthias Ringwald                             while (1){
346470734707SMatthias Ringwald                                 int index = l2cap_channel->rx_store_index;
346570734707SMatthias Ringwald                                 l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
346670734707SMatthias Ringwald                                 if (!rx_state->valid) break;
3467f85ade6bSMatthias Ringwald 
3468f85ade6bSMatthias Ringwald                                 log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
3469f85ade6bSMatthias Ringwald                                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3470f85ade6bSMatthias Ringwald                                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3471f85ade6bSMatthias Ringwald 
347270734707SMatthias Ringwald                                 rx_state->valid = 0;
347370734707SMatthias Ringwald                                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
3474f85ade6bSMatthias Ringwald 
3475f85ade6bSMatthias Ringwald                                 // update rx store index
347670734707SMatthias Ringwald                                 index++;
347770734707SMatthias Ringwald                                 if (index >= l2cap_channel->num_rx_buffers){
347870734707SMatthias Ringwald                                     index = 0;
347970734707SMatthias Ringwald                                 }
348070734707SMatthias Ringwald                                 l2cap_channel->rx_store_index = index;
348170734707SMatthias Ringwald                             }
348270734707SMatthias Ringwald 
3483f85ade6bSMatthias Ringwald                             //
3484f85ade6bSMatthias Ringwald                             l2cap_channel->send_supervisor_frame_receiver_ready = 1;
3485f85ade6bSMatthias Ringwald 
3486c7309e8dSMatthias Ringwald                         } else {
3487df2191a7SMatthias Ringwald                             int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
3488df2191a7SMatthias Ringwald                             if (delta < 2){
348970734707SMatthias Ringwald                                 // store segment
3490826c39d0SMatthias Ringwald                                 l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, payload_data, payload_len);
349170734707SMatthias Ringwald 
3492df2191a7SMatthias Ringwald                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
3493df2191a7SMatthias Ringwald                                 l2cap_channel->send_supervisor_frame_selective_reject = 1;
3494df2191a7SMatthias Ringwald                             } else {
3495df2191a7SMatthias Ringwald                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
3496c7309e8dSMatthias Ringwald                                 l2cap_channel->send_supervisor_frame_reject = 1;
349727e0774aSMatthias Ringwald                             }
349838f62777SMatthias Ringwald                         }
3499df2191a7SMatthias Ringwald                     }
350027e0774aSMatthias Ringwald                     break;
350127e0774aSMatthias Ringwald                 }
350227e0774aSMatthias Ringwald #endif
35033d50b4baSMatthias Ringwald                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
350400d93d79Smatthias.ringwald             }
3505bb0a72a6SMatthias Ringwald             break;
3506bb0a72a6SMatthias Ringwald     }
3507bb0a72a6SMatthias Ringwald #else
3508bb0a72a6SMatthias Ringwald     UNUSED(handle); // ok: no code
3509bb0a72a6SMatthias Ringwald     UNUSED(packet); // ok: no code
3510bb0a72a6SMatthias Ringwald     UNUSED(size);   // ok: no code
351109e9d05bSMatthias Ringwald #endif
3512bb0a72a6SMatthias Ringwald }
3513bb0a72a6SMatthias Ringwald 
3514bb0a72a6SMatthias Ringwald static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3515bb0a72a6SMatthias Ringwald #ifdef ENABLE_BLE
3516bb0a72a6SMatthias Ringwald 
3517fad84cafSMatthias Ringwald     l2cap_fixed_channel_t * l2cap_fixed_channel;
3518fad84cafSMatthias Ringwald 
3519bb0a72a6SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
3520bb0a72a6SMatthias Ringwald     l2cap_channel_t * l2cap_channel;
3521bb0a72a6SMatthias Ringwald #endif
3522bb0a72a6SMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3523bb0a72a6SMatthias Ringwald     switch (channel_id) {
3524bb0a72a6SMatthias Ringwald 
3525bb0a72a6SMatthias Ringwald         case L2CAP_CID_SIGNALING_LE: {
3526bb0a72a6SMatthias Ringwald             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
3527adcfabadSMatthias Ringwald             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
3528505f1c30SMatthias Ringwald             if ((COMPLETE_L2CAP_HEADER + 4 + len) > size) break;
3529bb0a72a6SMatthias Ringwald             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
3530bb0a72a6SMatthias Ringwald             if (!valid){
3531bb0a72a6SMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3532bb0a72a6SMatthias Ringwald             }
3533bb0a72a6SMatthias Ringwald             break;
3534bb0a72a6SMatthias Ringwald         }
3535bb0a72a6SMatthias Ringwald 
3536bb0a72a6SMatthias Ringwald         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
3537fad84cafSMatthias Ringwald             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL);
3538fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel) break;
3539fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel->packet_handler) break;
3540fad84cafSMatthias Ringwald             (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3541bb0a72a6SMatthias Ringwald             break;
3542bb0a72a6SMatthias Ringwald 
3543bb0a72a6SMatthias Ringwald         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
3544fad84cafSMatthias Ringwald             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
3545fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel) break;
3546fad84cafSMatthias Ringwald             if (!l2cap_fixed_channel->packet_handler) break;
3547fad84cafSMatthias Ringwald             (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3548bb0a72a6SMatthias Ringwald             break;
3549bb0a72a6SMatthias Ringwald 
3550bb0a72a6SMatthias Ringwald         default:
3551bb0a72a6SMatthias Ringwald 
3552a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
3553421cb104SMatthias Ringwald             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
355464e11ca9SMatthias Ringwald             if (l2cap_channel) {
355585aeef60SMatthias Ringwald                 // credit counting
355685aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming == 0){
355785aeef60SMatthias Ringwald                     log_error("LE Data Channel packet received but no incoming credits");
355885aeef60SMatthias Ringwald                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
355985aeef60SMatthias Ringwald                     break;
356085aeef60SMatthias Ringwald                 }
356185aeef60SMatthias Ringwald                 l2cap_channel->credits_incoming--;
356285aeef60SMatthias Ringwald 
356385aeef60SMatthias Ringwald                 // automatic credits
3564c1ab6cc1SMatthias Ringwald                 if ((l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK) && l2cap_channel->automatic_credits){
356585aeef60SMatthias Ringwald                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
356685aeef60SMatthias Ringwald                 }
356785aeef60SMatthias Ringwald 
3568cd529728SMatthias Ringwald                 // first fragment
3569cd529728SMatthias Ringwald                 uint16_t pos = 0;
3570cd529728SMatthias Ringwald                 if (!l2cap_channel->receive_sdu_len){
3571bb98c113SMatthias Ringwald                     uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3572bb98c113SMatthias Ringwald                     if(sdu_len > l2cap_channel->local_mtu) break;   // SDU would be larger than our buffer
3573bb98c113SMatthias Ringwald                     l2cap_channel->receive_sdu_len = sdu_len;
3574cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_pos = 0;
3575cd529728SMatthias Ringwald                     pos  += 2;
3576cd529728SMatthias Ringwald                     size -= 2;
3577cd529728SMatthias Ringwald                 }
3578bb98c113SMatthias Ringwald                 uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
3579bb98c113SMatthias Ringwald                 uint16_t remaining_space = l2cap_channel->local_mtu - l2cap_channel->receive_sdu_pos;
3580bb98c113SMatthias Ringwald                 if (fragment_size > remaining_space) break;         // SDU would cause buffer overrun
3581*6535961aSMatthias Ringwald                 (void)memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos],
3582*6535961aSMatthias Ringwald                              &packet[COMPLETE_L2CAP_HEADER + pos],
3583*6535961aSMatthias Ringwald                              fragment_size);
3584cd529728SMatthias Ringwald                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
3585cd529728SMatthias Ringwald                 // done?
3586895ff4a5SMatthias Ringwald                 log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
3587cd529728SMatthias Ringwald                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
3588cd529728SMatthias Ringwald                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
3589cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = 0;
3590cd529728SMatthias Ringwald                 }
359163f0ac45SMatthias Ringwald             } else {
359263f0ac45SMatthias Ringwald                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
359364e11ca9SMatthias Ringwald             }
359464e11ca9SMatthias Ringwald #endif
35955652b5ffS[email protected]             break;
35965652b5ffS[email protected]     }
3597bb0a72a6SMatthias Ringwald #else
3598bb0a72a6SMatthias Ringwald     UNUSED(handle); // ok: no code
3599bb0a72a6SMatthias Ringwald     UNUSED(packet); // ok: no code
3600bb0a72a6SMatthias Ringwald     UNUSED(size);   // ok: no code
3601bb0a72a6SMatthias Ringwald #endif
3602bb0a72a6SMatthias Ringwald }
3603bb0a72a6SMatthias Ringwald 
3604bb0a72a6SMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
3605bb0a72a6SMatthias Ringwald     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
3606bb0a72a6SMatthias Ringwald     UNUSED(channel);        // ok: there is no channel
3607bb0a72a6SMatthias Ringwald 
3608adcfabadSMatthias Ringwald     // Assert full L2CAP header present
3609adcfabadSMatthias Ringwald     if (size < COMPLETE_L2CAP_HEADER) return;
3610adcfabadSMatthias Ringwald 
3611f16129ceSMatthias Ringwald     // Dispatch to Classic or LE handler (SCO packets are not dispatched to L2CAP)
3612bb0a72a6SMatthias Ringwald     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
3613bb0a72a6SMatthias Ringwald     hci_connection_t *conn = hci_connection_for_handle(handle);
3614bb0a72a6SMatthias Ringwald     if (!conn) return;
3615f16129ceSMatthias Ringwald     if (conn->address_type == BD_ADDR_TYPE_ACL){
3616bb0a72a6SMatthias Ringwald         l2cap_acl_classic_handler(handle, packet, size);
3617bb0a72a6SMatthias Ringwald     } else {
3618bb0a72a6SMatthias Ringwald         l2cap_acl_le_handler(handle, packet, size);
3619bb0a72a6SMatthias Ringwald     }
362000d93d79Smatthias.ringwald 
36211eb2563eS[email protected]     l2cap_run();
36222718e2e7Smatthias.ringwald }
362300d93d79Smatthias.ringwald 
362409e9d05bSMatthias Ringwald // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
362509e9d05bSMatthias Ringwald void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
3626fad84cafSMatthias Ringwald     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
3627fad84cafSMatthias Ringwald     if (!channel) return;
3628fad84cafSMatthias Ringwald     channel->packet_handler = the_packet_handler;
362909e9d05bSMatthias Ringwald }
363009e9d05bSMatthias Ringwald 
363109e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
363215ec09bbSmatthias.ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
363327a923d0Smatthias.ringwald void l2cap_finialize_channel_close(l2cap_channel_t * channel){
3634f62db1e3Smatthias.ringwald     channel->state = L2CAP_STATE_CLOSED;
363566a72640SMatthias Ringwald     l2cap_handle_channel_closed(channel);
3636f62db1e3Smatthias.ringwald     // discard channel
3637665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3638c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
3639c8e4258aSmatthias.ringwald }
364013aa3e4bSMatthias Ringwald #endif
36411e6aba47Smatthias.ringwald 
364213aa3e4bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
36438f2a52f4SMatthias Ringwald static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3644665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
3645665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, services);
3646665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
3647665d90f2SMatthias Ringwald         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
36489d9bbc01Smatthias.ringwald         if ( service->psm == psm){
36499d9bbc01Smatthias.ringwald             return service;
36509d9bbc01Smatthias.ringwald         };
36519d9bbc01Smatthias.ringwald     }
36529d9bbc01Smatthias.ringwald     return NULL;
36539d9bbc01Smatthias.ringwald }
365413aa3e4bSMatthias Ringwald #endif
36559d9bbc01Smatthias.ringwald 
365613aa3e4bSMatthias Ringwald #ifdef ENABLE_CLASSIC
36577192e786SMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
36587192e786SMatthias Ringwald     return l2cap_get_service_internal(&l2cap_services, psm);
36597192e786SMatthias Ringwald }
36607192e786SMatthias Ringwald 
3661be2053a6SMatthias 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){
3662be2053a6SMatthias Ringwald 
3663be2053a6SMatthias Ringwald     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
3664e0abb8e7S[email protected] 
36654bb582b6Smatthias.ringwald     // check for alread registered psm
36669d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
3667277abc2cSmatthias.ringwald     if (service) {
3668be2053a6SMatthias Ringwald         log_error("l2cap_register_service: PSM %u already registered", psm);
3669be2053a6SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
3670277abc2cSmatthias.ringwald     }
36719d9bbc01Smatthias.ringwald 
36724bb582b6Smatthias.ringwald     // alloc structure
3673bb69aaaeS[email protected]     service = btstack_memory_l2cap_service_get();
3674277abc2cSmatthias.ringwald     if (!service) {
3675be2053a6SMatthias Ringwald         log_error("l2cap_register_service: no memory for l2cap_service_t");
3676be2053a6SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
3677277abc2cSmatthias.ringwald     }
36789d9bbc01Smatthias.ringwald 
36799d9bbc01Smatthias.ringwald     // fill in
36809d9bbc01Smatthias.ringwald     service->psm = psm;
36819d9bbc01Smatthias.ringwald     service->mtu = mtu;
368205ae8de3SMatthias Ringwald     service->packet_handler = service_packet_handler;
3683df3354fcS[email protected]     service->required_security_level = security_level;
36849d9bbc01Smatthias.ringwald 
36859d9bbc01Smatthias.ringwald     // add to services list
3686665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
3687c0e866bfSmatthias.ringwald 
3688c0e866bfSmatthias.ringwald     // enable page scan
368915a95bd5SMatthias Ringwald     gap_connectable_control(1);
36905842b6d9Smatthias.ringwald 
3691c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
36929d9bbc01Smatthias.ringwald }
36939d9bbc01Smatthias.ringwald 
36947e8856ebSMatthias Ringwald uint8_t l2cap_unregister_service(uint16_t psm){
3695e0abb8e7S[email protected] 
3696e0abb8e7S[email protected]     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
3697e0abb8e7S[email protected] 
36989d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
36997e8856ebSMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3700665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
3701d3a9df87Smatthias.ringwald     btstack_memory_l2cap_service_free(service);
3702c0e866bfSmatthias.ringwald 
3703c0e866bfSmatthias.ringwald     // disable page scan when no services registered
37047e8856ebSMatthias Ringwald     if (btstack_linked_list_empty(&l2cap_services)) {
370515a95bd5SMatthias Ringwald         gap_connectable_control(0);
37069d9bbc01Smatthias.ringwald     }
3707c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
37087e8856ebSMatthias Ringwald }
370909e9d05bSMatthias Ringwald #endif
37109d9bbc01Smatthias.ringwald 
37117192e786SMatthias Ringwald 
3712cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
371383fd9c76SMatthias Ringwald 
371457be49d6SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
371557be49d6SMatthias Ringwald     if (!channel->waiting_for_can_send_now) return;
371657be49d6SMatthias Ringwald     if (channel->send_sdu_buffer) return;
371757be49d6SMatthias Ringwald     channel->waiting_for_can_send_now = 0;
3718895ff4a5SMatthias Ringwald     log_debug("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
371957be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
372057be49d6SMatthias Ringwald }
372157be49d6SMatthias Ringwald 
372257be49d6SMatthias Ringwald // 1BH2222
372357be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
372457be49d6SMatthias 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",
372557be49d6SMatthias Ringwald              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
372657be49d6SMatthias Ringwald     uint8_t event[19];
372757be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
372857be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
372957be49d6SMatthias Ringwald     event[2] = channel->address_type;
373057be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
373157be49d6SMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
373257be49d6SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
373357be49d6SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
373457be49d6SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
373557be49d6SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_mtu);
373657be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
373757be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
373857be49d6SMatthias Ringwald }
373957be49d6SMatthias Ringwald // 11BH22222
374057be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
374157be49d6SMatthias 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",
374257be49d6SMatthias Ringwald              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
374357be49d6SMatthias Ringwald              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
3744c99bb618SMatthias Ringwald     uint8_t event[23];
374557be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
374657be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
374757be49d6SMatthias Ringwald     event[2] = status;
374857be49d6SMatthias Ringwald     event[3] = channel->address_type;
374957be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[4]);
375057be49d6SMatthias Ringwald     little_endian_store_16(event, 10, channel->con_handle);
3751c1ab6cc1SMatthias Ringwald     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
3752c99bb618SMatthias Ringwald     little_endian_store_16(event, 13, channel->psm);
3753c99bb618SMatthias Ringwald     little_endian_store_16(event, 15, channel->local_cid);
3754c99bb618SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_cid);
3755c99bb618SMatthias Ringwald     little_endian_store_16(event, 19, channel->local_mtu);
3756c99bb618SMatthias Ringwald     little_endian_store_16(event, 21, channel->remote_mtu);
375757be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
375857be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
375957be49d6SMatthias Ringwald }
376087050a0bSMatthias Ringwald // 2
376187050a0bSMatthias Ringwald static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel){
376287050a0bSMatthias Ringwald     log_info("L2CAP_EVENT_LE_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
376387050a0bSMatthias Ringwald     uint8_t event[4];
376487050a0bSMatthias Ringwald     event[0] = L2CAP_EVENT_LE_CHANNEL_CLOSED;
376587050a0bSMatthias Ringwald     event[1] = sizeof(event) - 2;
376687050a0bSMatthias Ringwald     little_endian_store_16(event, 2, channel->local_cid);
376787050a0bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
376887050a0bSMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
376987050a0bSMatthias Ringwald }
377087050a0bSMatthias Ringwald 
37716774d5c9SMatthias Ringwald static void l2cap_le_send_pdu(l2cap_channel_t *channel){
37726774d5c9SMatthias Ringwald     btstack_assert(channel != NULL);
37736774d5c9SMatthias Ringwald     btstack_assert(channel->send_pdu_buffer != NULL);
37746774d5c9SMatthias Ringwald     btstack_assert(channel->credits_outgoing > 0);
37756774d5c9SMatthias Ringwald 
37766774d5c9SMatthias Ringwald     // send part of SDU
37776774d5c9SMatthias Ringwald     hci_reserve_packet_buffer();
37786774d5c9SMatthias Ringwald     uint8_t * acl_buffer = hci_get_outgoing_packet_buffer();
37796774d5c9SMatthias Ringwald     uint8_t * l2cap_payload = acl_buffer + 8;
37806774d5c9SMatthias Ringwald     uint16_t pos = 0;
37816774d5c9SMatthias Ringwald     if (!channel->send_sdu_pos){
37826774d5c9SMatthias Ringwald         // store SDU len
37836774d5c9SMatthias Ringwald         channel->send_sdu_pos += 2;
37846774d5c9SMatthias Ringwald         little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
37856774d5c9SMatthias Ringwald         pos += 2;
37866774d5c9SMatthias Ringwald     }
37876774d5c9SMatthias Ringwald     uint16_t payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
37886774d5c9SMatthias Ringwald     log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
3789*6535961aSMatthias Ringwald     (void)memcpy(&l2cap_payload[pos],
3790*6535961aSMatthias Ringwald                  &channel->send_sdu_buffer[channel->send_sdu_pos - 2],
3791*6535961aSMatthias Ringwald                  payload_size); // -2 for virtual SDU len
37926774d5c9SMatthias Ringwald     pos += payload_size;
37936774d5c9SMatthias Ringwald     channel->send_sdu_pos += payload_size;
37946774d5c9SMatthias Ringwald     l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
37956774d5c9SMatthias Ringwald 
37966774d5c9SMatthias Ringwald     channel->credits_outgoing--;
37976774d5c9SMatthias Ringwald 
37986774d5c9SMatthias Ringwald     hci_send_acl_packet_buffer(8 + pos);
37996774d5c9SMatthias Ringwald 
3800c1ab6cc1SMatthias Ringwald     if (channel->send_sdu_pos >= (channel->send_sdu_len + 2)){
38016774d5c9SMatthias Ringwald         channel->send_sdu_buffer = NULL;
38026774d5c9SMatthias Ringwald         // send done event
38036774d5c9SMatthias Ringwald         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
38046774d5c9SMatthias Ringwald         // inform about can send now
38056774d5c9SMatthias Ringwald         l2cap_le_notify_channel_can_send(channel);
38066774d5c9SMatthias Ringwald     }
38076774d5c9SMatthias Ringwald }
38086774d5c9SMatthias Ringwald 
380957be49d6SMatthias Ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
381057be49d6SMatthias Ringwald void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
381157be49d6SMatthias Ringwald     channel->state = L2CAP_STATE_CLOSED;
381257be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
381357be49d6SMatthias Ringwald     // discard channel
3814421cb104SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3815c45d6b2cSMatthias Ringwald     l2cap_free_channel_entry(channel);
381657be49d6SMatthias Ringwald }
381757be49d6SMatthias Ringwald 
3818e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
3819e7d0c9aaSMatthias Ringwald     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
38207192e786SMatthias Ringwald }
3821efedfb4cSMatthias Ringwald 
3822da144af5SMatthias Ringwald uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
38237192e786SMatthias Ringwald 
3824da144af5SMatthias Ringwald     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
38257192e786SMatthias Ringwald 
38267192e786SMatthias Ringwald     // check for alread registered psm
38277192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
38287192e786SMatthias Ringwald     if (service) {
3829da144af5SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
38307192e786SMatthias Ringwald     }
38317192e786SMatthias Ringwald 
38327192e786SMatthias Ringwald     // alloc structure
38337192e786SMatthias Ringwald     service = btstack_memory_l2cap_service_get();
38347192e786SMatthias Ringwald     if (!service) {
38357192e786SMatthias Ringwald         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
3836da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
38377192e786SMatthias Ringwald     }
38387192e786SMatthias Ringwald 
38397192e786SMatthias Ringwald     // fill in
38407192e786SMatthias Ringwald     service->psm = psm;
3841da144af5SMatthias Ringwald     service->mtu = 0;
38427192e786SMatthias Ringwald     service->packet_handler = packet_handler;
38437192e786SMatthias Ringwald     service->required_security_level = security_level;
38447192e786SMatthias Ringwald 
38457192e786SMatthias Ringwald     // add to services list
3846665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
38477192e786SMatthias Ringwald 
38487192e786SMatthias Ringwald     // done
38499dd26175SMilanka Ringwald     return ERROR_CODE_SUCCESS;
38507192e786SMatthias Ringwald }
38517192e786SMatthias Ringwald 
3852da144af5SMatthias Ringwald uint8_t l2cap_le_unregister_service(uint16_t psm) {
38537192e786SMatthias Ringwald     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
38547192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
38559367f9b0SMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3856da144af5SMatthias Ringwald 
3857665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
38587192e786SMatthias Ringwald     btstack_memory_l2cap_service_free(service);
3859c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
38607192e786SMatthias Ringwald }
3861da144af5SMatthias Ringwald 
3862da144af5SMatthias Ringwald uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
3863e7d0c9aaSMatthias Ringwald     // get channel
3864421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3865e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3866e7d0c9aaSMatthias Ringwald 
3867e7d0c9aaSMatthias Ringwald     // validate state
3868e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3869e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
3870e7d0c9aaSMatthias Ringwald     }
3871e7d0c9aaSMatthias Ringwald 
3872efedfb4cSMatthias Ringwald     // set state accept connection
387323017473SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
387423017473SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
387523017473SMatthias Ringwald     channel->local_mtu = mtu;
387685aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
387785aeef60SMatthias Ringwald     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
387885aeef60SMatthias Ringwald 
387985aeef60SMatthias Ringwald     // test
388063f0ac45SMatthias Ringwald     // channel->new_credits_incoming = 1;
3881e7d0c9aaSMatthias Ringwald 
3882e7d0c9aaSMatthias Ringwald     // go
3883e7d0c9aaSMatthias Ringwald     l2cap_run();
3884c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
3885da144af5SMatthias Ringwald }
3886da144af5SMatthias Ringwald 
3887da144af5SMatthias Ringwald /**
3888da144af5SMatthias Ringwald  * @brief Deny incoming LE Data Channel connection due to resource constraints
3889da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3890da144af5SMatthias Ringwald  */
3891da144af5SMatthias Ringwald 
3892da144af5SMatthias Ringwald uint8_t l2cap_le_decline_connection(uint16_t local_cid){
3893e7d0c9aaSMatthias Ringwald     // get channel
3894421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3895e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3896e7d0c9aaSMatthias Ringwald 
3897e7d0c9aaSMatthias Ringwald     // validate state
3898e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3899e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
3900e7d0c9aaSMatthias Ringwald     }
3901e7d0c9aaSMatthias Ringwald 
3902efedfb4cSMatthias Ringwald     // set state decline connection
3903e7d0c9aaSMatthias Ringwald     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
3904e7d0c9aaSMatthias Ringwald     channel->reason = 0x04; // no resources available
3905e7d0c9aaSMatthias Ringwald     l2cap_run();
3906c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
3907da144af5SMatthias Ringwald }
3908da144af5SMatthias Ringwald 
39097dafa750SMatthias Ringwald uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
3910da144af5SMatthias Ringwald     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
3911efedfb4cSMatthias Ringwald     uint16_t * out_local_cid) {
3912efedfb4cSMatthias Ringwald 
39137dafa750SMatthias Ringwald     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
3914da144af5SMatthias Ringwald 
39157dafa750SMatthias Ringwald 
39167dafa750SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
39177dafa750SMatthias Ringwald     if (!connection) {
39187dafa750SMatthias Ringwald         log_error("no hci_connection for handle 0x%04x", con_handle);
39197dafa750SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
39207dafa750SMatthias Ringwald     }
39217dafa750SMatthias Ringwald 
39225d18f623SMatthias 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);
3923da144af5SMatthias Ringwald     if (!channel) {
3924da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
3925da144af5SMatthias Ringwald     }
3926e7d0c9aaSMatthias Ringwald     log_info("l2cap_le_create_channel %p", channel);
3927da144af5SMatthias Ringwald 
3928da144af5SMatthias Ringwald     // store local_cid
3929da144af5SMatthias Ringwald     if (out_local_cid){
3930da144af5SMatthias Ringwald        *out_local_cid = channel->local_cid;
3931da144af5SMatthias Ringwald     }
3932da144af5SMatthias Ringwald 
39337dafa750SMatthias Ringwald     // provide buffer
39347dafa750SMatthias Ringwald     channel->con_handle = con_handle;
3935cd529728SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
39367dafa750SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
393785aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
393885aeef60SMatthias Ringwald     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
393985aeef60SMatthias Ringwald 
3940efedfb4cSMatthias Ringwald     // add to connections list
3941421cb104SMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
3942efedfb4cSMatthias Ringwald 
39437dafa750SMatthias Ringwald     // go
394463f0ac45SMatthias Ringwald     l2cap_run();
3945c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
3946da144af5SMatthias Ringwald }
3947da144af5SMatthias Ringwald 
3948da144af5SMatthias Ringwald /**
3949da144af5SMatthias Ringwald  * @brief Provide credtis for LE Data Channel
3950da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3951da144af5SMatthias Ringwald  * @param credits               Number additional credits for peer
3952da144af5SMatthias Ringwald  */
395364e11ca9SMatthias Ringwald uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
395463f0ac45SMatthias Ringwald 
3955421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
395663f0ac45SMatthias Ringwald     if (!channel) {
395763f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
395863f0ac45SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
395963f0ac45SMatthias Ringwald     }
396063f0ac45SMatthias Ringwald 
3961efedfb4cSMatthias Ringwald     // check state
396263f0ac45SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN){
396363f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
396463f0ac45SMatthias Ringwald     }
396563f0ac45SMatthias Ringwald 
396663f0ac45SMatthias Ringwald     // assert incoming credits + credits <= 0xffff
396763f0ac45SMatthias Ringwald     uint32_t total_credits = channel->credits_incoming;
396863f0ac45SMatthias Ringwald     total_credits += channel->new_credits_incoming;
396963f0ac45SMatthias Ringwald     total_credits += credits;
397063f0ac45SMatthias Ringwald     if (total_credits > 0xffff){
397163f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
397263f0ac45SMatthias Ringwald             channel->new_credits_incoming, credits);
397363f0ac45SMatthias Ringwald     }
397463f0ac45SMatthias Ringwald 
3975efedfb4cSMatthias Ringwald     // set credits_granted
397663f0ac45SMatthias Ringwald     channel->new_credits_incoming += credits;
397763f0ac45SMatthias Ringwald 
397863f0ac45SMatthias Ringwald     // go
397963f0ac45SMatthias Ringwald     l2cap_run();
39809dd26175SMilanka Ringwald     return ERROR_CODE_SUCCESS;
3981da144af5SMatthias Ringwald }
3982da144af5SMatthias Ringwald 
3983da144af5SMatthias Ringwald /**
3984da144af5SMatthias Ringwald  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
3985da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3986da144af5SMatthias Ringwald  */
398764e11ca9SMatthias Ringwald int l2cap_le_can_send_now(uint16_t local_cid){
3988421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
398944276248SMatthias Ringwald     if (!channel) {
399044276248SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
3991da144af5SMatthias Ringwald         return 0;
3992da144af5SMatthias Ringwald     }
3993da144af5SMatthias Ringwald 
399444276248SMatthias Ringwald     // check state
399544276248SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN) return 0;
399644276248SMatthias Ringwald 
399744276248SMatthias Ringwald     // check queue
399844276248SMatthias Ringwald     if (channel->send_sdu_buffer) return 0;
399944276248SMatthias Ringwald 
400044276248SMatthias Ringwald     // fine, go ahead
400144276248SMatthias Ringwald     return 1;
400244276248SMatthias Ringwald }
400344276248SMatthias Ringwald 
4004da144af5SMatthias Ringwald /**
4005da144af5SMatthias Ringwald  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
4006da144af5SMatthias Ringwald  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
4007da144af5SMatthias Ringwald  *       so packet handler should be ready to handle it
4008da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
4009da144af5SMatthias Ringwald  */
401064e11ca9SMatthias Ringwald uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
4011421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
401244276248SMatthias Ringwald     if (!channel) {
401344276248SMatthias Ringwald         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
4014c8b2b785SMilanka Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
401544276248SMatthias Ringwald     }
401644276248SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
401744276248SMatthias Ringwald     l2cap_le_notify_channel_can_send(channel);
4018c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
4019da144af5SMatthias Ringwald }
4020da144af5SMatthias Ringwald 
4021da144af5SMatthias Ringwald /**
4022da144af5SMatthias Ringwald  * @brief Send data via LE Data Channel
4023da144af5SMatthias Ringwald  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
4024da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
4025da144af5SMatthias Ringwald  * @param data                  data to send
4026da144af5SMatthias Ringwald  * @param size                  data size
4027da144af5SMatthias Ringwald  */
402864e11ca9SMatthias Ringwald uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
402964e11ca9SMatthias Ringwald 
4030421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
403164e11ca9SMatthias Ringwald     if (!channel) {
403264e11ca9SMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4033828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
403464e11ca9SMatthias Ringwald     }
403564e11ca9SMatthias Ringwald 
403664e11ca9SMatthias Ringwald     if (len > channel->remote_mtu){
403764e11ca9SMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
403864e11ca9SMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
403964e11ca9SMatthias Ringwald     }
404064e11ca9SMatthias Ringwald 
40417f107edaSMatthias Ringwald     if (channel->send_sdu_buffer){
404264e11ca9SMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
404364e11ca9SMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
404464e11ca9SMatthias Ringwald     }
404564e11ca9SMatthias Ringwald 
40467f107edaSMatthias Ringwald     channel->send_sdu_buffer = data;
40477f107edaSMatthias Ringwald     channel->send_sdu_len    = len;
40487f107edaSMatthias Ringwald     channel->send_sdu_pos    = 0;
404964e11ca9SMatthias Ringwald 
40506774d5c9SMatthias Ringwald     l2cap_notify_channel_can_send();
4051c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
4052da144af5SMatthias Ringwald }
4053da144af5SMatthias Ringwald 
4054da144af5SMatthias Ringwald /**
4055da144af5SMatthias Ringwald  * @brief Disconnect from LE Data Channel
4056da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
4057da144af5SMatthias Ringwald  */
4058828a7f7aSMatthias Ringwald uint8_t l2cap_le_disconnect(uint16_t local_cid)
4059da144af5SMatthias Ringwald {
4060421cb104SMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4061828a7f7aSMatthias Ringwald     if (!channel) {
4062828a7f7aSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4063828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4064828a7f7aSMatthias Ringwald     }
4065828a7f7aSMatthias Ringwald 
4066828a7f7aSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4067828a7f7aSMatthias Ringwald     l2cap_run();
4068c8b2b785SMilanka Ringwald     return ERROR_CODE_SUCCESS;
4069da144af5SMatthias Ringwald }
4070da144af5SMatthias Ringwald 
40717f02f414SMatthias Ringwald #endif
4072