xref: /btstack/src/l2cap.c (revision fcb125edafb48af1f7ca83cadb7e28a8c35542e2)
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 
38ab2c6ae4SMatthias 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"
5216ece135SMatthias Ringwald #include "btstack_debug.h"
530e2df43fSMatthias Ringwald #include "btstack_event.h"
54d3a9df87Smatthias.ringwald #include "btstack_memory.h"
5543625864Smatthias.ringwald 
56cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
5783fd9c76SMatthias Ringwald #include "ble/sm.h"
5883fd9c76SMatthias Ringwald #endif
5983fd9c76SMatthias Ringwald 
6043625864Smatthias.ringwald #include <stdarg.h>
6143625864Smatthias.ringwald #include <string.h>
6243625864Smatthias.ringwald 
6343625864Smatthias.ringwald #include <stdio.h>
6443625864Smatthias.ringwald 
654c744e21Smatthias.ringwald // nr of buffered acl packets in outgoing queue to get max performance
664c744e21Smatthias.ringwald #define NR_BUFFERED_ACL_PACKETS 3
674c744e21Smatthias.ringwald 
6839bda6d5Smatthias.ringwald // used to cache l2cap rejects, echo, and informational requests
69e16a9cacSmatthias.ringwald #define NR_PENDING_SIGNALING_RESPONSES 3
7039bda6d5Smatthias.ringwald 
7185aeef60SMatthias Ringwald // nr of credits provided to remote if credits fall below watermark
7285aeef60SMatthias Ringwald #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK 5
7385aeef60SMatthias Ringwald #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT 5
7485aeef60SMatthias Ringwald 
7500d93d79Smatthias.ringwald // offsets for L2CAP SIGNALING COMMANDS
7600d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
7700d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
7800d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
7900d93d79Smatthias.ringwald #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
8000d93d79Smatthias.ringwald 
815628cf69SMatthias Ringwald // internal table
825628cf69SMatthias Ringwald #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL 0
835628cf69SMatthias Ringwald #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL  1
845628cf69SMatthias Ringwald #define L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL 2
855628cf69SMatthias Ringwald #define L2CAP_FIXED_CHANNEL_TABLE_SIZE (L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL+1)
865628cf69SMatthias Ringwald 
8709e9d05bSMatthias Ringwald #if defined(ENABLE_LE_DATA_CHANNELS) || defined(ENABLE_CLASSIC)
8809e9d05bSMatthias Ringwald #define L2CAP_USES_CHANNELS
8909e9d05bSMatthias Ringwald #endif
9009e9d05bSMatthias Ringwald 
9133c40538SMatthias Ringwald // prototypes
92675e6881SMatthias Ringwald static void l2cap_run(void);
9333c40538SMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
943d50b4baSMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size );
9530725612SMatthias Ringwald static void l2cap_notify_channel_can_send(void);
9609e9d05bSMatthias Ringwald static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel);
9709e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
98474f5c3fSMatthias Ringwald static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel);
99474f5c3fSMatthias Ringwald static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel);
10009e9d05bSMatthias Ringwald static void l2cap_finialize_channel_close(l2cap_channel_t *channel);
10109e9d05bSMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm);
10209e9d05bSMatthias Ringwald static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
10309e9d05bSMatthias Ringwald static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
10409e9d05bSMatthias Ringwald static void l2cap_emit_incoming_connection(l2cap_channel_t *channel);
10509e9d05bSMatthias Ringwald static int  l2cap_channel_ready_for_open(l2cap_channel_t *channel);
10609e9d05bSMatthias Ringwald #endif
107cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
10857be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status);
10957be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel);
11057be49d6SMatthias Ringwald static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid);
11144276248SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel);
112828a7f7aSMatthias Ringwald static void l2cap_le_finialize_channel_close(l2cap_channel_t *channel);
113e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t psm);
114e7d0c9aaSMatthias Ringwald #endif
115474f5c3fSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
116474f5c3fSMatthias Ringwald static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size);
117474f5c3fSMatthias Ringwald static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid);
118474f5c3fSMatthias Ringwald static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, bd_addr_t address, bd_addr_type_t address_type,
119474f5c3fSMatthias Ringwald         uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level);
120474f5c3fSMatthias Ringwald #endif
121212b6be2SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
12296646001SMatthias Ringwald static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel);
123c9300dcaSMatthias Ringwald static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts);
1248a700052SMatthias Ringwald static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts);
125212b6be2SMatthias Ringwald #endif
12633c40538SMatthias Ringwald 
1275628cf69SMatthias Ringwald typedef struct l2cap_fixed_channel {
1285628cf69SMatthias Ringwald     btstack_packet_handler_t callback;
1292125de09SMatthias Ringwald     uint8_t waiting_for_can_send_now;
13008dc6394SMatthias Ringwald     uint8_t next_request;
1315628cf69SMatthias Ringwald } l2cap_fixed_channel_t;
1325628cf69SMatthias Ringwald 
13309e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1345628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_channels;
1355628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_services;
13609e9d05bSMatthias Ringwald static uint8_t require_security_level2_for_outgoing_sdp;
13709e9d05bSMatthias Ringwald #endif
13857be49d6SMatthias Ringwald 
13957be49d6SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1405628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_le_channels;
1415628cf69SMatthias Ringwald static btstack_linked_list_t l2cap_le_services;
14257be49d6SMatthias Ringwald #endif
14339bda6d5Smatthias.ringwald 
14439bda6d5Smatthias.ringwald // used to cache l2cap rejects, echo, and informational requests
1452b83fb7dSmatthias.ringwald static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
1462b83fb7dSmatthias.ringwald static int signaling_responses_pending;
1472b83fb7dSmatthias.ringwald 
148fb37a842SMatthias Ringwald static btstack_packet_callback_registration_t hci_event_callback_registration;
14908dc6394SMatthias Ringwald #define FIXED_CHANNEL_FIFO_INVALID_INDEX 0xff
1505628cf69SMatthias Ringwald static l2cap_fixed_channel_t fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_SIZE];
15108dc6394SMatthias Ringwald static uint8_t fixed_channel_head_index = FIXED_CHANNEL_FIFO_INVALID_INDEX;
15208dc6394SMatthias Ringwald static uint8_t fixed_channel_tail_index = FIXED_CHANNEL_FIFO_INVALID_INDEX;
15339bda6d5Smatthias.ringwald 
154d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
155d6ed9f9cSMatthias Ringwald // only used for connection parameter update events
156d6ed9f9cSMatthias Ringwald static btstack_packet_handler_t l2cap_event_packet_handler;
157d6ed9f9cSMatthias Ringwald #endif
158d6ed9f9cSMatthias Ringwald 
15985ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
16085ddcd84SMatthias Ringwald 
161*fcb125edSMatthias Ringwald static uint8_t l2cap_ertm_omit_fcs_option;
162*fcb125edSMatthias Ringwald 
16385ddcd84SMatthias Ringwald /*
16485ddcd84SMatthias Ringwald  * CRC lookup table for generator polynom D^16 + D^15 + D^2 + 1
16585ddcd84SMatthias Ringwald  */
16685ddcd84SMatthias Ringwald static const uint16_t crc16_table[256] = {
16785ddcd84SMatthias Ringwald     0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
16885ddcd84SMatthias Ringwald     0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841,
16985ddcd84SMatthias Ringwald     0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41,
17085ddcd84SMatthias Ringwald     0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040,
17185ddcd84SMatthias Ringwald     0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441,
17285ddcd84SMatthias Ringwald     0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840,
17385ddcd84SMatthias Ringwald     0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40,
17485ddcd84SMatthias Ringwald     0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041,
17585ddcd84SMatthias Ringwald     0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
17685ddcd84SMatthias Ringwald     0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840,
17785ddcd84SMatthias Ringwald     0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
17885ddcd84SMatthias Ringwald     0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041,
17985ddcd84SMatthias Ringwald     0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440,
18085ddcd84SMatthias Ringwald     0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841,
18185ddcd84SMatthias Ringwald     0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41,
18285ddcd84SMatthias Ringwald     0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040,
18385ddcd84SMatthias Ringwald };
18485ddcd84SMatthias Ringwald 
18585ddcd84SMatthias Ringwald static uint16_t crc16_calc(uint8_t * data, uint16_t len){
18685ddcd84SMatthias Ringwald     uint16_t crc = 0;   // initial value = 0
18785ddcd84SMatthias Ringwald     while (len--){
18885ddcd84SMatthias Ringwald         crc = (crc >> 8) ^ crc16_table[ (crc ^ ((uint16_t) *data++)) & 0x00FF ];
18985ddcd84SMatthias Ringwald     }
19085ddcd84SMatthias Ringwald     return crc;
19185ddcd84SMatthias Ringwald }
19285ddcd84SMatthias Ringwald 
193474f5c3fSMatthias 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){
194474f5c3fSMatthias Ringwald     return (((uint16_t) sar) << 14) | (req_seq << 8) | (final << 7) | (tx_seq << 1) | 0;
195474f5c3fSMatthias Ringwald }
196474f5c3fSMatthias Ringwald 
197474f5c3fSMatthias 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){
198474f5c3fSMatthias Ringwald     return (req_seq << 8) | (final << 7) | (poll << 4) | (((int) supervisory_function) << 2) | 1;
199474f5c3fSMatthias Ringwald }
200474f5c3fSMatthias Ringwald 
201474f5c3fSMatthias Ringwald static int l2cap_next_ertm_seq_nr(int seq_nr){
202474f5c3fSMatthias Ringwald     return (seq_nr + 1) & 0x3f;
203474f5c3fSMatthias Ringwald }
204474f5c3fSMatthias Ringwald 
205474f5c3fSMatthias Ringwald static int l2cap_ertm_can_store_packet_now(l2cap_channel_t * channel){
206474f5c3fSMatthias Ringwald      // get num free tx buffers
207474f5c3fSMatthias Ringwald     int num_tx_buffers_used = channel->tx_write_index - channel->tx_read_index;
208474f5c3fSMatthias Ringwald     if (num_tx_buffers_used < 0){
209474f5c3fSMatthias Ringwald         num_tx_buffers_used += channel->num_tx_buffers;
210474f5c3fSMatthias Ringwald     }
211474f5c3fSMatthias Ringwald     int num_free_tx_buffers = channel->num_tx_buffers - num_tx_buffers_used;
212474f5c3fSMatthias Ringwald     // calculate num tx buffers for remote MTU
213474f5c3fSMatthias Ringwald     int num_tx_buffers_for_max_remote_mtu;
214474f5c3fSMatthias Ringwald     if (channel->remote_mtu <= channel->remote_mps){
215474f5c3fSMatthias Ringwald         // MTU fits into single packet
216474f5c3fSMatthias Ringwald         num_tx_buffers_for_max_remote_mtu = 1;
217474f5c3fSMatthias Ringwald     } else {
218474f5c3fSMatthias Ringwald         // include SDU Length
219474f5c3fSMatthias Ringwald         num_tx_buffers_for_max_remote_mtu = (channel->remote_mtu + 2 + (channel->remote_mps - 1)) / channel->remote_mps;
220474f5c3fSMatthias Ringwald     }
221474f5c3fSMatthias Ringwald     return num_tx_buffers_for_max_remote_mtu <= num_free_tx_buffers;
222474f5c3fSMatthias Ringwald }
223474f5c3fSMatthias Ringwald 
224474f5c3fSMatthias Ringwald static void l2cap_ertm_next_tx_write_index(l2cap_channel_t * channel){
225474f5c3fSMatthias Ringwald     channel->tx_write_index++;
226474f5c3fSMatthias Ringwald     if (channel->tx_write_index < channel->num_tx_buffers) return;
227474f5c3fSMatthias Ringwald     channel->tx_write_index = 0;
228474f5c3fSMatthias Ringwald }
229474f5c3fSMatthias Ringwald 
230474f5c3fSMatthias Ringwald static void l2cap_ertm_start_monitor_timer(l2cap_channel_t * channel){
231550189ffSMatthias Ringwald     log_info("Start Monitor timer");
232474f5c3fSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->monitor_timer);
233474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->monitor_timer, &l2cap_ertm_monitor_timeout_callback);
234474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer_context(&channel->monitor_timer, channel);
235474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer(&channel->monitor_timer, channel->local_monitor_timeout_ms);
236474f5c3fSMatthias Ringwald     btstack_run_loop_add_timer(&channel->monitor_timer);
237474f5c3fSMatthias Ringwald }
238474f5c3fSMatthias Ringwald 
239550189ffSMatthias Ringwald static void l2cap_ertm_stop_monitor_timer(l2cap_channel_t * channel){
240550189ffSMatthias Ringwald     log_info("Stop Monitor timer");
241550189ffSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->monitor_timer);
242550189ffSMatthias Ringwald }
243474f5c3fSMatthias Ringwald 
244474f5c3fSMatthias Ringwald static void l2cap_ertm_start_retransmission_timer(l2cap_channel_t * channel){
245550189ffSMatthias Ringwald     log_info("Start Retransmission timer");
246474f5c3fSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->retransmission_timer);
247474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->retransmission_timer, &l2cap_ertm_retransmission_timeout_callback);
248474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer_context(&channel->retransmission_timer, channel);
249474f5c3fSMatthias Ringwald     btstack_run_loop_set_timer(&channel->retransmission_timer, channel->local_retransmission_timeout_ms);
250474f5c3fSMatthias Ringwald     btstack_run_loop_add_timer(&channel->retransmission_timer);
251474f5c3fSMatthias Ringwald }
252474f5c3fSMatthias Ringwald 
253474f5c3fSMatthias Ringwald static void l2cap_ertm_stop_retransmission_timer(l2cap_channel_t * l2cap_channel){
254550189ffSMatthias Ringwald     log_info("Stop Retransmission timer");
255474f5c3fSMatthias Ringwald     btstack_run_loop_remove_timer(&l2cap_channel->retransmission_timer);
256474f5c3fSMatthias Ringwald }
257474f5c3fSMatthias Ringwald 
258474f5c3fSMatthias Ringwald static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts){
259550189ffSMatthias Ringwald     log_info("Monitor timeout");
260474f5c3fSMatthias Ringwald     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
261474f5c3fSMatthias Ringwald 
262474f5c3fSMatthias Ringwald     // TODO: we assume that it's the oldest packet
263474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
264474f5c3fSMatthias Ringwald     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
265474f5c3fSMatthias Ringwald 
266474f5c3fSMatthias Ringwald     // check retry count
267474f5c3fSMatthias Ringwald     if (tx_state->retry_count < l2cap_channel->remote_max_transmit){
268474f5c3fSMatthias Ringwald         // increment retry count
269474f5c3fSMatthias Ringwald         tx_state->retry_count++;
270474f5c3fSMatthias Ringwald 
271474f5c3fSMatthias Ringwald         l2cap_ertm_start_monitor_timer(l2cap_channel);
272474f5c3fSMatthias Ringwald 
273474f5c3fSMatthias Ringwald         // send RR/P=1
274474f5c3fSMatthias Ringwald         l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
275474f5c3fSMatthias Ringwald     } else {
276474f5c3fSMatthias Ringwald         log_info("Monitor timer expired & retry count >= max transmit -> disconnect");
277474f5c3fSMatthias Ringwald         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
278474f5c3fSMatthias Ringwald     }
279474f5c3fSMatthias Ringwald     l2cap_run();
280474f5c3fSMatthias Ringwald }
281474f5c3fSMatthias Ringwald 
282474f5c3fSMatthias Ringwald static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts){
283550189ffSMatthias Ringwald     log_info("Retransmission timeout");
284474f5c3fSMatthias Ringwald     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
285474f5c3fSMatthias Ringwald 
286474f5c3fSMatthias Ringwald     // TODO: we assume that it's the oldest packet
287474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
288474f5c3fSMatthias Ringwald     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
289474f5c3fSMatthias Ringwald 
290474f5c3fSMatthias Ringwald     // set retry count = 1
291474f5c3fSMatthias Ringwald     tx_state->retry_count = 1;
292474f5c3fSMatthias Ringwald 
293474f5c3fSMatthias Ringwald     // start monitor timer
294474f5c3fSMatthias Ringwald     l2cap_ertm_start_monitor_timer(l2cap_channel);
295474f5c3fSMatthias Ringwald 
296474f5c3fSMatthias Ringwald     // send RR/P=1
297474f5c3fSMatthias Ringwald     l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
298474f5c3fSMatthias Ringwald     l2cap_run();
299474f5c3fSMatthias Ringwald }
300474f5c3fSMatthias Ringwald 
301474f5c3fSMatthias Ringwald static int l2cap_ertm_send_information_frame(l2cap_channel_t * channel, int index, int final){
302474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
303474f5c3fSMatthias Ringwald     hci_reserve_packet_buffer();
304474f5c3fSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
305474f5c3fSMatthias Ringwald     uint16_t control = l2cap_encanced_control_field_for_information_frame(tx_state->tx_seq, final, channel->req_seq, tx_state->sar);
306474f5c3fSMatthias Ringwald     log_info("I-Frame: control 0x%04x", control);
307474f5c3fSMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
308474f5c3fSMatthias Ringwald     memcpy(&acl_buffer[8+2], &channel->tx_packets_data[index * channel->local_mtu], tx_state->len);
3091e1a46bbSMatthias Ringwald     // (re-)start retransmission timer on
3101e1a46bbSMatthias Ringwald     l2cap_ertm_start_retransmission_timer(channel);
311474f5c3fSMatthias Ringwald     // send
312474f5c3fSMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2 + tx_state->len);
313474f5c3fSMatthias Ringwald }
314474f5c3fSMatthias Ringwald 
315474f5c3fSMatthias 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){
316474f5c3fSMatthias Ringwald     // get next index for storing packets
317474f5c3fSMatthias Ringwald     int index = channel->tx_write_index;
318474f5c3fSMatthias Ringwald 
319474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
320474f5c3fSMatthias Ringwald     tx_state->tx_seq = channel->next_tx_seq;
321474f5c3fSMatthias Ringwald     tx_state->len = len;
322474f5c3fSMatthias Ringwald     tx_state->sar = sar;
323474f5c3fSMatthias Ringwald     tx_state->retry_count = 0;
324474f5c3fSMatthias Ringwald 
325474f5c3fSMatthias Ringwald     uint8_t * tx_packet = &channel->tx_packets_data[index * channel->local_mtu];
326474f5c3fSMatthias Ringwald     int pos = 0;
327474f5c3fSMatthias Ringwald     if (sar == L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU){
328474f5c3fSMatthias Ringwald         little_endian_store_16(tx_packet, 0, sdu_length);
329474f5c3fSMatthias Ringwald         pos += 2;
330474f5c3fSMatthias Ringwald     }
331474f5c3fSMatthias Ringwald     memcpy(&tx_packet[pos], data, len);
332474f5c3fSMatthias Ringwald 
333474f5c3fSMatthias Ringwald     // update
334474f5c3fSMatthias Ringwald     channel->next_tx_seq = l2cap_next_ertm_seq_nr(channel->next_tx_seq);
335474f5c3fSMatthias Ringwald     l2cap_ertm_next_tx_write_index(channel);
33694301352SMatthias Ringwald 
33794301352SMatthias Ringwald     log_info("l2cap_ertm_store_fragment: after store, tx_read_index %u, tx_write_index %u", channel->tx_read_index, channel->tx_write_index);
33894301352SMatthias Ringwald 
339474f5c3fSMatthias Ringwald }
340474f5c3fSMatthias Ringwald 
341474f5c3fSMatthias Ringwald static int l2cap_ertm_send(l2cap_channel_t * channel, uint8_t * data, uint16_t len){
342474f5c3fSMatthias Ringwald     if (len > channel->remote_mtu){
343474f5c3fSMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
344474f5c3fSMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
345474f5c3fSMatthias Ringwald     }
346474f5c3fSMatthias Ringwald 
347474f5c3fSMatthias Ringwald     // check if it needs to get fragmented
348474f5c3fSMatthias Ringwald     if (len > channel->remote_mps){
349474f5c3fSMatthias Ringwald         // fragmentation needed.
350474f5c3fSMatthias Ringwald         l2cap_segmentation_and_reassembly_t sar =  L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU;
351474f5c3fSMatthias Ringwald         int chunk_len;
352474f5c3fSMatthias Ringwald         while (len){
353474f5c3fSMatthias Ringwald             switch (sar){
354474f5c3fSMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
355474f5c3fSMatthias Ringwald                     chunk_len = channel->remote_mps - 2;    // sdu_length
356474f5c3fSMatthias Ringwald                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
357474f5c3fSMatthias Ringwald                     len -= chunk_len;
358474f5c3fSMatthias Ringwald                     sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU;
359474f5c3fSMatthias Ringwald                     break;
360474f5c3fSMatthias Ringwald                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
361474f5c3fSMatthias Ringwald                     chunk_len = channel->remote_mps;
362474f5c3fSMatthias Ringwald                     if (chunk_len >= len){
363474f5c3fSMatthias Ringwald                         sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU;
364474f5c3fSMatthias Ringwald                         chunk_len = len;
365474f5c3fSMatthias Ringwald                     }
366474f5c3fSMatthias Ringwald                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
367474f5c3fSMatthias Ringwald                     len -= chunk_len;
368474f5c3fSMatthias Ringwald                     break;
369474f5c3fSMatthias Ringwald                 default:
370474f5c3fSMatthias Ringwald                     break;
371474f5c3fSMatthias Ringwald             }
372474f5c3fSMatthias Ringwald         }
373474f5c3fSMatthias Ringwald 
374474f5c3fSMatthias Ringwald     } else {
375474f5c3fSMatthias Ringwald         l2cap_ertm_store_fragment(channel, L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU, 0, data, len);
376474f5c3fSMatthias Ringwald     }
377474f5c3fSMatthias Ringwald 
378474f5c3fSMatthias Ringwald     // try to send
379474f5c3fSMatthias Ringwald     l2cap_run();
380474f5c3fSMatthias Ringwald     return 0;
381474f5c3fSMatthias Ringwald }
382474f5c3fSMatthias Ringwald 
3837cbe539fSMatthias Ringwald static uint16_t l2cap_setup_options_ertm_request(l2cap_channel_t * channel, uint8_t * config_options){
384*fcb125edSMatthias Ringwald     int pos = 0;
385*fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
386*fcb125edSMatthias Ringwald     config_options[pos++] = 9;      // length
387*fcb125edSMatthias Ringwald     config_options[pos++] = (uint8_t) channel->mode;
388*fcb125edSMatthias Ringwald     config_options[pos++] = channel->num_rx_buffers;    // == TxWindows size
389*fcb125edSMatthias Ringwald     config_options[pos++] = channel->local_max_transmit;
390*fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
391*fcb125edSMatthias Ringwald     pos += 2;
392*fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
393*fcb125edSMatthias Ringwald     pos += 2;
394*fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_mps);
395*fcb125edSMatthias Ringwald     pos += 2;
3966574158aSMatthias Ringwald     //
397*fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT;
398*fcb125edSMatthias Ringwald     config_options[pos++] = 2;     // length
399*fcb125edSMatthias Ringwald     little_endian_store_16(config_options, pos, channel->local_mtu);
400*fcb125edSMatthias Ringwald     pos += 2;
401d64e9771SMatthias Ringwald     //
402*fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
403*fcb125edSMatthias Ringwald     config_options[pos++] = 1;     // length
404*fcb125edSMatthias Ringwald     config_options[pos++] = channel->fcs_option;
405*fcb125edSMatthias Ringwald     return pos;
406474f5c3fSMatthias Ringwald }
407474f5c3fSMatthias Ringwald 
4087cbe539fSMatthias Ringwald static uint16_t l2cap_setup_options_ertm_response(l2cap_channel_t * channel, uint8_t * config_options){
409*fcb125edSMatthias Ringwald     int pos = 0;
410*fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
411*fcb125edSMatthias Ringwald     config_options[pos++] = 9;      // length
412*fcb125edSMatthias Ringwald     config_options[pos++] = (uint8_t) channel->mode;
4137cbe539fSMatthias Ringwald     // less or equal to remote tx window size
414*fcb125edSMatthias Ringwald     config_options[pos++] = btstack_min(channel->num_tx_buffers, channel->remote_tx_window_size);
4157cbe539fSMatthias Ringwald     // max transmit in response shall be ignored -> use sender values
416*fcb125edSMatthias Ringwald     config_options[pos++] = channel->remote_max_transmit;
4177cbe539fSMatthias Ringwald     // A value for the Retransmission time-out shall be sent in a positive Configuration Response
4187cbe539fSMatthias Ringwald     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
419*fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
420*fcb125edSMatthias Ringwald     pos += 2;
4217cbe539fSMatthias Ringwald     // A value for the Monitor time-out shall be sent in a positive Configuration Response
4227cbe539fSMatthias Ringwald     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
423*fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
424*fcb125edSMatthias Ringwald     pos += 2;
4257cbe539fSMatthias Ringwald     // less or equal to remote mps
426*fcb125edSMatthias Ringwald     little_endian_store_16( config_options, pos, btstack_min(channel->local_mps, channel->remote_mps));
427*fcb125edSMatthias Ringwald     pos += 2;
4286574158aSMatthias Ringwald     //
429*fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
430*fcb125edSMatthias Ringwald     config_options[pos++] = 2;     // length
431*fcb125edSMatthias Ringwald     little_endian_store_16(config_options, pos, channel->remote_mtu);
432*fcb125edSMatthias Ringwald     pos += 2;
433*fcb125edSMatthias Ringwald #if 0
434d64e9771SMatthias Ringwald     //
435*fcb125edSMatthias Ringwald     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
436*fcb125edSMatthias Ringwald     config_options[pos++] = 1;     // length
437*fcb125edSMatthias Ringwald     config_options[pos++] = channel->fcs_option;
438*fcb125edSMatthias Ringwald #endif
439*fcb125edSMatthias Ringwald     return pos;
4407cbe539fSMatthias Ringwald }
4417cbe539fSMatthias Ringwald 
442474f5c3fSMatthias Ringwald static int l2cap_ertm_send_supervisor_frame(l2cap_channel_t * channel, uint16_t control){
443474f5c3fSMatthias Ringwald     hci_reserve_packet_buffer();
444474f5c3fSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
445474f5c3fSMatthias Ringwald     log_info("S-Frame: control 0x%04x", control);
446474f5c3fSMatthias Ringwald     little_endian_store_16(acl_buffer, 8, control);
447474f5c3fSMatthias Ringwald     return l2cap_send_prepared(channel->local_cid, 2);
448474f5c3fSMatthias Ringwald }
449474f5c3fSMatthias Ringwald 
4505774a392SMatthias Ringwald static uint8_t l2cap_ertm_validate_local_config(l2cap_ertm_config_t * ertm_config){
451474f5c3fSMatthias Ringwald 
452474f5c3fSMatthias Ringwald     uint8_t result = ERROR_CODE_SUCCESS;
4539c0e62d3SMatthias Ringwald     if (ertm_config->max_transmit < 1){
454474f5c3fSMatthias Ringwald         log_error("max_transmit must be >= 1");
455474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
456474f5c3fSMatthias Ringwald     }
4579c0e62d3SMatthias Ringwald     if (ertm_config->retransmission_timeout_ms < 2000){
458474f5c3fSMatthias Ringwald         log_error("retransmission_timeout_ms must be >= 2000 ms");
459474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
460474f5c3fSMatthias Ringwald     }
4619c0e62d3SMatthias Ringwald     if (ertm_config->monitor_timeout_ms < 12000){
462474f5c3fSMatthias Ringwald         log_error("monitor_timeout_ms must be >= 12000 ms");
463474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
464474f5c3fSMatthias Ringwald     }
4659c0e62d3SMatthias Ringwald     if (ertm_config->local_mtu < 48){
466474f5c3fSMatthias Ringwald         log_error("local_mtu must be >= 48");
467474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
468474f5c3fSMatthias Ringwald     }
4699c0e62d3SMatthias Ringwald     if (ertm_config->num_rx_buffers < 1){
470474f5c3fSMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
471474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
472474f5c3fSMatthias Ringwald     }
4739c0e62d3SMatthias Ringwald     if (ertm_config->num_tx_buffers < 1){
474474f5c3fSMatthias Ringwald         log_error("num_rx_buffers must be >= 1");
475474f5c3fSMatthias Ringwald         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
476474f5c3fSMatthias Ringwald     }
477474f5c3fSMatthias Ringwald     return result;
478474f5c3fSMatthias Ringwald }
479474f5c3fSMatthias Ringwald 
4809c0e62d3SMatthias Ringwald static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
481474f5c3fSMatthias Ringwald 
482474f5c3fSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
4839c0e62d3SMatthias Ringwald     channel->ertm_mandatory = ertm_config->ertm_mandatory;
4849c0e62d3SMatthias Ringwald     channel->local_max_transmit = ertm_config->max_transmit;
4859c0e62d3SMatthias Ringwald     channel->local_retransmission_timeout_ms = ertm_config->retransmission_timeout_ms;
4869c0e62d3SMatthias Ringwald     channel->local_monitor_timeout_ms = ertm_config->monitor_timeout_ms;
4879c0e62d3SMatthias Ringwald     channel->local_mtu = ertm_config->local_mtu;
4889c0e62d3SMatthias Ringwald     channel->num_rx_buffers = ertm_config->num_rx_buffers;
4899c0e62d3SMatthias Ringwald     channel->num_tx_buffers = ertm_config->num_tx_buffers;
490474f5c3fSMatthias Ringwald 
491474f5c3fSMatthias Ringwald     // align buffer to 16-byte boundary, just in case
492474f5c3fSMatthias Ringwald     int bytes_till_alignment = 16 - (((uintptr_t) buffer) & 0x0f);
493474f5c3fSMatthias Ringwald     buffer += bytes_till_alignment;
494474f5c3fSMatthias Ringwald     size   -= bytes_till_alignment;
495474f5c3fSMatthias Ringwald 
496474f5c3fSMatthias Ringwald     // setup state buffers
497474f5c3fSMatthias Ringwald     uint32_t pos = 0;
498474f5c3fSMatthias Ringwald     channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) &buffer[pos];
4999c0e62d3SMatthias Ringwald     pos += ertm_config->num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
500474f5c3fSMatthias Ringwald     channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) &buffer[pos];
5019c0e62d3SMatthias Ringwald     pos += ertm_config->num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
502474f5c3fSMatthias Ringwald 
503474f5c3fSMatthias Ringwald     // setup reassembly buffer
504474f5c3fSMatthias Ringwald     channel->reassembly_buffer = &buffer[pos];
5059c0e62d3SMatthias Ringwald     pos += ertm_config->local_mtu;
506474f5c3fSMatthias Ringwald 
507474f5c3fSMatthias Ringwald     // divide rest of data equally
5089c0e62d3SMatthias Ringwald     channel->local_mps = (size - pos) / (ertm_config->num_rx_buffers + ertm_config->num_tx_buffers);
5090d3ee2efSMatthias Ringwald     log_info("Local MPS: %u", channel->local_mps);
510474f5c3fSMatthias Ringwald     channel->rx_packets_data = &buffer[pos];
5110d3ee2efSMatthias Ringwald     pos += ertm_config->num_rx_buffers * channel->local_mps;
512474f5c3fSMatthias Ringwald     channel->tx_packets_data = &buffer[pos];
5136574158aSMatthias Ringwald 
5146574158aSMatthias Ringwald     // Issue: iOS (e.g. 10.2) uses "No FCS" as default while Core 5.0 specifies "FCS" as default
5156574158aSMatthias Ringwald     // Workaround: try to actively negotiate "No FCS" and fall back to "FCS" if "No FCS" is rejected
5166574158aSMatthias Ringwald     // This works as iOS accepts the "No FCS" request, hence the default value is only used on non-iOS devices
5176574158aSMatthias Ringwald     channel->fcs_option = 0;
518474f5c3fSMatthias Ringwald }
519474f5c3fSMatthias Ringwald 
520474f5c3fSMatthias Ringwald uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
5219c0e62d3SMatthias Ringwald     l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
522474f5c3fSMatthias Ringwald 
5239c0e62d3SMatthias 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);
524474f5c3fSMatthias Ringwald 
525474f5c3fSMatthias Ringwald     // validate local config
5265774a392SMatthias Ringwald     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
527474f5c3fSMatthias Ringwald     if (result) return result;
528474f5c3fSMatthias Ringwald 
5299c0e62d3SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, ertm_config->local_mtu, LEVEL_0);
530474f5c3fSMatthias Ringwald     if (!channel) {
531474f5c3fSMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
532474f5c3fSMatthias Ringwald     }
533474f5c3fSMatthias Ringwald 
534474f5c3fSMatthias Ringwald     // configure ERTM
5359c0e62d3SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
536474f5c3fSMatthias Ringwald 
537474f5c3fSMatthias Ringwald     // add to connections list
538474f5c3fSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
539474f5c3fSMatthias Ringwald 
540474f5c3fSMatthias Ringwald     // store local_cid
541474f5c3fSMatthias Ringwald     if (out_local_cid){
542474f5c3fSMatthias Ringwald        *out_local_cid = channel->local_cid;
543474f5c3fSMatthias Ringwald     }
544474f5c3fSMatthias Ringwald 
545474f5c3fSMatthias Ringwald     // check if hci connection is already usable
546474f5c3fSMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
547474f5c3fSMatthias Ringwald     if (conn){
548474f5c3fSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
549474f5c3fSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
550474f5c3fSMatthias Ringwald         // check if remote supported fearures are already received
551474f5c3fSMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
552474f5c3fSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
553474f5c3fSMatthias Ringwald         }
554474f5c3fSMatthias Ringwald     }
555474f5c3fSMatthias Ringwald 
556474f5c3fSMatthias Ringwald     l2cap_run();
557474f5c3fSMatthias Ringwald 
558474f5c3fSMatthias Ringwald     return 0;
559474f5c3fSMatthias Ringwald }
560474f5c3fSMatthias Ringwald 
561474f5c3fSMatthias Ringwald static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel){
562474f5c3fSMatthias Ringwald     if (l2cap_ertm_can_store_packet_now(channel)){
563474f5c3fSMatthias Ringwald         channel->waiting_for_can_send_now = 0;
564474f5c3fSMatthias Ringwald         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
565474f5c3fSMatthias Ringwald     }
566474f5c3fSMatthias Ringwald }
567474f5c3fSMatthias Ringwald 
5689c0e62d3SMatthias Ringwald uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
569474f5c3fSMatthias Ringwald 
570474f5c3fSMatthias Ringwald     log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
571474f5c3fSMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
572474f5c3fSMatthias Ringwald     if (!channel) {
573474f5c3fSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
574474f5c3fSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
575474f5c3fSMatthias Ringwald     }
576474f5c3fSMatthias Ringwald 
577474f5c3fSMatthias Ringwald     // validate local config
5785774a392SMatthias Ringwald     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
579474f5c3fSMatthias Ringwald     if (result) return result;
580474f5c3fSMatthias Ringwald 
581474f5c3fSMatthias Ringwald     // configure L2CAP ERTM
5829c0e62d3SMatthias Ringwald     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
583474f5c3fSMatthias Ringwald 
584474f5c3fSMatthias Ringwald     // continue
585474f5c3fSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
586474f5c3fSMatthias Ringwald 
587474f5c3fSMatthias Ringwald     // process
588474f5c3fSMatthias Ringwald     l2cap_run();
589474f5c3fSMatthias Ringwald 
590474f5c3fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
591474f5c3fSMatthias Ringwald }
592474f5c3fSMatthias Ringwald 
593474f5c3fSMatthias Ringwald uint8_t l2cap_ertm_set_busy(uint16_t local_cid){
594474f5c3fSMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
595474f5c3fSMatthias Ringwald     if (!channel) {
596474f5c3fSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
597474f5c3fSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
598474f5c3fSMatthias Ringwald     }
599474f5c3fSMatthias Ringwald     if (!channel->local_busy){
600474f5c3fSMatthias Ringwald         channel->local_busy = 1;
601474f5c3fSMatthias Ringwald         channel->send_supervisor_frame_receiver_not_ready = 1;
602474f5c3fSMatthias Ringwald         l2cap_run();
603474f5c3fSMatthias Ringwald     }
604474f5c3fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
605474f5c3fSMatthias Ringwald }
606474f5c3fSMatthias Ringwald 
607474f5c3fSMatthias Ringwald uint8_t l2cap_ertm_set_ready(uint16_t local_cid){
608474f5c3fSMatthias Ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
609474f5c3fSMatthias Ringwald     if (!channel) {
610474f5c3fSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
611474f5c3fSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
612474f5c3fSMatthias Ringwald     }
613474f5c3fSMatthias Ringwald     if (channel->local_busy){
614474f5c3fSMatthias Ringwald         channel->local_busy = 0;
615474f5c3fSMatthias Ringwald         channel->send_supervisor_frame_receiver_ready_poll = 1;
616474f5c3fSMatthias Ringwald         l2cap_run();
617474f5c3fSMatthias Ringwald     }
618474f5c3fSMatthias Ringwald     return ERROR_CODE_SUCCESS;
619474f5c3fSMatthias Ringwald }
620474f5c3fSMatthias Ringwald 
6211e1a46bbSMatthias Ringwald // Process-ReqSeq
6221e1a46bbSMatthias Ringwald static void l2cap_ertm_process_req_seq(l2cap_channel_t * l2cap_channel, uint8_t req_seq){
623474f5c3fSMatthias Ringwald     int num_buffers_acked = 0;
624474f5c3fSMatthias Ringwald     l2cap_ertm_tx_packet_state_t * tx_state;
62594301352SMatthias 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);
626474f5c3fSMatthias Ringwald     while (1){
6271e1a46bbSMatthias Ringwald 
62894301352SMatthias Ringwald         // no unack packets left
62994301352SMatthias Ringwald         if (l2cap_channel->unacked_frames == 0) {
6301e1a46bbSMatthias Ringwald             // stop retransmission timer
6311e1a46bbSMatthias Ringwald             l2cap_ertm_stop_retransmission_timer(l2cap_channel);
6321e1a46bbSMatthias Ringwald             break;
6331e1a46bbSMatthias Ringwald         }
6341e1a46bbSMatthias Ringwald 
635474f5c3fSMatthias Ringwald         tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
636474f5c3fSMatthias Ringwald         // calc delta
637474f5c3fSMatthias Ringwald         int delta = (req_seq - tx_state->tx_seq) & 0x03f;
638474f5c3fSMatthias Ringwald         if (delta == 0) break;  // all packets acknowledged
639474f5c3fSMatthias Ringwald         if (delta > l2cap_channel->remote_tx_window_size) break;
640474f5c3fSMatthias Ringwald 
641474f5c3fSMatthias Ringwald         num_buffers_acked++;
64294301352SMatthias Ringwald         l2cap_channel->unacked_frames--;
643474f5c3fSMatthias Ringwald         log_info("RR seq %u => packet with tx_seq %u done", req_seq, tx_state->tx_seq);
644474f5c3fSMatthias Ringwald 
645474f5c3fSMatthias Ringwald         l2cap_channel->tx_read_index++;
646474f5c3fSMatthias Ringwald         if (l2cap_channel->tx_read_index >= l2cap_channel->num_rx_buffers){
647474f5c3fSMatthias Ringwald             l2cap_channel->tx_read_index = 0;
648474f5c3fSMatthias Ringwald         }
649474f5c3fSMatthias Ringwald     }
650474f5c3fSMatthias Ringwald 
651474f5c3fSMatthias Ringwald     if (num_buffers_acked){
652474f5c3fSMatthias Ringwald         l2cap_ertm_notify_channel_can_send(l2cap_channel);
653474f5c3fSMatthias Ringwald     }
654474f5c3fSMatthias Ringwald }
655474f5c3fSMatthias Ringwald 
656474f5c3fSMatthias Ringwald static l2cap_ertm_tx_packet_state_t * l2cap_ertm_get_tx_state(l2cap_channel_t * l2cap_channel, uint8_t tx_seq){
657474f5c3fSMatthias Ringwald     int i;
658474f5c3fSMatthias Ringwald     for (i=0;i<l2cap_channel->num_tx_buffers;i++){
659474f5c3fSMatthias Ringwald         l2cap_ertm_tx_packet_state_t * tx_state = &l2cap_channel->tx_packets_state[i];
660474f5c3fSMatthias Ringwald         if (tx_state->tx_seq == tx_seq) return tx_state;
661474f5c3fSMatthias Ringwald     }
662474f5c3fSMatthias Ringwald     return NULL;
663474f5c3fSMatthias Ringwald }
664474f5c3fSMatthias Ringwald 
665474f5c3fSMatthias Ringwald // @param delta number of frames in the future, >= 1
666122c2b05SMatthias Ringwald // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
6673d244bfaSMatthias 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){
668474f5c3fSMatthias Ringwald     log_info("Store SDU with delta %u", delta);
669474f5c3fSMatthias Ringwald     // get rx state for packet to store
670474f5c3fSMatthias Ringwald     int index = l2cap_channel->rx_store_index + delta - 1;
671474f5c3fSMatthias Ringwald     if (index > l2cap_channel->num_rx_buffers){
672474f5c3fSMatthias Ringwald         index -= l2cap_channel->num_rx_buffers;
673474f5c3fSMatthias Ringwald     }
674474f5c3fSMatthias Ringwald     log_info("Index of packet to store %u", index);
675474f5c3fSMatthias Ringwald     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
676474f5c3fSMatthias Ringwald     // check if buffer is free
677474f5c3fSMatthias Ringwald     if (rx_state->valid){
678474f5c3fSMatthias Ringwald         log_error("Packet buffer already used");
679474f5c3fSMatthias Ringwald         return;
680474f5c3fSMatthias Ringwald     }
681474f5c3fSMatthias Ringwald     rx_state->valid = 1;
682474f5c3fSMatthias Ringwald     rx_state->sar = sar;
683474f5c3fSMatthias Ringwald     rx_state->len = size;
684474f5c3fSMatthias Ringwald     uint8_t * rx_buffer = &l2cap_channel->rx_packets_data[index];
685474f5c3fSMatthias Ringwald     memcpy(rx_buffer, payload, size);
686474f5c3fSMatthias Ringwald }
687474f5c3fSMatthias Ringwald 
688122c2b05SMatthias Ringwald // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
6893d244bfaSMatthias 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){
690122c2b05SMatthias Ringwald     uint16_t reassembly_sdu_length;
691474f5c3fSMatthias Ringwald     switch (sar){
692474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
693122c2b05SMatthias Ringwald             // assert total packet size <= our mtu
694122c2b05SMatthias Ringwald             if (size > l2cap_channel->local_mtu) break;
695474f5c3fSMatthias Ringwald             // packet complete -> disapatch
6963d244bfaSMatthias Ringwald             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, (uint8_t*) payload, size);
697474f5c3fSMatthias Ringwald             break;
698474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
699122c2b05SMatthias Ringwald             // read SDU len
700122c2b05SMatthias Ringwald             reassembly_sdu_length = little_endian_read_16(payload, 0);
701474f5c3fSMatthias Ringwald             payload += 2;
702474f5c3fSMatthias Ringwald             size    -= 2;
703122c2b05SMatthias Ringwald             // assert reassembled size <= our mtu
704122c2b05SMatthias Ringwald             if (reassembly_sdu_length > l2cap_channel->local_mtu) break;
705122c2b05SMatthias Ringwald             // store start segment
706122c2b05SMatthias Ringwald             l2cap_channel->reassembly_sdu_length = reassembly_sdu_length;
707474f5c3fSMatthias Ringwald             memcpy(&l2cap_channel->reassembly_buffer[0], payload, size);
708474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos = size;
709474f5c3fSMatthias Ringwald             break;
710474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
711122c2b05SMatthias Ringwald             // assert size of reassembled data <= our mtu
712122c2b05SMatthias Ringwald             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
713122c2b05SMatthias Ringwald             // store continuation segment
714474f5c3fSMatthias Ringwald             memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos], payload, size);
715474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos += size;
716474f5c3fSMatthias Ringwald             break;
717474f5c3fSMatthias Ringwald         case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
718122c2b05SMatthias Ringwald             // assert size of reassembled data <= our mtu
719122c2b05SMatthias Ringwald             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
720122c2b05SMatthias Ringwald             // store continuation segment
721474f5c3fSMatthias Ringwald             memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos], payload, size);
722474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos += size;
723122c2b05SMatthias Ringwald             // assert size of reassembled data matches announced sdu length
724122c2b05SMatthias Ringwald             if (l2cap_channel->reassembly_pos != l2cap_channel->reassembly_sdu_length) break;
725474f5c3fSMatthias Ringwald             // packet complete -> disapatch
726474f5c3fSMatthias Ringwald             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->reassembly_buffer, l2cap_channel->reassembly_pos);
727474f5c3fSMatthias Ringwald             l2cap_channel->reassembly_pos = 0;
728474f5c3fSMatthias Ringwald             break;
729474f5c3fSMatthias Ringwald     }
730474f5c3fSMatthias Ringwald }
731474f5c3fSMatthias Ringwald 
732*fcb125edSMatthias Ringwald void l2cap_ertm_dont_send_fcs_option(void){
733*fcb125edSMatthias Ringwald     l2cap_ertm_omit_fcs_option = 1;
734*fcb125edSMatthias Ringwald }
735*fcb125edSMatthias Ringwald 
73685ddcd84SMatthias Ringwald #endif
73785ddcd84SMatthias Ringwald 
73885ddcd84SMatthias Ringwald 
73934e7e577SMatthias Ringwald static uint16_t l2cap_fixed_channel_table_channel_id_for_index(int index){
74034e7e577SMatthias Ringwald     switch (index){
74134e7e577SMatthias Ringwald         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL:
74234e7e577SMatthias Ringwald             return L2CAP_CID_ATTRIBUTE_PROTOCOL;
74334e7e577SMatthias Ringwald         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL:
74434e7e577SMatthias Ringwald             return L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
74534e7e577SMatthias Ringwald         case L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL:
74634e7e577SMatthias Ringwald             return L2CAP_CID_CONNECTIONLESS_CHANNEL;
74734e7e577SMatthias Ringwald         default:
74834e7e577SMatthias Ringwald             return 0;
74934e7e577SMatthias Ringwald     }
75034e7e577SMatthias Ringwald }
7515628cf69SMatthias Ringwald static int l2cap_fixed_channel_table_index_for_channel_id(uint16_t channel_id){
7525628cf69SMatthias Ringwald     switch (channel_id){
7535628cf69SMatthias Ringwald         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
7545628cf69SMatthias Ringwald             return L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL;
7555628cf69SMatthias Ringwald         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
7565628cf69SMatthias Ringwald             return  L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL;
7575628cf69SMatthias Ringwald         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
7585628cf69SMatthias Ringwald             return  L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL;
7595628cf69SMatthias Ringwald         default:
7605628cf69SMatthias Ringwald             return -1;
7615628cf69SMatthias Ringwald         }
7625628cf69SMatthias Ringwald }
76339bda6d5Smatthias.ringwald 
76434e7e577SMatthias Ringwald static int l2cap_fixed_channel_table_index_is_le(int index){
76534e7e577SMatthias Ringwald     if (index == L2CAP_CID_CONNECTIONLESS_CHANNEL) return 0;
76634e7e577SMatthias Ringwald     return 1;
76734e7e577SMatthias Ringwald }
76834e7e577SMatthias Ringwald 
76971de195eSMatthias Ringwald void l2cap_init(void){
7702b83fb7dSmatthias.ringwald     signaling_responses_pending = 0;
771808a48abSmatthias.ringwald 
77209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
773f5454fc6Smatthias.ringwald     l2cap_channels = NULL;
774f5454fc6Smatthias.ringwald     l2cap_services = NULL;
77509e9d05bSMatthias Ringwald     require_security_level2_for_outgoing_sdp = 0;
77609e9d05bSMatthias Ringwald #endif
777a3dc965aSMatthias Ringwald 
778a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
7797192e786SMatthias Ringwald     l2cap_le_services = NULL;
7807192e786SMatthias Ringwald     l2cap_le_channels = NULL;
781a3dc965aSMatthias Ringwald #endif
782f5454fc6Smatthias.ringwald 
783d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
78433c40538SMatthias Ringwald     l2cap_event_packet_handler = NULL;
785d6ed9f9cSMatthias Ringwald #endif
7865628cf69SMatthias Ringwald     memset(fixed_channels, 0, sizeof(fixed_channels));
78708dc6394SMatthias Ringwald     int i;
78808dc6394SMatthias Ringwald     for (i=0;i<L2CAP_FIXED_CHANNEL_TABLE_SIZE;i++){
78908dc6394SMatthias Ringwald         fixed_channels[i].next_request = FIXED_CHANNEL_FIFO_INVALID_INDEX;
79008dc6394SMatthias Ringwald     }
791f5454fc6Smatthias.ringwald 
792fcadd0caSmatthias.ringwald     //
7932718e2e7Smatthias.ringwald     // register callback with HCI
794fcadd0caSmatthias.ringwald     //
795d9a7306aSMatthias Ringwald     hci_event_callback_registration.callback = &l2cap_hci_event_handler;
796fb37a842SMatthias Ringwald     hci_add_event_handler(&hci_event_callback_registration);
797fb37a842SMatthias Ringwald 
798d9a7306aSMatthias Ringwald     hci_register_acl_packet_handler(&l2cap_acl_handler);
799fb37a842SMatthias Ringwald 
800be005ed6SMatthias Ringwald #ifdef ENABLE_CLASSIC
80115a95bd5SMatthias Ringwald     gap_connectable_control(0); // no services yet
802be005ed6SMatthias Ringwald #endif
803fcadd0caSmatthias.ringwald }
804fcadd0caSmatthias.ringwald 
805ffbf8201SMatthias Ringwald void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
806d6ed9f9cSMatthias Ringwald #ifdef ENABLE_BLE
80733c40538SMatthias Ringwald     l2cap_event_packet_handler = handler;
808d6ed9f9cSMatthias Ringwald #else
8095774a392SMatthias Ringwald     UNUSED(handler);    // ok: no code
810d6ed9f9cSMatthias Ringwald #endif
8111e6aba47Smatthias.ringwald }
8121e6aba47Smatthias.ringwald 
81309e9d05bSMatthias Ringwald void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
8145774a392SMatthias Ringwald     UNUSED(con_handle);  // ok: there is no channel
8159ec2630cSMatthias Ringwald 
81609e9d05bSMatthias Ringwald     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
81709e9d05bSMatthias Ringwald     if (index < 0) return;
81808dc6394SMatthias Ringwald 
8196bd7c69dSMatthias Ringwald     // check if already registered
8206bd7c69dSMatthias Ringwald     if (fixed_channels[index].waiting_for_can_send_now) return;
8216bd7c69dSMatthias Ringwald 
82208dc6394SMatthias Ringwald     // insert into queue
82308dc6394SMatthias Ringwald     if (fixed_channel_tail_index == FIXED_CHANNEL_FIFO_INVALID_INDEX){
82408dc6394SMatthias Ringwald         fixed_channel_head_index = index;
82508dc6394SMatthias Ringwald     } else {
82608dc6394SMatthias Ringwald         fixed_channels[fixed_channel_tail_index].next_request = index;
82708dc6394SMatthias Ringwald     }
82808dc6394SMatthias Ringwald     fixed_channel_tail_index = index;
82908dc6394SMatthias Ringwald     fixed_channels[index].next_request = FIXED_CHANNEL_FIFO_INVALID_INDEX;
83009e9d05bSMatthias Ringwald     fixed_channels[index].waiting_for_can_send_now = 1;
83109e9d05bSMatthias Ringwald     l2cap_notify_channel_can_send();
83209e9d05bSMatthias Ringwald }
83309e9d05bSMatthias Ringwald 
83409e9d05bSMatthias Ringwald int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
8355774a392SMatthias Ringwald     UNUSED(channel_id); // ok: only depends on Controller LE buffers
8369ec2630cSMatthias Ringwald 
83709e9d05bSMatthias Ringwald     return hci_can_send_acl_packet_now(con_handle);
83809e9d05bSMatthias Ringwald }
83909e9d05bSMatthias Ringwald 
84009e9d05bSMatthias Ringwald uint8_t *l2cap_get_outgoing_buffer(void){
84109e9d05bSMatthias Ringwald     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
84209e9d05bSMatthias Ringwald }
84309e9d05bSMatthias Ringwald 
84409e9d05bSMatthias Ringwald int l2cap_reserve_packet_buffer(void){
84509e9d05bSMatthias Ringwald     return hci_reserve_packet_buffer();
84609e9d05bSMatthias Ringwald }
84709e9d05bSMatthias Ringwald 
84809e9d05bSMatthias Ringwald void l2cap_release_packet_buffer(void){
84909e9d05bSMatthias Ringwald     hci_release_packet_buffer();
85009e9d05bSMatthias Ringwald }
85109e9d05bSMatthias Ringwald 
852f511cefaSMatthias 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){
85309e9d05bSMatthias Ringwald     // 0 - Connection handle : PB=pb : BC=00
854f511cefaSMatthias Ringwald     little_endian_store_16(acl_buffer, 0, con_handle | (packet_boundary << 12) | (0 << 14));
85509e9d05bSMatthias Ringwald     // 2 - ACL length
85609e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 2,  len + 4);
85709e9d05bSMatthias Ringwald     // 4 - L2CAP packet length
85809e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 4,  len + 0);
85909e9d05bSMatthias Ringwald     // 6 - L2CAP channel DEST
86009e9d05bSMatthias Ringwald     little_endian_store_16(acl_buffer, 6,  remote_cid);
86109e9d05bSMatthias Ringwald }
86209e9d05bSMatthias Ringwald 
863f511cefaSMatthias Ringwald // assumption - only on LE connections
86409e9d05bSMatthias Ringwald int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
86509e9d05bSMatthias Ringwald 
86609e9d05bSMatthias Ringwald     if (!hci_is_packet_buffer_reserved()){
86709e9d05bSMatthias Ringwald         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
86809e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
86909e9d05bSMatthias Ringwald     }
87009e9d05bSMatthias Ringwald 
87109e9d05bSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
87209e9d05bSMatthias Ringwald         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
87309e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
87409e9d05bSMatthias Ringwald     }
87509e9d05bSMatthias Ringwald 
87609e9d05bSMatthias Ringwald     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
87709e9d05bSMatthias Ringwald 
87809e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
879f511cefaSMatthias Ringwald     l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
88009e9d05bSMatthias Ringwald     // send
88109e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len+8);
88209e9d05bSMatthias Ringwald }
88309e9d05bSMatthias Ringwald 
884f511cefaSMatthias Ringwald // assumption - only on LE connections
88509e9d05bSMatthias Ringwald int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
88609e9d05bSMatthias Ringwald 
88709e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(con_handle)){
88809e9d05bSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", cid);
88909e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
89009e9d05bSMatthias Ringwald     }
89109e9d05bSMatthias Ringwald 
89209e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
89309e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
89409e9d05bSMatthias Ringwald 
89509e9d05bSMatthias Ringwald     memcpy(&acl_buffer[8], data, len);
89609e9d05bSMatthias Ringwald 
89709e9d05bSMatthias Ringwald     return l2cap_send_prepared_connectionless(con_handle, cid, len);
89809e9d05bSMatthias Ringwald }
89909e9d05bSMatthias Ringwald 
90009e9d05bSMatthias Ringwald static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
901d9d23054SMatthias Ringwald     log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
90209e9d05bSMatthias Ringwald     uint8_t event[4];
90309e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
90409e9d05bSMatthias Ringwald     event[1] = sizeof(event) - 2;
90509e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, channel);
90609e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
90709e9d05bSMatthias Ringwald     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
90809e9d05bSMatthias Ringwald }
90909e9d05bSMatthias Ringwald 
91009e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
91117a9b554SMatthias Ringwald static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
91258de5610Smatthias.ringwald     (* (channel->packet_handler))(type, channel->local_cid, data, size);
91358de5610Smatthias.ringwald }
91458de5610Smatthias.ringwald 
91544276248SMatthias Ringwald static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
91644276248SMatthias Ringwald     uint8_t event[4];
91744276248SMatthias Ringwald     event[0] = event_code;
91844276248SMatthias Ringwald     event[1] = sizeof(event) - 2;
91944276248SMatthias Ringwald     little_endian_store_16(event, 2, channel->local_cid);
92044276248SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
92144276248SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
92244276248SMatthias Ringwald }
92309e9d05bSMatthias Ringwald #endif
92444276248SMatthias Ringwald 
92509e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
92658de5610Smatthias.ringwald void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
927c9dc710bS[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",
928fc64f94aSMatthias Ringwald              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
929c9dc710bS[email protected]              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
930*fcb125edSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
931*fcb125edSMatthias Ringwald     log_info("ERTM mode %u, fcs enabled %u", channel->mode, channel->fcs_option);
932*fcb125edSMatthias Ringwald #endif
933bab5f4f0SMatthias Ringwald     uint8_t event[24];
93458de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
93558de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
93658de5610Smatthias.ringwald     event[2] = status;
937724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
938fc64f94aSMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
939f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
940f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
941f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
942f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 17, channel->local_mtu);
943f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 19, channel->remote_mtu);
944f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 21, channel->flush_timeout);
945bab5f4f0SMatthias Ringwald     event[23] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
94658de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
94717a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
94858de5610Smatthias.ringwald }
94958de5610Smatthias.ringwald 
95044276248SMatthias Ringwald static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
951e0abb8e7S[email protected]     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
95244276248SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
95358de5610Smatthias.ringwald }
95458de5610Smatthias.ringwald 
95544276248SMatthias Ringwald static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
956e0abb8e7S[email protected]     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
957fc64f94aSMatthias Ringwald              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
95858de5610Smatthias.ringwald     uint8_t event[16];
95958de5610Smatthias.ringwald     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
96058de5610Smatthias.ringwald     event[1] = sizeof(event) - 2;
961724d70a2SMatthias Ringwald     reverse_bd_addr(channel->address, &event[2]);
962fc64f94aSMatthias Ringwald     little_endian_store_16(event,  8, channel->con_handle);
963f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 10, channel->psm);
964f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 12, channel->local_cid);
965f8fbdce0SMatthias Ringwald     little_endian_store_16(event, 14, channel->remote_cid);
96658de5610Smatthias.ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
96717a9b554SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
9680af41d30Smatthias.ringwald }
969808a48abSmatthias.ringwald 
9707f02f414SMatthias Ringwald static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
971665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
972665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
973665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
974665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
975b35f641cSmatthias.ringwald         if ( channel->local_cid == local_cid) {
976f62db1e3Smatthias.ringwald             return channel;
977f62db1e3Smatthias.ringwald         }
978f62db1e3Smatthias.ringwald     }
979f62db1e3Smatthias.ringwald     return NULL;
980f62db1e3Smatthias.ringwald }
981f62db1e3Smatthias.ringwald 
9820b9d7e78SMatthias Ringwald ///
9830b9d7e78SMatthias Ringwald 
98430725612SMatthias Ringwald void l2cap_request_can_send_now_event(uint16_t local_cid){
98530725612SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
98630725612SMatthias Ringwald     if (!channel) return;
98730725612SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
98896646001SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
98996646001SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
99096646001SMatthias Ringwald         l2cap_ertm_notify_channel_can_send(channel);
99196646001SMatthias Ringwald         return;
99296646001SMatthias Ringwald     }
99396646001SMatthias Ringwald #endif
99430725612SMatthias Ringwald     l2cap_notify_channel_can_send();
99530725612SMatthias Ringwald }
99630725612SMatthias Ringwald 
99796646001SMatthias Ringwald int  l2cap_can_send_packet_now(uint16_t local_cid){
99896646001SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
99996646001SMatthias Ringwald     if (!channel) return 0;
100096646001SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
100196646001SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
100296646001SMatthias Ringwald         return l2cap_ertm_can_store_packet_now(channel);
100396646001SMatthias Ringwald     }
100496646001SMatthias Ringwald #endif
10050b9d7e78SMatthias Ringwald     return hci_can_send_acl_packet_now(channel->con_handle);
10067856fb31S[email protected] }
10077856fb31S[email protected] 
100883e7cdd9SMatthias Ringwald int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
100983e7cdd9SMatthias Ringwald     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
101083e7cdd9SMatthias Ringwald     if (!channel) return 0;
10110b20b13bSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
10120b20b13bSMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
10130b20b13bSMatthias Ringwald         return 0;
10140b20b13bSMatthias Ringwald     }
10150b20b13bSMatthias Ringwald #endif
10160b9d7e78SMatthias Ringwald     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
101783e7cdd9SMatthias Ringwald }
10180b20b13bSMatthias Ringwald 
101996cbd662Smatthias.ringwald uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
102096cbd662Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
102196cbd662Smatthias.ringwald     if (channel) {
102296cbd662Smatthias.ringwald         return channel->remote_mtu;
102396cbd662Smatthias.ringwald     }
102496cbd662Smatthias.ringwald     return 0;
102596cbd662Smatthias.ringwald }
102696cbd662Smatthias.ringwald 
1027ec820d77SMatthias Ringwald static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
1028665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1029665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1030665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1031665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
10325932bd7cS[email protected]         if ( &channel->rtx == ts) {
10335932bd7cS[email protected]             return channel;
10345932bd7cS[email protected]         }
10355932bd7cS[email protected]     }
10365932bd7cS[email protected]     return NULL;
10375932bd7cS[email protected] }
10385932bd7cS[email protected] 
1039ec820d77SMatthias Ringwald static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
10405932bd7cS[email protected]     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
104195d2c8f4SMatthias Ringwald     if (!channel) return;
10425932bd7cS[email protected] 
10435932bd7cS[email protected]     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
10445932bd7cS[email protected] 
10455932bd7cS[email protected]     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
10465932bd7cS[email protected]     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
10475932bd7cS[email protected]     // notify client
10485932bd7cS[email protected]     l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
10495932bd7cS[email protected] 
10505932bd7cS[email protected]     // discard channel
10519dcb2fb2S[email protected]     // no need to stop timer here, it is removed from list during timer callback
1052665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
10535932bd7cS[email protected]     btstack_memory_l2cap_channel_free(channel);
10545932bd7cS[email protected] }
10555932bd7cS[email protected] 
10565932bd7cS[email protected] static void l2cap_stop_rtx(l2cap_channel_t * channel){
10575932bd7cS[email protected]     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
1058528a4a3bSMatthias Ringwald     btstack_run_loop_remove_timer(&channel->rtx);
10595932bd7cS[email protected] }
10605932bd7cS[email protected] 
10615932bd7cS[email protected] static void l2cap_start_rtx(l2cap_channel_t * channel){
10625932bd7cS[email protected]     l2cap_stop_rtx(channel);
1063cb0ff06bS[email protected]     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
1064528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1065528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
1066528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
10675932bd7cS[email protected] }
10685932bd7cS[email protected] 
10695932bd7cS[email protected] static void l2cap_start_ertx(l2cap_channel_t * channel){
10705932bd7cS[email protected]     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
10715932bd7cS[email protected]     l2cap_stop_rtx(channel);
1072528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1073528a4a3bSMatthias Ringwald     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
1074528a4a3bSMatthias Ringwald     btstack_run_loop_add_timer(&channel->rtx);
10755932bd7cS[email protected] }
10765932bd7cS[email protected] 
107771de195eSMatthias Ringwald void l2cap_require_security_level_2_for_outgoing_sdp(void){
1078ac301f95S[email protected]     require_security_level2_for_outgoing_sdp = 1;
1079ac301f95S[email protected] }
1080ac301f95S[email protected] 
1081df3354fcS[email protected] static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
1082235946f1SMatthias Ringwald     return (psm == BLUETOOTH_PROTOCOL_SDP) && (!require_security_level2_for_outgoing_sdp);
1083df3354fcS[email protected] }
10845932bd7cS[email protected] 
108563854e74SMatthias Ringwald static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1086a35252c8S[email protected]     if (!hci_can_send_acl_packet_now(handle)){
10879da54300S[email protected]         log_info("l2cap_send_signaling_packet, cannot send");
1088b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
1089b1d43497Smatthias.ringwald     }
1090b1d43497Smatthias.ringwald 
10919da54300S[email protected]     // log_info("l2cap_send_signaling_packet type %u", cmd);
10922a373862S[email protected]     hci_reserve_packet_buffer();
1093facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
109458de5610Smatthias.ringwald     va_list argptr;
109558de5610Smatthias.ringwald     va_start(argptr, identifier);
109670efece1S[email protected]     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
109758de5610Smatthias.ringwald     va_end(argptr);
10989da54300S[email protected]     // log_info("l2cap_send_signaling_packet con %u!", handle);
1099826f7347S[email protected]     return hci_send_acl_packet_buffer(len);
110058de5610Smatthias.ringwald }
110158de5610Smatthias.ringwald 
1102f511cefaSMatthias Ringwald // assumption - only on Classic connections
1103b1d43497Smatthias.ringwald int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
1104b1d43497Smatthias.ringwald 
1105c8b9416aS[email protected]     if (!hci_is_packet_buffer_reserved()){
1106c8b9416aS[email protected]         log_error("l2cap_send_prepared called without reserving packet first");
1107c8b9416aS[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
1108c8b9416aS[email protected]     }
1109c8b9416aS[email protected] 
111058de5610Smatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1111b1d43497Smatthias.ringwald     if (!channel) {
11129da54300S[email protected]         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
1113b1d43497Smatthias.ringwald         return -1;   // TODO: define error
11146218e6f1Smatthias.ringwald     }
11156218e6f1Smatthias.ringwald 
1116fc64f94aSMatthias Ringwald     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
11179da54300S[email protected]         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
1118a35252c8S[email protected]         return BTSTACK_ACL_BUFFERS_FULL;
1119a35252c8S[email protected]     }
1120a35252c8S[email protected] 
1121fc64f94aSMatthias Ringwald     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
1122b1d43497Smatthias.ringwald 
112385ddcd84SMatthias Ringwald     int fcs_size = 0;
112485ddcd84SMatthias Ringwald 
112585ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
11266574158aSMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->fcs_option){
112785ddcd84SMatthias Ringwald         fcs_size = 2;
112885ddcd84SMatthias Ringwald     }
112985ddcd84SMatthias Ringwald #endif
113085ddcd84SMatthias Ringwald 
1131f511cefaSMatthias Ringwald     // set non-flushable packet boundary flag if supported on Controller
1132facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1133f511cefaSMatthias Ringwald     uint8_t packet_boundary_flag = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
113485ddcd84SMatthias Ringwald     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
113585ddcd84SMatthias Ringwald 
113685ddcd84SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
113785ddcd84SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
113885ddcd84SMatthias Ringwald         // calculate FCS over l2cap data
113985ddcd84SMatthias Ringwald         uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
114085ddcd84SMatthias Ringwald         log_info("I-Frame: fcs 0x%04x", fcs);
114185ddcd84SMatthias Ringwald         little_endian_store_16(acl_buffer, 8 + len, fcs);
114258de5610Smatthias.ringwald     }
114385ddcd84SMatthias Ringwald #endif
114485ddcd84SMatthias Ringwald 
114585ddcd84SMatthias Ringwald     // send
114685ddcd84SMatthias Ringwald     return hci_send_acl_packet_buffer(len+8+fcs_size);
114785ddcd84SMatthias Ringwald }
114885ddcd84SMatthias Ringwald 
1149f511cefaSMatthias Ringwald // assumption - only on Classic connections
1150ce8f182eSMatthias Ringwald int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
1151a35252c8S[email protected]     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1152a35252c8S[email protected]     if (!channel) {
1153ce8f182eSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
1154a35252c8S[email protected]         return -1;   // TODO: define error
1155a35252c8S[email protected]     }
1156a35252c8S[email protected] 
1157f0fb4cd7SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1158f0fb4cd7SMatthias Ringwald     // send in ERTM
1159f0fb4cd7SMatthias Ringwald     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1160f0fb4cd7SMatthias Ringwald         return l2cap_ertm_send(channel, data, len);
1161f0fb4cd7SMatthias Ringwald     }
1162f0fb4cd7SMatthias Ringwald #endif
1163f0fb4cd7SMatthias Ringwald 
1164f0efaa57S[email protected]     if (len > channel->remote_mtu){
1165ce8f182eSMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
1166f0efaa57S[email protected]         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
1167f0efaa57S[email protected]     }
1168f0efaa57S[email protected] 
1169fc64f94aSMatthias Ringwald     if (!hci_can_send_acl_packet_now(channel->con_handle)){
1170ce8f182eSMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
1171b1d43497Smatthias.ringwald         return BTSTACK_ACL_BUFFERS_FULL;
1172b1d43497Smatthias.ringwald     }
1173b1d43497Smatthias.ringwald 
11742a373862S[email protected]     hci_reserve_packet_buffer();
1175facf93fdS[email protected]     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1176f0fb4cd7SMatthias Ringwald     memcpy(&acl_buffer[8], data, len);
1177f0fb4cd7SMatthias Ringwald     return l2cap_send_prepared(local_cid, len);
1178b1d43497Smatthias.ringwald }
1179b1d43497Smatthias.ringwald 
1180fc64f94aSMatthias Ringwald int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
1181fc64f94aSMatthias Ringwald     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
11820e37e417S[email protected] }
11830e37e417S[email protected] 
118428ca2b46S[email protected] static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
118528ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
118628ca2b46S[email protected] }
118728ca2b46S[email protected] 
118828ca2b46S[email protected] static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
118928ca2b46S[email protected]     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
119028ca2b46S[email protected] }
119109e9d05bSMatthias Ringwald #endif
119228ca2b46S[email protected] 
119328ca2b46S[email protected] 
119409e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
119563854e74SMatthias Ringwald static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
119609e9d05bSMatthias Ringwald 
119709e9d05bSMatthias Ringwald     if (!hci_can_send_acl_packet_now(handle)){
119809e9d05bSMatthias Ringwald         log_info("l2cap_send_le_signaling_packet, cannot send");
119909e9d05bSMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
120009e9d05bSMatthias Ringwald     }
120109e9d05bSMatthias Ringwald 
120209e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
120309e9d05bSMatthias Ringwald     hci_reserve_packet_buffer();
120409e9d05bSMatthias Ringwald     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
120509e9d05bSMatthias Ringwald     va_list argptr;
120609e9d05bSMatthias Ringwald     va_start(argptr, identifier);
120709e9d05bSMatthias Ringwald     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
120809e9d05bSMatthias Ringwald     va_end(argptr);
120909e9d05bSMatthias Ringwald     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
121009e9d05bSMatthias Ringwald     return hci_send_acl_packet_buffer(len);
121109e9d05bSMatthias Ringwald }
121209e9d05bSMatthias Ringwald #endif
121309e9d05bSMatthias Ringwald 
121409e9d05bSMatthias Ringwald uint16_t l2cap_max_mtu(void){
121509e9d05bSMatthias Ringwald     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
121609e9d05bSMatthias Ringwald }
121709e9d05bSMatthias Ringwald 
121809e9d05bSMatthias Ringwald uint16_t l2cap_max_le_mtu(void){
121909e9d05bSMatthias Ringwald     return l2cap_max_mtu();
122009e9d05bSMatthias Ringwald }
1221b1d43497Smatthias.ringwald 
1222d2afdd38SMatthias Ringwald #ifdef ENABLE_CLASSIC
1223d2afdd38SMatthias Ringwald 
12246b99230fSMatthias Ringwald static uint16_t l2cap_setup_options_mtu(uint8_t * config_options, uint16_t mtu){
1225d64e9771SMatthias Ringwald     config_options[0] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
1226d2afdd38SMatthias Ringwald     config_options[1] = 2; // len param
12276b99230fSMatthias Ringwald     little_endian_store_16(config_options, 2, mtu);
1228d2afdd38SMatthias Ringwald     return 4;
1229d2afdd38SMatthias Ringwald }
1230d2afdd38SMatthias Ringwald 
1231450ad7ecSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
12326b99230fSMatthias Ringwald static int l2cap_ertm_mode(l2cap_channel_t * channel){
1233450ad7ecSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
12346b99230fSMatthias Ringwald     return ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE)
12356b99230fSMatthias Ringwald         &&  (connection->l2cap_state.extended_feature_mask & 0x08));
1236450ad7ecSMatthias Ringwald }
1237450ad7ecSMatthias Ringwald #endif
12386b99230fSMatthias Ringwald 
12396b99230fSMatthias Ringwald static uint16_t l2cap_setup_options_request(l2cap_channel_t * channel, uint8_t * config_options){
12406b99230fSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
12416b99230fSMatthias Ringwald     // use ERTM options if supported
12426b99230fSMatthias Ringwald     if (l2cap_ertm_mode(channel)){
12437cbe539fSMatthias Ringwald         return l2cap_setup_options_ertm_request(channel, config_options);
12446b99230fSMatthias Ringwald     }
12456b99230fSMatthias Ringwald #endif
12466b99230fSMatthias Ringwald     uint16_t mtu = channel->local_mtu;
12476b99230fSMatthias Ringwald     return l2cap_setup_options_mtu(config_options, mtu);
12486b99230fSMatthias Ringwald }
12496b99230fSMatthias Ringwald 
12506b99230fSMatthias Ringwald static uint16_t l2cap_setup_options_response(l2cap_channel_t * channel, uint8_t * config_options){
12516b99230fSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
12526b99230fSMatthias Ringwald     // use ERTM options if supported
12536b99230fSMatthias Ringwald     if (l2cap_ertm_mode(channel)){
12547cbe539fSMatthias Ringwald         return l2cap_setup_options_ertm_response(channel, config_options);
12556b99230fSMatthias Ringwald     }
12566b99230fSMatthias Ringwald #endif
125732717978SMatthias Ringwald     uint16_t mtu = btstack_min(channel->local_mtu, channel->remote_mtu);
12586b99230fSMatthias Ringwald     return l2cap_setup_options_mtu(config_options, mtu);
12596dca2a0cSMatthias Ringwald }
12606dca2a0cSMatthias Ringwald 
12611b9cb13dSMatthias Ringwald static uint32_t l2cap_extended_features_mask(void){
12621b9cb13dSMatthias Ringwald     // extended features request supported, features: fixed channels, unicast connectionless data reception
12631b9cb13dSMatthias Ringwald     uint32_t features = 0x280;
12641b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
12651b9cb13dSMatthias Ringwald     features |= 0x0008;
12661b9cb13dSMatthias Ringwald #endif
12671b9cb13dSMatthias Ringwald     return features;
12681b9cb13dSMatthias Ringwald }
1269d2afdd38SMatthias Ringwald #endif
12701b9cb13dSMatthias Ringwald 
12718158c421Smatthias.ringwald // MARK: L2CAP_RUN
12722cd0be45Smatthias.ringwald // process outstanding signaling tasks
12737f02f414SMatthias Ringwald static void l2cap_run(void){
12742b83fb7dSmatthias.ringwald 
127522c29ab4SMatthias Ringwald     // log_info("l2cap_run: entered");
127622c29ab4SMatthias Ringwald 
12772b83fb7dSmatthias.ringwald     // check pending signaling responses
12782b83fb7dSmatthias.ringwald     while (signaling_responses_pending){
12792b83fb7dSmatthias.ringwald 
12802b83fb7dSmatthias.ringwald         hci_con_handle_t handle = signaling_responses[0].handle;
1281a35252c8S[email protected] 
1282a35252c8S[email protected]         if (!hci_can_send_acl_packet_now(handle)) break;
1283a35252c8S[email protected] 
12842b83fb7dSmatthias.ringwald         uint8_t  sig_id        = signaling_responses[0].sig_id;
1285e74c5f58SMatthias Ringwald         uint8_t  response_code = signaling_responses[0].code;
128663a7246aSmatthias.ringwald         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
1287b3264428SMatthias Ringwald #ifdef ENABLE_CLASSIC
12885774a392SMatthias Ringwald         uint16_t info_type     = signaling_responses[0].data;  // INFORMATION_REQUEST
1289b3264428SMatthias Ringwald         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
1290b3264428SMatthias Ringwald #endif
129109e9d05bSMatthias Ringwald 
1292f53da564S[email protected]         // remove first item before sending (to avoid sending response mutliple times)
1293f53da564S[email protected]         signaling_responses_pending--;
1294f53da564S[email protected]         int i;
1295f53da564S[email protected]         for (i=0; i < signaling_responses_pending; i++){
1296f53da564S[email protected]             memcpy(&signaling_responses[i], &signaling_responses[i+1], sizeof(l2cap_signaling_response_t));
1297f53da564S[email protected]         }
1298f53da564S[email protected] 
1299f53da564S[email protected]         switch (response_code){
130009e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
13012b360848Smatthias.ringwald             case CONNECTION_REQUEST:
1302e74c5f58SMatthias Ringwald                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
13032bd8b7e7S[email protected]                 // also disconnect if result is 0x0003 - security blocked
13044d816277S[email protected]                 if (result == 0x0003){
13052bd8b7e7S[email protected]                     hci_disconnect_security_block(handle);
13064d816277S[email protected]                 }
13072b360848Smatthias.ringwald                 break;
13082b83fb7dSmatthias.ringwald             case ECHO_REQUEST:
13092b83fb7dSmatthias.ringwald                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
13102b83fb7dSmatthias.ringwald                 break;
13112b83fb7dSmatthias.ringwald             case INFORMATION_REQUEST:
13123e64cb44SMatthias Ringwald                 switch (info_type){
13133e64cb44SMatthias Ringwald                     case L2CAP_INFO_TYPE_CONNECTIONLESS_MTU: {
13143b0484b3S[email protected]                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
13153e64cb44SMatthias Ringwald                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(connectionless_mtu), &connectionless_mtu);
13163b0484b3S[email protected]                         }
1317202c8a4cSMatthias Ringwald                         break;
13183e64cb44SMatthias Ringwald                     case L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED: {
13191b9cb13dSMatthias Ringwald                             uint32_t features = l2cap_extended_features_mask();
13203e64cb44SMatthias Ringwald                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(features), &features);
13213b0484b3S[email protected]                         }
1322202c8a4cSMatthias Ringwald                         break;
13233e64cb44SMatthias Ringwald                     case L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED: {
13243b0484b3S[email protected]                             uint8_t map[8];
13253b0484b3S[email protected]                             memset(map, 0, 8);
1326288636a2SMatthias Ringwald                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
13273e64cb44SMatthias Ringwald                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(map), &map);
13283b0484b3S[email protected]                         }
1329202c8a4cSMatthias Ringwald                         break;
13303b0484b3S[email protected]                     default:
13312b83fb7dSmatthias.ringwald                         // all other types are not supported
13323e64cb44SMatthias Ringwald                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 1, 0, NULL);
13333b0484b3S[email protected]                         break;
13342b83fb7dSmatthias.ringwald                 }
13352b83fb7dSmatthias.ringwald                 break;
133663a7246aSmatthias.ringwald             case COMMAND_REJECT:
13375ca8d57bS[email protected]                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
133863f0ac45SMatthias Ringwald                 break;
133909e9d05bSMatthias Ringwald #endif
1340a9a4c409SMatthias Ringwald #ifdef ENABLE_BLE
134163f0ac45SMatthias Ringwald             case LE_CREDIT_BASED_CONNECTION_REQUEST:
134263f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
134363f0ac45SMatthias Ringwald                 break;
134470efece1S[email protected]             case COMMAND_REJECT_LE:
134570efece1S[email protected]                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
134663a7246aSmatthias.ringwald                 break;
134770efece1S[email protected] #endif
13482b83fb7dSmatthias.ringwald             default:
13492b83fb7dSmatthias.ringwald                 // should not happen
13502b83fb7dSmatthias.ringwald                 break;
13512b83fb7dSmatthias.ringwald         }
13522b83fb7dSmatthias.ringwald     }
13532b83fb7dSmatthias.ringwald 
1354959f646aSMatthias Ringwald #if defined(ENABLE_CLASSIC) || defined(ENABLE_BLE)
1355665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
13565774a392SMatthias Ringwald #endif
135709e9d05bSMatthias Ringwald 
13581b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
13591b9cb13dSMatthias Ringwald     // send l2cap information request if neccessary
13601b9cb13dSMatthias Ringwald     hci_connections_get_iterator(&it);
13611b9cb13dSMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
13621b9cb13dSMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
13631b9cb13dSMatthias Ringwald         if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST){
13641b9cb13dSMatthias Ringwald             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
13651b9cb13dSMatthias Ringwald             // send information request for extended features
13661b9cb13dSMatthias Ringwald             uint8_t sig_id = l2cap_next_sig_id();
13673e64cb44SMatthias Ringwald             uint8_t info_type = L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED;
13681b9cb13dSMatthias Ringwald             l2cap_send_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
13691b9cb13dSMatthias Ringwald             return;
13701b9cb13dSMatthias Ringwald         }
13711b9cb13dSMatthias Ringwald     }
13721b9cb13dSMatthias Ringwald #endif
13731b9cb13dSMatthias Ringwald 
137409e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
137543ec931dSMatthias Ringwald     uint8_t  config_options[10];
1376665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1377665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1378baf94f06S[email protected] 
1379665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
138022c29ab4SMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
13812cd0be45Smatthias.ringwald         switch (channel->state){
13822cd0be45Smatthias.ringwald 
1383df3354fcS[email protected]             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1384ad671560S[email protected]             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
1385fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1386a00031e2S[email protected]                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
1387ad671560S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
1388fc64f94aSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
1389ad671560S[email protected]                 }
1390ad671560S[email protected]                 break;
1391ad671560S[email protected] 
139202b22dc4Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1393baf94f06S[email protected]                 if (!hci_can_send_command_packet_now()) break;
139464472d52Smatthias.ringwald                 // send connection request - set state first
139564472d52Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
139602b22dc4Smatthias.ringwald                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
13978f8108aaSmatthias.ringwald                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
139802b22dc4Smatthias.ringwald                 break;
139902b22dc4Smatthias.ringwald 
1400e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
1401fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
140222c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1403fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
1404e7ff783cSmatthias.ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
14059dcb2fb2S[email protected]                 l2cap_stop_rtx(channel);
1406665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1407d3a9df87Smatthias.ringwald                 btstack_memory_l2cap_channel_free(channel);
1408e7ff783cSmatthias.ringwald                 break;
1409e7ff783cSmatthias.ringwald 
1410552d92a1Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
1411fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1412fa8473a4Smatthias.ringwald                 channel->state = L2CAP_STATE_CONFIG;
141328ca2b46S[email protected]                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1414fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
1415552d92a1Smatthias.ringwald                 break;
1416552d92a1Smatthias.ringwald 
14176fdcc387Smatthias.ringwald             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
1418fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
14196fdcc387Smatthias.ringwald                 // success, start l2cap handshake
1420b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
14216fdcc387Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
1422fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
14235932bd7cS[email protected]                 l2cap_start_rtx(channel);
14246fdcc387Smatthias.ringwald                 break;
14256fdcc387Smatthias.ringwald 
1426fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
1427fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
142873cf2b3dSmatthias.ringwald                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
142963a7246aSmatthias.ringwald                     uint16_t flags = 0;
143028ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
143163a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
143263a7246aSmatthias.ringwald                         flags = 1;
143363a7246aSmatthias.ringwald                     } else {
143428ca2b46S[email protected]                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
143563a7246aSmatthias.ringwald                     }
143663a7246aSmatthias.ringwald                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
1437ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1438fc64f94aSMatthias 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);
1439ac8f1300SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1440ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
1441ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1442ac8f1300SMatthias Ringwald                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
14436b99230fSMatthias Ringwald                         uint16_t options_size = l2cap_setup_options_response(channel, config_options);
1444ac8f1300SMatthias 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);
1445ac8f1300SMatthias Ringwald #endif
1446ac8f1300SMatthias Ringwald                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
144763a7246aSmatthias.ringwald                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
14486b99230fSMatthias Ringwald                         uint16_t options_size = l2cap_setup_options_response(channel, config_options);
1449ac8f1300SMatthias 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);
145063a7246aSmatthias.ringwald                     } else {
1451ac8f1300SMatthias Ringwald                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
145263a7246aSmatthias.ringwald                     }
145363a7246aSmatthias.ringwald                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1454fa8473a4Smatthias.ringwald                 }
145573cf2b3dSmatthias.ringwald                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
145628ca2b46S[email protected]                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
145728ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
1458b1988dceSmatthias.ringwald                     channel->local_sig_id = l2cap_next_sig_id();
14596b99230fSMatthias Ringwald                     uint16_t options_size = l2cap_setup_options_request(channel, config_options);
14606dca2a0cSMatthias Ringwald                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options);
14615932bd7cS[email protected]                     l2cap_start_rtx(channel);
1462fa8473a4Smatthias.ringwald                 }
1463fa8473a4Smatthias.ringwald                 if (l2cap_channel_ready_for_open(channel)){
1464552d92a1Smatthias.ringwald                     channel->state = L2CAP_STATE_OPEN;
1465552d92a1Smatthias.ringwald                     l2cap_emit_channel_opened(channel, 0);  // success
1466fa8473a4Smatthias.ringwald                 }
1467552d92a1Smatthias.ringwald                 break;
1468552d92a1Smatthias.ringwald 
1469e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1470fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
147122c29ab4SMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1472fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
14735932bd7cS[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 :)
1474756102d3Smatthias.ringwald                 l2cap_finialize_channel_close(channel);  // -- remove from list
1475e7ff783cSmatthias.ringwald                 break;
1476e7ff783cSmatthias.ringwald 
1477e7ff783cSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1478fc64f94aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1479b1988dceSmatthias.ringwald                 channel->local_sig_id = l2cap_next_sig_id();
14802cd0be45Smatthias.ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1481fc64f94aSMatthias Ringwald                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
14822cd0be45Smatthias.ringwald                 break;
14832cd0be45Smatthias.ringwald             default:
14842cd0be45Smatthias.ringwald                 break;
14852cd0be45Smatthias.ringwald         }
148638f62777SMatthias Ringwald 
148738f62777SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
148838f62777SMatthias Ringwald         // send s-frame to acknowledge received packets
148938f62777SMatthias Ringwald         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
1490675e6881SMatthias Ringwald 
1491675e6881SMatthias Ringwald         if (channel->tx_send_index != channel->tx_write_index){
1492212b6be2SMatthias Ringwald             // check remote tx window
149394301352SMatthias Ringwald             log_info("unacknowledged_packets %u, remote tx window size %u", channel->unacked_frames, channel->remote_tx_window_size);
149494301352SMatthias Ringwald             if (channel->unacked_frames < channel->remote_tx_window_size){
149594301352SMatthias Ringwald                 channel->unacked_frames++;
1496675e6881SMatthias Ringwald                 int index = channel->tx_send_index;
1497675e6881SMatthias Ringwald                 channel->tx_send_index++;
1498675e6881SMatthias Ringwald                 if (channel->tx_send_index >= channel->num_tx_buffers){
1499675e6881SMatthias Ringwald                     channel->tx_send_index = 0;
1500675e6881SMatthias Ringwald                 }
15017b7901d8SMatthias Ringwald                 l2cap_ertm_send_information_frame(channel, index, 0);   // final = 0
1502675e6881SMatthias Ringwald                 continue;
1503675e6881SMatthias Ringwald             }
1504212b6be2SMatthias Ringwald         }
1505675e6881SMatthias Ringwald 
1506d84e866fSMatthias Ringwald         if (channel->send_supervisor_frame_receiver_ready){
150778cd8a22SMatthias Ringwald             channel->send_supervisor_frame_receiver_ready = 0;
1508d2afdd38SMatthias Ringwald             log_info("Send S-Frame: RR %u, final %u", channel->req_seq, channel->set_final_bit_after_packet_with_poll_bit_set);
1509d2afdd38SMatthias 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);
1510d2afdd38SMatthias Ringwald             channel->set_final_bit_after_packet_with_poll_bit_set = 0;
151138f62777SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
1512675e6881SMatthias Ringwald             continue;
151338f62777SMatthias Ringwald         }
151462041d70SMatthias Ringwald         if (channel->send_supervisor_frame_receiver_ready_poll){
151578cd8a22SMatthias Ringwald             channel->send_supervisor_frame_receiver_ready_poll = 0;
151662041d70SMatthias Ringwald             log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
151762041d70SMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
151862041d70SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
151962041d70SMatthias Ringwald             continue;
152062041d70SMatthias Ringwald         }
15218f1c9639SMatthias Ringwald         if (channel->send_supervisor_frame_receiver_not_ready){
152278cd8a22SMatthias Ringwald             channel->send_supervisor_frame_receiver_not_ready = 0;
15238f1c9639SMatthias Ringwald             log_info("Send S-Frame: RNR %u", channel->req_seq);
15248f1c9639SMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
15258f1c9639SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
15268f1c9639SMatthias Ringwald             continue;
15278f1c9639SMatthias Ringwald         }
1528c7309e8dSMatthias Ringwald         if (channel->send_supervisor_frame_reject){
1529c7309e8dSMatthias Ringwald             channel->send_supervisor_frame_reject = 0;
1530c7309e8dSMatthias Ringwald             log_info("Send S-Frame: REJ %u", channel->req_seq);
1531c7309e8dSMatthias Ringwald             uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 0, 0, channel->req_seq);
1532c7309e8dSMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
1533c7309e8dSMatthias Ringwald             continue;
1534c7309e8dSMatthias Ringwald         }
1535df2191a7SMatthias Ringwald         if (channel->send_supervisor_frame_selective_reject){
1536df2191a7SMatthias Ringwald             channel->send_supervisor_frame_selective_reject = 0;
1537df2191a7SMatthias Ringwald             log_info("Send S-Frame: SREJ %u", channel->expected_tx_seq);
1538f85ade6bSMatthias 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);
1539f85ade6bSMatthias Ringwald             channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1540df2191a7SMatthias Ringwald             l2cap_ertm_send_supervisor_frame(channel, control);
1541df2191a7SMatthias Ringwald             continue;
1542df2191a7SMatthias Ringwald         }
15437b7901d8SMatthias Ringwald 
15447b7901d8SMatthias Ringwald         if (channel->srej_active){
15457b7901d8SMatthias Ringwald             int i;
15467b7901d8SMatthias Ringwald             for (i=0;i<channel->num_tx_buffers;i++){
15477b7901d8SMatthias Ringwald                 l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
15487b7901d8SMatthias Ringwald                 if (tx_state->retransmission_requested) {
15497b7901d8SMatthias Ringwald                     tx_state->retransmission_requested = 0;
1550d2afdd38SMatthias Ringwald                     uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set;
1551d2afdd38SMatthias Ringwald                     channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1552d2afdd38SMatthias Ringwald                     l2cap_ertm_send_information_frame(channel, i, final);
15537b7901d8SMatthias Ringwald                     break;
15547b7901d8SMatthias Ringwald                 }
15557b7901d8SMatthias Ringwald             }
15567b7901d8SMatthias Ringwald             if (i == channel->num_tx_buffers){
15577b7901d8SMatthias Ringwald                 // no retransmission request found
15587b7901d8SMatthias Ringwald                 channel->srej_active = 0;
15597b7901d8SMatthias Ringwald             } else {
15607b7901d8SMatthias Ringwald                 // packet was sent
15617b7901d8SMatthias Ringwald                 continue;
15627b7901d8SMatthias Ringwald             }
15637b7901d8SMatthias Ringwald         }
156438f62777SMatthias Ringwald #endif
156538f62777SMatthias Ringwald 
15662cd0be45Smatthias.ringwald     }
156709e9d05bSMatthias Ringwald #endif
1568da886c03S[email protected] 
1569cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
1570efedfb4cSMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
1571efedfb4cSMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
15727f107edaSMatthias Ringwald         uint8_t  * acl_buffer;
15737f107edaSMatthias Ringwald         uint8_t  * l2cap_payload;
15747f107edaSMatthias Ringwald         uint16_t pos;
15757f107edaSMatthias Ringwald         uint16_t payload_size;
1576efedfb4cSMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1577efedfb4cSMatthias Ringwald         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1578efedfb4cSMatthias Ringwald         switch (channel->state){
15795cb87675SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
15805cb87675SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
15815cb87675SMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
15825cb87675SMatthias Ringwald                 // le psm, source cid, mtu, mps, initial credits
15831b8b8d05SMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
158463f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
158563f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
158663f0ac45SMatthias 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, 23, channel->credits_incoming);
15875cb87675SMatthias Ringwald                 break;
158823017473SMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
158923017473SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
159023017473SMatthias Ringwald                 // TODO: support larger MPS
159123017473SMatthias Ringwald                 channel->state = L2CAP_STATE_OPEN;
159263f0ac45SMatthias Ringwald                 channel->credits_incoming =  channel->new_credits_incoming;
159363f0ac45SMatthias Ringwald                 channel->new_credits_incoming = 0;
159463f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->local_mtu, 23, channel->credits_incoming, 0);
159564e11ca9SMatthias Ringwald                 // notify client
159644276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0);
159723017473SMatthias Ringwald                 break;
1598e7d0c9aaSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
1599e7d0c9aaSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1600e7d0c9aaSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
160163f0ac45SMatthias Ringwald                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
1602e7d0c9aaSMatthias Ringwald                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1603e7d0c9aaSMatthias Ringwald                 l2cap_stop_rtx(channel);
1604e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
1605e7d0c9aaSMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
1606e7d0c9aaSMatthias Ringwald                 break;
16077f107edaSMatthias Ringwald             case L2CAP_STATE_OPEN:
160885aeef60SMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
160985aeef60SMatthias Ringwald 
161085aeef60SMatthias Ringwald                 // send credits
161185aeef60SMatthias Ringwald                 if (channel->new_credits_incoming){
161285aeef60SMatthias Ringwald                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
161385aeef60SMatthias Ringwald                     channel->local_sig_id = l2cap_next_sig_id();
161485aeef60SMatthias Ringwald                     uint16_t new_credits = channel->new_credits_incoming;
161585aeef60SMatthias Ringwald                     channel->new_credits_incoming = 0;
161685aeef60SMatthias Ringwald                     channel->credits_incoming += new_credits;
161785aeef60SMatthias Ringwald                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
161885aeef60SMatthias Ringwald                     break;
161985aeef60SMatthias Ringwald                 }
162085aeef60SMatthias Ringwald 
162185aeef60SMatthias Ringwald                 // send data
16227f107edaSMatthias Ringwald                 if (!channel->send_sdu_buffer) break;
16237f107edaSMatthias Ringwald                 if (!channel->credits_outgoing) break;
162485aeef60SMatthias Ringwald 
16257f107edaSMatthias Ringwald                 // send part of SDU
16267f107edaSMatthias Ringwald                 hci_reserve_packet_buffer();
16277f107edaSMatthias Ringwald                 acl_buffer = hci_get_outgoing_packet_buffer();
16287f107edaSMatthias Ringwald                 l2cap_payload = acl_buffer + 8;
16297f107edaSMatthias Ringwald                 pos = 0;
16307f107edaSMatthias Ringwald                 if (!channel->send_sdu_pos){
16317f107edaSMatthias Ringwald                     // store SDU len
16327f107edaSMatthias Ringwald                     channel->send_sdu_pos += 2;
16337f107edaSMatthias Ringwald                     little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
16347f107edaSMatthias Ringwald                     pos += 2;
16357f107edaSMatthias Ringwald                 }
16367f107edaSMatthias Ringwald                 payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
163785aeef60SMatthias Ringwald                 log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
16387f107edaSMatthias Ringwald                 memcpy(&l2cap_payload[pos], &channel->send_sdu_buffer[channel->send_sdu_pos-2], payload_size); // -2 for virtual SDU len
16397f107edaSMatthias Ringwald                 pos += payload_size;
16407f107edaSMatthias Ringwald                 channel->send_sdu_pos += payload_size;
1641f511cefaSMatthias Ringwald                 l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
16427f107edaSMatthias Ringwald                 // done
16437f107edaSMatthias Ringwald 
164485aeef60SMatthias Ringwald                 channel->credits_outgoing--;
16457f107edaSMatthias Ringwald 
16467f107edaSMatthias Ringwald                 if (channel->send_sdu_pos >= channel->send_sdu_len + 2){
16477f107edaSMatthias Ringwald                     channel->send_sdu_buffer = NULL;
164844276248SMatthias Ringwald                     // send done event
164944276248SMatthias Ringwald                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
165044276248SMatthias Ringwald                     // inform about can send now
165144276248SMatthias Ringwald                     l2cap_le_notify_channel_can_send(channel);
16527f107edaSMatthias Ringwald                 }
16537f107edaSMatthias Ringwald                 hci_send_acl_packet_buffer(8 + pos);
16547f107edaSMatthias Ringwald                 break;
1655828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1656828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1657828a7f7aSMatthias Ringwald                 channel->local_sig_id = l2cap_next_sig_id();
1658828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1659828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1660828a7f7aSMatthias Ringwald                 break;
1661828a7f7aSMatthias Ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1662828a7f7aSMatthias Ringwald                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1663828a7f7aSMatthias Ringwald                 channel->state = L2CAP_STATE_INVALID;
1664828a7f7aSMatthias Ringwald                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1665828a7f7aSMatthias Ringwald                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
1666828a7f7aSMatthias Ringwald                 break;
1667efedfb4cSMatthias Ringwald             default:
1668efedfb4cSMatthias Ringwald                 break;
1669efedfb4cSMatthias Ringwald         }
1670efedfb4cSMatthias Ringwald     }
167109e9d05bSMatthias Ringwald #endif
1672efedfb4cSMatthias Ringwald 
167309e9d05bSMatthias Ringwald #ifdef ENABLE_BLE
1674da886c03S[email protected]     // send l2cap con paramter update if necessary
1675da886c03S[email protected]     hci_connections_get_iterator(&it);
1676665d90f2SMatthias Ringwald     while(btstack_linked_list_iterator_has_next(&it)){
1677665d90f2SMatthias Ringwald         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
16785d14fa8fSMatthias Ringwald         if (connection->address_type != BD_ADDR_TYPE_LE_PUBLIC && connection->address_type != BD_ADDR_TYPE_LE_RANDOM) continue;
1679b68d7bc3SMatthias Ringwald         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
1680da886c03S[email protected]         switch (connection->le_con_parameter_update_state){
1681b68d7bc3SMatthias Ringwald             case CON_PARAMETER_UPDATE_SEND_REQUEST:
1682b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1683b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, connection->le_con_param_update_identifier,
1684b68d7bc3SMatthias Ringwald                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
1685b68d7bc3SMatthias Ringwald                 break;
1686da886c03S[email protected]             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
1687b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
1688b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
1689da886c03S[email protected]                 break;
1690da886c03S[email protected]             case CON_PARAMETER_UPDATE_DENY:
1691b68d7bc3SMatthias Ringwald                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1692b68d7bc3SMatthias Ringwald                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
1693da886c03S[email protected]                 break;
1694da886c03S[email protected]             default:
1695da886c03S[email protected]                 break;
1696da886c03S[email protected]         }
1697da886c03S[email protected]     }
16984d7157c3S[email protected] #endif
1699da886c03S[email protected] 
170022c29ab4SMatthias Ringwald     // log_info("l2cap_run: exit");
17012cd0be45Smatthias.ringwald }
17022cd0be45Smatthias.ringwald 
170309e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1704fc64f94aSMatthias Ringwald static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
17052df5dadcS[email protected]     if (channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE || channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION) {
17065533f01eS[email protected]         log_info("l2cap_handle_connection_complete expected state");
17072df5dadcS[email protected]         // success, start l2cap handshake
1708fc64f94aSMatthias Ringwald         channel->con_handle = con_handle;
17092df5dadcS[email protected]         // check remote SSP feature first
17102df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
17112df5dadcS[email protected]     }
17122df5dadcS[email protected] }
17132df5dadcS[email protected] 
17141b9cb13dSMatthias Ringwald static void l2cap_ready_to_connect(l2cap_channel_t * channel){
17151b9cb13dSMatthias Ringwald 
17161b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
171727e0774aSMatthias Ringwald     // assumption: outgoing connection
17181b9cb13dSMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
17191b9cb13dSMatthias Ringwald     if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
17201b9cb13dSMatthias Ringwald         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
17211b9cb13dSMatthias Ringwald         channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
17221b9cb13dSMatthias Ringwald         return;
17231b9cb13dSMatthias Ringwald     }
17241b9cb13dSMatthias Ringwald #endif
17251b9cb13dSMatthias Ringwald 
17261b9cb13dSMatthias Ringwald     // fine, go ahead
17271b9cb13dSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
17281b9cb13dSMatthias Ringwald }
17291b9cb13dSMatthias Ringwald 
17302df5dadcS[email protected] static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
17312df5dadcS[email protected]     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
17322df5dadcS[email protected] 
17332df5dadcS[email protected]     // we have been waiting for remote supported features, if both support SSP,
1734ac301f95S[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));
1735fc64f94aSMatthias Ringwald     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
17362df5dadcS[email protected]         // request security level 2
17372df5dadcS[email protected]         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
1738dfce2622SMilanka Ringwald         channel->required_security_level = LEVEL_2;
1739fc64f94aSMatthias Ringwald         gap_request_security_level(channel->con_handle, LEVEL_2);
17402df5dadcS[email protected]         return;
17412df5dadcS[email protected]     }
17421b9cb13dSMatthias Ringwald 
17431b9cb13dSMatthias Ringwald     l2cap_ready_to_connect(channel);
17442df5dadcS[email protected] }
174509e9d05bSMatthias Ringwald #endif
17462df5dadcS[email protected] 
174709e9d05bSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
1748da144af5SMatthias Ringwald static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, bd_addr_t address, bd_addr_type_t address_type,
1749da144af5SMatthias Ringwald     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
1750da144af5SMatthias Ringwald 
1751da144af5SMatthias Ringwald     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1752da144af5SMatthias Ringwald     if (!channel) {
1753da144af5SMatthias Ringwald         return NULL;
1754da144af5SMatthias Ringwald     }
1755da144af5SMatthias Ringwald 
1756da144af5SMatthias Ringwald      // Init memory (make valgrind happy)
1757da144af5SMatthias Ringwald     memset(channel, 0, sizeof(l2cap_channel_t));
1758da144af5SMatthias Ringwald 
1759da144af5SMatthias Ringwald     // fill in
1760da144af5SMatthias Ringwald     channel->packet_handler = packet_handler;
1761da144af5SMatthias Ringwald     bd_addr_copy(channel->address, address);
1762da144af5SMatthias Ringwald     channel->address_type = address_type;
1763da144af5SMatthias Ringwald     channel->psm = psm;
1764da144af5SMatthias Ringwald     channel->local_mtu  = local_mtu;
1765b37a9357SMatthias Ringwald     channel->remote_mtu = L2CAP_DEFAULT_MTU;
1766da144af5SMatthias Ringwald     channel->required_security_level = security_level;
1767da144af5SMatthias Ringwald 
1768da144af5SMatthias Ringwald     //
1769da144af5SMatthias Ringwald     channel->local_cid = l2cap_next_local_cid();
1770da144af5SMatthias Ringwald     channel->con_handle = 0;
1771da144af5SMatthias Ringwald 
1772da144af5SMatthias Ringwald     // set initial state
1773da144af5SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
1774da144af5SMatthias Ringwald     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
1775da144af5SMatthias Ringwald     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
1776da144af5SMatthias Ringwald     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
177738f62777SMatthias Ringwald 
1778da144af5SMatthias Ringwald     return channel;
1779da144af5SMatthias Ringwald }
178009e9d05bSMatthias Ringwald #endif
178109e9d05bSMatthias Ringwald 
178209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
1783da144af5SMatthias Ringwald 
17849077cb15SMatthias Ringwald /**
17859077cb15SMatthias Ringwald  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
17869077cb15SMatthias Ringwald  * @param packet_handler
17879077cb15SMatthias Ringwald  * @param address
17889077cb15SMatthias Ringwald  * @param psm
17899077cb15SMatthias Ringwald  * @param mtu
17909077cb15SMatthias Ringwald  * @param local_cid
17919077cb15SMatthias Ringwald  */
17929077cb15SMatthias Ringwald 
17939d139fbaSMatthias 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){
17949d139fbaSMatthias Ringwald     // limit MTU to the size of our outtgoing HCI buffer
17959d139fbaSMatthias Ringwald     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1796da144af5SMatthias Ringwald 
17979d139fbaSMatthias 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);
1798da144af5SMatthias Ringwald 
1799da144af5SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, address, BD_ADDR_TYPE_CLASSIC, psm, local_mtu, LEVEL_0);
1800fc64f94aSMatthias Ringwald     if (!channel) {
18019077cb15SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
18029077cb15SMatthias Ringwald     }
18039077cb15SMatthias Ringwald 
18041b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
18051b9cb13dSMatthias Ringwald     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
18061b9cb13dSMatthias Ringwald #endif
18071b9cb13dSMatthias Ringwald 
18089077cb15SMatthias Ringwald     // add to connections list
1809fc64f94aSMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
18109077cb15SMatthias Ringwald 
18119077cb15SMatthias Ringwald     // store local_cid
18129077cb15SMatthias Ringwald     if (out_local_cid){
1813fc64f94aSMatthias Ringwald        *out_local_cid = channel->local_cid;
18149077cb15SMatthias Ringwald     }
18159077cb15SMatthias Ringwald 
18169077cb15SMatthias Ringwald     // check if hci connection is already usable
18179077cb15SMatthias Ringwald     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_CLASSIC);
18189077cb15SMatthias Ringwald     if (conn){
1819add0254bSMatthias Ringwald         log_info("l2cap_create_channel, hci connection already exists");
1820fc64f94aSMatthias Ringwald         l2cap_handle_connection_complete(conn->con_handle, channel);
18219077cb15SMatthias Ringwald         // check if remote supported fearures are already received
18229077cb15SMatthias Ringwald         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
1823fc64f94aSMatthias Ringwald             l2cap_handle_remote_supported_features_received(channel);
18249077cb15SMatthias Ringwald         }
18259077cb15SMatthias Ringwald     }
18269077cb15SMatthias Ringwald 
18279077cb15SMatthias Ringwald     l2cap_run();
18289077cb15SMatthias Ringwald 
18299077cb15SMatthias Ringwald     return 0;
18309077cb15SMatthias Ringwald }
18319077cb15SMatthias Ringwald 
1832ce8f182eSMatthias Ringwald void
1833ce8f182eSMatthias Ringwald l2cap_disconnect(uint16_t local_cid, uint8_t reason){
1834e0abb8e7S[email protected]     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
1835b35f641cSmatthias.ringwald     // find channel for local_cid
1836b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1837f62db1e3Smatthias.ringwald     if (channel) {
1838e7ff783cSmatthias.ringwald         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1839f62db1e3Smatthias.ringwald     }
18402cd0be45Smatthias.ringwald     // process
18412cd0be45Smatthias.ringwald     l2cap_run();
184243625864Smatthias.ringwald }
18431e6aba47Smatthias.ringwald 
1844afde0c52Smatthias.ringwald static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
1845ceec418aSMatthias Ringwald     // mark all channels before emitting open events as these could trigger new connetion requests to the same device
1846665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1847665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1848665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1849665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1850058e3d6bSMatthias Ringwald         if ( bd_addr_cmp( channel->address, address) != 0) continue;
1851c22aecc9S[email protected]         // channel for this address found
1852c22aecc9S[email protected]         switch (channel->state){
1853c22aecc9S[email protected]             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
1854c22aecc9S[email protected]             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1855ceec418aSMatthias Ringwald                 channel->state = L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD;
1856c22aecc9S[email protected]                 break;
1857c22aecc9S[email protected]             default:
1858c22aecc9S[email protected]                 break;
1859afde0c52Smatthias.ringwald         }
1860afde0c52Smatthias.ringwald     }
1861ceec418aSMatthias Ringwald     // emit and free marked entries. restart loop to deal with list changes
1862ceec418aSMatthias Ringwald     int done = 0;
1863ceec418aSMatthias Ringwald     while (!done) {
1864ceec418aSMatthias Ringwald         done = 1;
1865ceec418aSMatthias Ringwald         btstack_linked_list_iterator_init(&it, &l2cap_channels);
1866ceec418aSMatthias Ringwald         while (btstack_linked_list_iterator_has_next(&it)){
1867ceec418aSMatthias Ringwald             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1868ceec418aSMatthias Ringwald             if (channel->state == L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD){
1869ceec418aSMatthias Ringwald                 done = 0;
1870ceec418aSMatthias Ringwald                 // failure, forward error code
1871ceec418aSMatthias Ringwald                 l2cap_emit_channel_opened(channel, status);
1872ceec418aSMatthias Ringwald                 // discard channel
1873ceec418aSMatthias Ringwald                 l2cap_stop_rtx(channel);
1874ceec418aSMatthias Ringwald                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1875ceec418aSMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
1876ceec418aSMatthias Ringwald                 break;
1877ceec418aSMatthias Ringwald             }
1878ceec418aSMatthias Ringwald         }
1879ceec418aSMatthias Ringwald     }
1880ceec418aSMatthias Ringwald 
1881afde0c52Smatthias.ringwald }
1882afde0c52Smatthias.ringwald 
1883afde0c52Smatthias.ringwald static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
1884665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
1885665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1886665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
1887665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1888058e3d6bSMatthias Ringwald         if ( ! bd_addr_cmp( channel->address, address) ){
18892df5dadcS[email protected]             l2cap_handle_connection_complete(handle, channel);
1890afde0c52Smatthias.ringwald         }
1891afde0c52Smatthias.ringwald     }
18926fdcc387Smatthias.ringwald     // process
18936fdcc387Smatthias.ringwald     l2cap_run();
1894afde0c52Smatthias.ringwald }
189509e9d05bSMatthias Ringwald #endif
1896b448a0e7Smatthias.ringwald 
189733c40538SMatthias Ringwald static void l2cap_notify_channel_can_send(void){
189809e9d05bSMatthias Ringwald 
189909e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
190033c40538SMatthias Ringwald     btstack_linked_list_iterator_t it;
190133c40538SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
190233c40538SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
190333c40538SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
190433c40538SMatthias Ringwald         if (!channel->waiting_for_can_send_now) continue;
1905fc64f94aSMatthias Ringwald         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
190633c40538SMatthias Ringwald         channel->waiting_for_can_send_now = 0;
190734e7e577SMatthias Ringwald         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
190833c40538SMatthias Ringwald     }
190909e9d05bSMatthias Ringwald #endif
191044276248SMatthias Ringwald 
191108dc6394SMatthias Ringwald #if 1
191208dc6394SMatthias Ringwald     if (fixed_channel_head_index != FIXED_CHANNEL_FIFO_INVALID_INDEX){
191308dc6394SMatthias Ringwald         int can_send = 0;
19146bd7c69dSMatthias Ringwald         int remove_entry = 1;
191508dc6394SMatthias Ringwald         uint8_t i = fixed_channel_head_index;
191608dc6394SMatthias Ringwald         if (fixed_channels[i].callback && fixed_channels[i].waiting_for_can_send_now){
191708dc6394SMatthias Ringwald             if (l2cap_fixed_channel_table_index_is_le(i)){
191808dc6394SMatthias Ringwald #ifdef ENABLE_BLE
191908dc6394SMatthias Ringwald                 can_send = hci_can_send_acl_le_packet_now();
19206bd7c69dSMatthias Ringwald                 remove_entry = can_send;
192108dc6394SMatthias Ringwald #endif
192208dc6394SMatthias Ringwald             } else {
192308dc6394SMatthias Ringwald #ifdef ENABLE_CLASSIC
192408dc6394SMatthias Ringwald                 can_send = hci_can_send_acl_classic_packet_now();
19256bd7c69dSMatthias Ringwald                 remove_entry = can_send;
192608dc6394SMatthias Ringwald #endif
192708dc6394SMatthias Ringwald             }
192808dc6394SMatthias Ringwald         }
19296bd7c69dSMatthias Ringwald         // remove entry
19306bd7c69dSMatthias Ringwald         if (remove_entry){
193108dc6394SMatthias Ringwald             fixed_channels[i].waiting_for_can_send_now = 0;
193208dc6394SMatthias Ringwald             fixed_channel_head_index = fixed_channels[i].next_request;
193308dc6394SMatthias Ringwald             fixed_channels[i].next_request = FIXED_CHANNEL_FIFO_INVALID_INDEX;
193408dc6394SMatthias Ringwald             if (fixed_channel_head_index == FIXED_CHANNEL_FIFO_INVALID_INDEX){
193508dc6394SMatthias Ringwald                 fixed_channel_tail_index = FIXED_CHANNEL_FIFO_INVALID_INDEX;
193608dc6394SMatthias Ringwald             }
19376bd7c69dSMatthias Ringwald         }
19386bd7c69dSMatthias Ringwald         // notify
193908dc6394SMatthias Ringwald         if (can_send) {
194008dc6394SMatthias Ringwald             l2cap_emit_can_send_now(fixed_channels[i].callback, l2cap_fixed_channel_table_channel_id_for_index(i));
194108dc6394SMatthias Ringwald         }
194208dc6394SMatthias Ringwald     }
194308dc6394SMatthias Ringwald #else
19442125de09SMatthias Ringwald     int i;
19452125de09SMatthias Ringwald     for (i=0;i<L2CAP_FIXED_CHANNEL_TABLE_SIZE;i++){
1946773c4106SMatthias Ringwald         if (!fixed_channels[i].callback) continue;
19472125de09SMatthias Ringwald         if (!fixed_channels[i].waiting_for_can_send_now) continue;
194835454696SMatthias Ringwald         int can_send = 0;
194934e7e577SMatthias Ringwald         if (l2cap_fixed_channel_table_index_is_le(i)){
195035454696SMatthias Ringwald #ifdef ENABLE_BLE
195134e7e577SMatthias Ringwald             can_send = hci_can_send_acl_le_packet_now();
195235454696SMatthias Ringwald #endif
195334e7e577SMatthias Ringwald         } else {
195435454696SMatthias Ringwald #ifdef ENABLE_CLASSIC
195534e7e577SMatthias Ringwald             can_send = hci_can_send_acl_classic_packet_now();
195635454696SMatthias Ringwald #endif
195734e7e577SMatthias Ringwald         }
195834e7e577SMatthias Ringwald         if (!can_send) continue;
195934e7e577SMatthias Ringwald         fixed_channels[i].waiting_for_can_send_now = 0;
196034e7e577SMatthias Ringwald         l2cap_emit_can_send_now(fixed_channels[i].callback, l2cap_fixed_channel_table_channel_id_for_index(i));
19612125de09SMatthias Ringwald     }
196208dc6394SMatthias Ringwald 
196308dc6394SMatthias Ringwald #endif
196408dc6394SMatthias Ringwald 
196533c40538SMatthias Ringwald }
196633c40538SMatthias Ringwald 
19672053036dSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
19682053036dSMatthias Ringwald 
19692053036dSMatthias Ringwald static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){
19702053036dSMatthias Ringwald     // open cannot fail for for incoming connections
19712053036dSMatthias Ringwald     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0;
19722053036dSMatthias Ringwald 
19732053036dSMatthias Ringwald     // check state
19742053036dSMatthias Ringwald     switch (channel->state){
19752053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
19762053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
19772053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES:
19782053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
19792053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
19802053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES:
19812053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
19822053036dSMatthias Ringwald         case L2CAP_STATE_CONFIG:
19832053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
19842053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
19852053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE:
1986ceec418aSMatthias Ringwald         case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD:
19872053036dSMatthias Ringwald             return 1;
19882053036dSMatthias Ringwald 
19892053036dSMatthias Ringwald         case L2CAP_STATE_OPEN:
19902053036dSMatthias Ringwald         case L2CAP_STATE_CLOSED:
19912053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES:
19922053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
19932053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY:
19942053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
19952053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
19962053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
19972053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
19982053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
19992053036dSMatthias Ringwald         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
20002053036dSMatthias Ringwald         case L2CAP_STATE_INVALID:
20012053036dSMatthias Ringwald         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
20022053036dSMatthias Ringwald             return 0;
20036aa7d794SMatthias Ringwald         // no default here, to get a warning about new states
20042053036dSMatthias Ringwald     }
20056aa7d794SMatthias Ringwald     // still, the compiler insists on a return value
20066aa7d794SMatthias Ringwald     return 0;
20072053036dSMatthias Ringwald }
20082053036dSMatthias Ringwald 
20092053036dSMatthias Ringwald static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){
20102053036dSMatthias Ringwald     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
20112053036dSMatthias Ringwald         l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
20122053036dSMatthias Ringwald     } else {
20132053036dSMatthias Ringwald         l2cap_emit_channel_closed(channel);
20142053036dSMatthias Ringwald     }
20152053036dSMatthias Ringwald     btstack_memory_l2cap_channel_free(channel);
20162053036dSMatthias Ringwald }
20172053036dSMatthias Ringwald 
20182053036dSMatthias Ringwald #endif
20192053036dSMatthias Ringwald 
20202053036dSMatthias Ringwald 
2021d9a7306aSMatthias Ringwald static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
2022afde0c52Smatthias.ringwald 
20235774a392SMatthias Ringwald     UNUSED(packet_type); // ok: registered with hci_event_callback_registration
20245774a392SMatthias Ringwald     UNUSED(cid);         // ok: there is no channel
20255774a392SMatthias Ringwald     UNUSED(size);        // ok: fixed format events read from HCI buffer
20269ec2630cSMatthias Ringwald 
20275774a392SMatthias Ringwald #ifdef ENABLE_CLASSIC
2028afde0c52Smatthias.ringwald     bd_addr_t address;
20292d00edd4Smatthias.ringwald     int hci_con_used;
20305774a392SMatthias Ringwald #endif
20315774a392SMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
20325774a392SMatthias Ringwald     hci_con_handle_t handle;
203309e9d05bSMatthias Ringwald     btstack_linked_list_iterator_t it;
20345774a392SMatthias Ringwald #endif
2035afde0c52Smatthias.ringwald 
20360e2df43fSMatthias Ringwald     switch(hci_event_packet_get_type(packet)){
2037afde0c52Smatthias.ringwald 
203809e9d05bSMatthias Ringwald         // Notify channel packet handler if they can send now
203909e9d05bSMatthias Ringwald         case HCI_EVENT_TRANSPORT_PACKET_SENT:
204009e9d05bSMatthias Ringwald         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
204109e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
204209e9d05bSMatthias Ringwald             l2cap_notify_channel_can_send();
204309e9d05bSMatthias Ringwald             break;
204409e9d05bSMatthias Ringwald 
204509e9d05bSMatthias Ringwald         case HCI_EVENT_COMMAND_STATUS:
204609e9d05bSMatthias Ringwald             l2cap_run();    // try sending signaling packets first
204709e9d05bSMatthias Ringwald             break;
204809e9d05bSMatthias Ringwald 
204909e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2050afde0c52Smatthias.ringwald         // handle connection complete events
2051afde0c52Smatthias.ringwald         case HCI_EVENT_CONNECTION_COMPLETE:
2052724d70a2SMatthias Ringwald             reverse_bd_addr(&packet[5], address);
2053afde0c52Smatthias.ringwald             if (packet[2] == 0){
2054f8fbdce0SMatthias Ringwald                 handle = little_endian_read_16(packet, 3);
2055afde0c52Smatthias.ringwald                 l2cap_handle_connection_success_for_addr(address, handle);
2056afde0c52Smatthias.ringwald             } else {
2057afde0c52Smatthias.ringwald                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
2058afde0c52Smatthias.ringwald             }
2059afde0c52Smatthias.ringwald             break;
2060afde0c52Smatthias.ringwald 
2061afde0c52Smatthias.ringwald         // handle successful create connection cancel command
2062afde0c52Smatthias.ringwald         case HCI_EVENT_COMMAND_COMPLETE:
2063073bd0faSMatthias Ringwald             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
2064afde0c52Smatthias.ringwald                 if (packet[5] == 0){
2065724d70a2SMatthias Ringwald                     reverse_bd_addr(&packet[6], address);
2066afde0c52Smatthias.ringwald                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
2067afde0c52Smatthias.ringwald                     l2cap_handle_connection_failed_for_addr(address, 0x16);
206803cfbabcSmatthias.ringwald                 }
20691e6aba47Smatthias.ringwald             }
207039d59809Smatthias.ringwald             l2cap_run();    // try sending signaling packets first
207139d59809Smatthias.ringwald             break;
207209e9d05bSMatthias Ringwald #endif
207327a923d0Smatthias.ringwald 
20742053036dSMatthias Ringwald #ifdef L2CAP_USES_CHANNELS
20751e6aba47Smatthias.ringwald         // handle disconnection complete events
2076afde0c52Smatthias.ringwald         case HCI_EVENT_DISCONNECTION_COMPLETE:
2077d0662982SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
20782053036dSMatthias Ringwald             // send l2cap open failed or closed events for all channels on this handle and free them
20792053036dSMatthias Ringwald #ifdef ENABLE_CLASSIC
2080665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2081665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2082665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2083fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
2084665d90f2SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
20852053036dSMatthias Ringwald                 l2cap_stop_rtx(channel);
20862053036dSMatthias Ringwald                 l2cap_handle_hci_disconnect_event(channel);
208727a923d0Smatthias.ringwald             }
208809e9d05bSMatthias Ringwald #endif
2089a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2090991fea48SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2091991fea48SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2092991fea48SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2093991fea48SMatthias Ringwald                 if (channel->con_handle != handle) continue;
2094991fea48SMatthias Ringwald                 btstack_linked_list_iterator_remove(&it);
20952053036dSMatthias Ringwald                 l2cap_handle_hci_disconnect_event(channel);
2096991fea48SMatthias Ringwald             }
2097991fea48SMatthias Ringwald #endif
2098afde0c52Smatthias.ringwald             break;
20992053036dSMatthias Ringwald #endif
2100fcadd0caSmatthias.ringwald 
2101ee091cf1Smatthias.ringwald         // HCI Connection Timeouts
210209e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
2103afde0c52Smatthias.ringwald         case L2CAP_EVENT_TIMEOUT_CHECK:
2104f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
2105bd04d84aSMatthias Ringwald             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
210680ca58a0Smatthias.ringwald             if (hci_authentication_active_for_handle(handle)) break;
21072d00edd4Smatthias.ringwald             hci_con_used = 0;
2108665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2109665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2110665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2111fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
21122d00edd4Smatthias.ringwald                 hci_con_used = 1;
2113c22aecc9S[email protected]                 break;
2114ee091cf1Smatthias.ringwald             }
21152d00edd4Smatthias.ringwald             if (hci_con_used) break;
2116d94d3cafS[email protected]             if (!hci_can_send_command_packet_now()) break;
21179edc8742Smatthias.ringwald             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
2118afde0c52Smatthias.ringwald             break;
2119ee091cf1Smatthias.ringwald 
2120df3354fcS[email protected]         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2121f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 3);
2122665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2123665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2124665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2125fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
21262df5dadcS[email protected]                 l2cap_handle_remote_supported_features_received(channel);
2127df3354fcS[email protected]                 break;
2128df3354fcS[email protected]             }
2129c22aecc9S[email protected]             break;
2130df3354fcS[email protected] 
21315611a760SMatthias Ringwald         case GAP_EVENT_SECURITY_LEVEL:
2132f8fbdce0SMatthias Ringwald             handle = little_endian_read_16(packet, 2);
2133bd63148eS[email protected]             log_info("l2cap - security level update");
2134665d90f2SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2135665d90f2SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
2136665d90f2SMatthias Ringwald                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2137fc64f94aSMatthias Ringwald                 if (channel->con_handle != handle) continue;
21385533f01eS[email protected] 
2139e569dfd9SMatthias Ringwald                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
21405533f01eS[email protected]                 gap_security_level_t required_level = channel->required_security_level;
21415533f01eS[email protected] 
2142dfce2622SMilanka Ringwald                 log_info("channel state %u: actual %u >= required %u?", channel->state, actual_level, required_level);
2143dfce2622SMilanka Ringwald 
2144df3354fcS[email protected]                 switch (channel->state){
2145df3354fcS[email protected]                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
21465533f01eS[email protected]                         if (actual_level >= required_level){
214752606043SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
214852606043SMatthias Ringwald                             // we need to know if ERTM is supported before sending a config response
214952606043SMatthias Ringwald                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
215052606043SMatthias Ringwald                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
215152606043SMatthias Ringwald                             channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
215252606043SMatthias Ringwald #else
2153f85a9399S[email protected]                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
215444276248SMatthias Ringwald                             l2cap_emit_incoming_connection(channel);
215552606043SMatthias Ringwald #endif
21561eb2563eS[email protected]                         } else {
2157775ecc36SMatthias Ringwald                             channel->reason = 0x0003; // security block
21581eb2563eS[email protected]                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
21591eb2563eS[email protected]                         }
2160df3354fcS[email protected]                         break;
2161df3354fcS[email protected] 
2162df3354fcS[email protected]                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
21635533f01eS[email protected]                         if (actual_level >= required_level){
21641b9cb13dSMatthias Ringwald                             l2cap_ready_to_connect(channel);
2165df3354fcS[email protected]                         } else {
2166df3354fcS[email protected]                             // disconnnect, authentication not good enough
2167df3354fcS[email protected]                             hci_disconnect_security_block(handle);
2168df3354fcS[email protected]                         }
2169df3354fcS[email protected]                         break;
2170df3354fcS[email protected] 
2171df3354fcS[email protected]                     default:
2172df3354fcS[email protected]                         break;
2173df3354fcS[email protected]                 }
2174f85a9399S[email protected]             }
2175f85a9399S[email protected]             break;
217609e9d05bSMatthias Ringwald #endif
2177f85a9399S[email protected] 
2178afde0c52Smatthias.ringwald         default:
2179afde0c52Smatthias.ringwald             break;
2180afde0c52Smatthias.ringwald     }
2181afde0c52Smatthias.ringwald 
2182bd63148eS[email protected]     l2cap_run();
21831e6aba47Smatthias.ringwald }
21841e6aba47Smatthias.ringwald 
2185e74c5f58SMatthias 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){
21864cf56b4aSmatthias.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."
21872b360848Smatthias.ringwald     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
21882b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].handle = handle;
21892b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].code = code;
21902b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].sig_id = sig_id;
2191e74c5f58SMatthias Ringwald         signaling_responses[signaling_responses_pending].cid = cid;
21922b360848Smatthias.ringwald         signaling_responses[signaling_responses_pending].data = data;
21932b360848Smatthias.ringwald         signaling_responses_pending++;
21942b360848Smatthias.ringwald         l2cap_run();
21952b360848Smatthias.ringwald     }
21962b360848Smatthias.ringwald }
21972b360848Smatthias.ringwald 
219809e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
219909e9d05bSMatthias Ringwald static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
220009e9d05bSMatthias Ringwald     channel->remote_sig_id = identifier;
220109e9d05bSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
220209e9d05bSMatthias Ringwald     l2cap_run();
220309e9d05bSMatthias Ringwald }
220409e9d05bSMatthias Ringwald 
2205b35f641cSmatthias.ringwald static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
2206645658c9Smatthias.ringwald 
22079da54300S[email protected]     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
2208645658c9Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
2209645658c9Smatthias.ringwald     if (!service) {
2210645658c9Smatthias.ringwald         // 0x0002 PSM not supported
2211e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2212645658c9Smatthias.ringwald         return;
2213645658c9Smatthias.ringwald     }
2214645658c9Smatthias.ringwald 
22155061f3afS[email protected]     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
2216645658c9Smatthias.ringwald     if (!hci_connection) {
22172b360848Smatthias.ringwald         //
22189da54300S[email protected]         log_error("no hci_connection for handle %u", handle);
2219645658c9Smatthias.ringwald         return;
2220645658c9Smatthias.ringwald     }
22212bd8b7e7S[email protected] 
2222645658c9Smatthias.ringwald     // alloc structure
22239da54300S[email protected]     // log_info("l2cap_handle_connection_request register channel");
2224da144af5SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, hci_connection->address, BD_ADDR_TYPE_CLASSIC,
2225da144af5SMatthias Ringwald     psm, service->mtu, service->required_security_level);
22262b360848Smatthias.ringwald     if (!channel){
22272b360848Smatthias.ringwald         // 0x0004 No resources available
2228e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
22292b360848Smatthias.ringwald         return;
22302b360848Smatthias.ringwald     }
2231da144af5SMatthias Ringwald 
2232fc64f94aSMatthias Ringwald     channel->con_handle = handle;
2233b35f641cSmatthias.ringwald     channel->remote_cid = source_cid;
2234b1988dceSmatthias.ringwald     channel->remote_sig_id = sig_id;
2235645658c9Smatthias.ringwald 
2236f53da564S[email protected]     // limit local mtu to max acl packet length - l2cap header
22372985cb84Smatthias.ringwald     if (channel->local_mtu > l2cap_max_mtu()) {
22382985cb84Smatthias.ringwald         channel->local_mtu = l2cap_max_mtu();
22399775e25bSmatthias.ringwald     }
22409775e25bSmatthias.ringwald 
2241645658c9Smatthias.ringwald     // set initial state
2242df3354fcS[email protected]     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
2243a24785d0SMatthias Ringwald     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
2244e405ae81Smatthias.ringwald 
2245645658c9Smatthias.ringwald     // add to connections list
2246665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
2247645658c9Smatthias.ringwald 
2248f85a9399S[email protected]     // assert security requirements
22491eb2563eS[email protected]     gap_request_security_level(handle, channel->required_security_level);
2250e405ae81Smatthias.ringwald }
2251645658c9Smatthias.ringwald 
2252ce8f182eSMatthias Ringwald void l2cap_accept_connection(uint16_t local_cid){
2253e0abb8e7S[email protected]     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
2254b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2255e405ae81Smatthias.ringwald     if (!channel) {
2256ce8f182eSMatthias Ringwald         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
2257e405ae81Smatthias.ringwald         return;
2258e405ae81Smatthias.ringwald     }
2259e405ae81Smatthias.ringwald 
226043ec931dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
226143ec931dSMatthias Ringwald     // configure L2CAP Basic mode
226243ec931dSMatthias Ringwald     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
226343ec931dSMatthias Ringwald #endif
226443ec931dSMatthias Ringwald 
2265552d92a1Smatthias.ringwald     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
2266e405ae81Smatthias.ringwald 
2267552d92a1Smatthias.ringwald     // process
2268552d92a1Smatthias.ringwald     l2cap_run();
2269e405ae81Smatthias.ringwald }
2270645658c9Smatthias.ringwald 
22717ef6a7bbSMatthias Ringwald void l2cap_decline_connection(uint16_t local_cid){
22727ef6a7bbSMatthias Ringwald     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
2273b35f641cSmatthias.ringwald     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
2274e405ae81Smatthias.ringwald     if (!channel) {
2275ce8f182eSMatthias Ringwald         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
2276e405ae81Smatthias.ringwald         return;
2277e405ae81Smatthias.ringwald     }
2278e7ff783cSmatthias.ringwald     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
22797ef6a7bbSMatthias Ringwald     channel->reason = 0x04; // no resources available
2280e7ff783cSmatthias.ringwald     l2cap_run();
2281645658c9Smatthias.ringwald }
2282645658c9Smatthias.ringwald 
2283e9cfb251SMatthias Ringwald // @pre command len is valid, see check in l2cap_signaling_handler_channel
22847f02f414SMatthias Ringwald static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
2285b1988dceSmatthias.ringwald 
2286*fcb125edSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2287*fcb125edSMatthias Ringwald     uint8_t use_fcs = 1;
2288*fcb125edSMatthias Ringwald #endif
2289*fcb125edSMatthias Ringwald 
2290b1988dceSmatthias.ringwald     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2291b1988dceSmatthias.ringwald 
2292f8fbdce0SMatthias Ringwald     uint16_t flags = little_endian_read_16(command, 6);
229363a7246aSmatthias.ringwald     if (flags & 1) {
229463a7246aSmatthias.ringwald         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
229563a7246aSmatthias.ringwald     }
229663a7246aSmatthias.ringwald 
22972784b77dSmatthias.ringwald     // accept the other's configuration options
2298f8fbdce0SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
22993de7c0caSmatthias.ringwald     uint16_t pos     = 8;
23003de7c0caSmatthias.ringwald     while (pos < end_pos){
230163a7246aSmatthias.ringwald         uint8_t option_hint = command[pos] >> 7;
230263a7246aSmatthias.ringwald         uint8_t option_type = command[pos] & 0x7f;
23033844aeadSMatthias Ringwald         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
230463a7246aSmatthias.ringwald         pos++;
23051dc511deSmatthias.ringwald         uint8_t length = command[pos++];
23061dc511deSmatthias.ringwald         // MTU { type(8): 1, len(8):2, MTU(16) }
2307671fb338SMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT && length == 2){
2308f8fbdce0SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, pos);
23093844aeadSMatthias Ringwald             log_info("Remote MTU %u", channel->remote_mtu);
23109d139fbaSMatthias Ringwald             if (channel->remote_mtu > l2cap_max_mtu()){
23119d139fbaSMatthias Ringwald                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
23129d139fbaSMatthias Ringwald                 channel->remote_mtu = l2cap_max_mtu();
23139d139fbaSMatthias Ringwald             }
231463a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
231563a7246aSmatthias.ringwald         }
23160fe7a9d0S[email protected]         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
2317671fb338SMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT && length == 2){
2318f8fbdce0SMatthias Ringwald             channel->flush_timeout = little_endian_read_16(command, pos);
23193844aeadSMatthias Ringwald             log_info("Flush timeout: %u ms", channel->flush_timeout);
23200fe7a9d0S[email protected]         }
2321f2fa388dSMatthias Ringwald 
23226dca2a0cSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
23236dca2a0cSMatthias Ringwald         // Retransmission and Flow Control Option
2324671fb338SMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
23253232a1c6SMatthias Ringwald             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
2326ac8f1300SMatthias Ringwald             switch(channel->mode){
2327ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
232825cd60d3SMatthias Ringwald                     // Store remote config
2329bbc0a9e7SMatthias Ringwald                     channel->remote_tx_window_size = command[pos+1];
2330bbc0a9e7SMatthias Ringwald                     channel->remote_max_transmit   = command[pos+2];
2331bbc0a9e7SMatthias Ringwald                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
2332bbc0a9e7SMatthias Ringwald                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
23333844aeadSMatthias Ringwald                     channel->remote_mps = little_endian_read_16(command, pos + 7);
23343844aeadSMatthias Ringwald                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
2335bbc0a9e7SMatthias Ringwald                         channel->remote_tx_window_size,
2336bbc0a9e7SMatthias Ringwald                         channel->remote_max_transmit,
2337bbc0a9e7SMatthias Ringwald                         channel->remote_retransmission_timeout_ms,
23383844aeadSMatthias Ringwald                         channel->remote_monitor_timeout_ms,
23393844aeadSMatthias Ringwald                         channel->remote_mps);
234025cd60d3SMatthias Ringwald                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
234125cd60d3SMatthias Ringwald                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
234225cd60d3SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2343ac8f1300SMatthias Ringwald                     } else {
2344ac8f1300SMatthias Ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
2345ac8f1300SMatthias Ringwald                     }
2346ac8f1300SMatthias Ringwald                     break;
2347ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
2348ac8f1300SMatthias Ringwald                     switch (mode){
2349ac8f1300SMatthias Ringwald                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2350ac8f1300SMatthias Ringwald                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
2351ac8f1300SMatthias Ringwald                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
2352ac8f1300SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2353ac8f1300SMatthias Ringwald                             }
2354ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
2355ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
2356ac8f1300SMatthias Ringwald                             break;
2357ac8f1300SMatthias Ringwald                         default: // case L2CAP_CHANNEL_MODE_BASIC:
2358ac8f1300SMatthias Ringwald                             // TODO store and evaluate configuration
2359ac8f1300SMatthias Ringwald                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
2360ac8f1300SMatthias Ringwald                             break;
2361ac8f1300SMatthias Ringwald                     }
2362ac8f1300SMatthias Ringwald                     break;
2363ac8f1300SMatthias Ringwald                 default:
2364ac8f1300SMatthias Ringwald                     break;
2365ac8f1300SMatthias Ringwald             }
23663232a1c6SMatthias Ringwald         }
23676574158aSMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
2368*fcb125edSMatthias Ringwald             use_fcs = command[pos];
23696574158aSMatthias Ringwald         }
23706dca2a0cSMatthias Ringwald #endif
237163a7246aSmatthias.ringwald         // check for unknown options
2372671fb338SMatthias Ringwald         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
2373c177a91cS[email protected]             log_info("l2cap cid %u, unknown options", channel->local_cid);
237463a7246aSmatthias.ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
23751dc511deSmatthias.ringwald         }
23761dc511deSmatthias.ringwald         pos += length;
23771dc511deSmatthias.ringwald     }
2378*fcb125edSMatthias Ringwald 
2379*fcb125edSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2380*fcb125edSMatthias Ringwald         // "FCS" has precedence over "No FCS"
2381*fcb125edSMatthias Ringwald         uint8_t update = channel->fcs_option || use_fcs;
2382*fcb125edSMatthias Ringwald         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
2383*fcb125edSMatthias Ringwald         channel->fcs_option = update;
2384*fcb125edSMatthias Ringwald #endif
23852784b77dSmatthias.ringwald }
23862784b77dSmatthias.ringwald 
2387e9cfb251SMatthias Ringwald // @pre command len is valid, see check in l2cap_signaling_handler_channel
2388f2fa388dSMatthias Ringwald static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
2389f2fa388dSMatthias Ringwald     log_info("l2cap_signaling_handle_configure_response");
23903232a1c6SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
23913232a1c6SMatthias Ringwald     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2392f2fa388dSMatthias Ringwald     uint16_t pos     = 10;
23933232a1c6SMatthias Ringwald     while (pos < end_pos){
23943232a1c6SMatthias Ringwald         uint8_t option_hint = command[pos] >> 7;
23953232a1c6SMatthias Ringwald         uint8_t option_type = command[pos] & 0x7f;
2396*fcb125edSMatthias Ringwald         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
23973232a1c6SMatthias Ringwald         pos++;
23983232a1c6SMatthias Ringwald         uint8_t length = command[pos++];
23993232a1c6SMatthias Ringwald 
24003232a1c6SMatthias Ringwald         // Retransmission and Flow Control Option
2401671fb338SMatthias Ringwald         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2402ac8f1300SMatthias Ringwald             switch (channel->mode){
2403ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2404f2fa388dSMatthias Ringwald                     if (channel->ertm_mandatory){
2405ac8f1300SMatthias Ringwald                         // ??
2406f2fa388dSMatthias Ringwald                     } else {
2407ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
2408ac8f1300SMatthias Ringwald                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2409f2fa388dSMatthias Ringwald                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
24103232a1c6SMatthias Ringwald                         }
24113232a1c6SMatthias Ringwald                     }
2412ac8f1300SMatthias Ringwald                     break;
2413ac8f1300SMatthias Ringwald                 case L2CAP_CHANNEL_MODE_BASIC:
2414ac8f1300SMatthias Ringwald                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2415ac8f1300SMatthias Ringwald                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
2416ac8f1300SMatthias Ringwald                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2417ac8f1300SMatthias Ringwald                     }
2418ac8f1300SMatthias Ringwald                     break;
2419ac8f1300SMatthias Ringwald                 default:
2420ac8f1300SMatthias Ringwald                     break;
24213232a1c6SMatthias Ringwald             }
2422f2fa388dSMatthias Ringwald         }
24233232a1c6SMatthias Ringwald 
24243232a1c6SMatthias Ringwald         // check for unknown options
2425671fb338SMatthias Ringwald         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
24263232a1c6SMatthias Ringwald             log_info("l2cap cid %u, unknown options", channel->local_cid);
24273232a1c6SMatthias Ringwald             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
24283232a1c6SMatthias Ringwald         }
24293232a1c6SMatthias Ringwald 
24303232a1c6SMatthias Ringwald         pos += length;
24313232a1c6SMatthias Ringwald     }
2432688f9764SMatthias Ringwald #else
24335774a392SMatthias Ringwald     UNUSED(channel);  // ok: no code
24345774a392SMatthias Ringwald     UNUSED(result);   // ok: no code
24355774a392SMatthias Ringwald     UNUSED(command);  // ok: no code
24363232a1c6SMatthias Ringwald #endif
24373232a1c6SMatthias Ringwald }
24383232a1c6SMatthias Ringwald 
2439fa8473a4Smatthias.ringwald static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
24409da54300S[email protected]     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
244173cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
244273cf2b3dSmatthias.ringwald     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
2443019f9b43SMatthias Ringwald     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
2444019f9b43SMatthias Ringwald     if (channel->state == L2CAP_STATE_OPEN) return 0;
2445fa8473a4Smatthias.ringwald     return 1;
2446fa8473a4Smatthias.ringwald }
2447fa8473a4Smatthias.ringwald 
2448fa8473a4Smatthias.ringwald 
2449e9cfb251SMatthias Ringwald // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
24507f02f414SMatthias Ringwald static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
24511e6aba47Smatthias.ringwald 
245200d93d79Smatthias.ringwald     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
245300d93d79Smatthias.ringwald     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2454e9cfb251SMatthias Ringwald     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
245538e5900eSmatthias.ringwald     uint16_t result = 0;
24561e6aba47Smatthias.ringwald 
24579da54300S[email protected]     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
2458b35f641cSmatthias.ringwald 
24599a011532Smatthias.ringwald     // handle DISCONNECT REQUESTS seperately
24609a011532Smatthias.ringwald     if (code == DISCONNECTION_REQUEST){
24619a011532Smatthias.ringwald         switch (channel->state){
2462fa8473a4Smatthias.ringwald             case L2CAP_STATE_CONFIG:
24639a011532Smatthias.ringwald             case L2CAP_STATE_OPEN:
24642b83fb7dSmatthias.ringwald             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
24659a011532Smatthias.ringwald             case L2CAP_STATE_WAIT_DISCONNECT:
24669a011532Smatthias.ringwald                 l2cap_handle_disconnect_request(channel, identifier);
24679a011532Smatthias.ringwald                 break;
24689a011532Smatthias.ringwald 
24699a011532Smatthias.ringwald             default:
24709a011532Smatthias.ringwald                 // ignore in other states
24719a011532Smatthias.ringwald                 break;
24729a011532Smatthias.ringwald         }
24739a011532Smatthias.ringwald         return;
24749a011532Smatthias.ringwald     }
24759a011532Smatthias.ringwald 
247656081214Smatthias.ringwald     // @STATEMACHINE(l2cap)
24771e6aba47Smatthias.ringwald     switch (channel->state) {
24781e6aba47Smatthias.ringwald 
24791e6aba47Smatthias.ringwald         case L2CAP_STATE_WAIT_CONNECT_RSP:
24801e6aba47Smatthias.ringwald             switch (code){
24811e6aba47Smatthias.ringwald                 case CONNECTION_RESPONSE:
2482e9cfb251SMatthias Ringwald                     if (cmd_len < 8){
2483e9cfb251SMatthias Ringwald                         // command imcomplete
2484e9cfb251SMatthias Ringwald                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2485e9cfb251SMatthias Ringwald                         break;
2486e9cfb251SMatthias Ringwald                     }
24875932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2488f8fbdce0SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
248938e5900eSmatthias.ringwald                     switch (result) {
249038e5900eSmatthias.ringwald                         case 0:
2491169f8b28Smatthias.ringwald                             // successful connection
2492f8fbdce0SMatthias Ringwald                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2493fa8473a4Smatthias.ringwald                             channel->state = L2CAP_STATE_CONFIG;
249428ca2b46S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
249538e5900eSmatthias.ringwald                             break;
249638e5900eSmatthias.ringwald                         case 1:
24975932bd7cS[email protected]                             // connection pending. get some coffee, but start the ERTX
24985932bd7cS[email protected]                             l2cap_start_ertx(channel);
249938e5900eSmatthias.ringwald                             break;
250038e5900eSmatthias.ringwald                         default:
2501eb920dbeSmatthias.ringwald                             // channel closed
2502eb920dbeSmatthias.ringwald                             channel->state = L2CAP_STATE_CLOSED;
2503f32b992eSmatthias.ringwald                             // map l2cap connection response result to BTstack status enumeration
250438e5900eSmatthias.ringwald                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
2505eb920dbeSmatthias.ringwald 
2506eb920dbeSmatthias.ringwald                             // drop link key if security block
2507eb920dbeSmatthias.ringwald                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
250815a95bd5SMatthias Ringwald                                 gap_drop_link_key_for_bd_addr(channel->address);
2509eb920dbeSmatthias.ringwald                             }
2510eb920dbeSmatthias.ringwald 
2511eb920dbeSmatthias.ringwald                             // discard channel
2512665d90f2SMatthias Ringwald                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2513d3a9df87Smatthias.ringwald                             btstack_memory_l2cap_channel_free(channel);
251438e5900eSmatthias.ringwald                             break;
25151e6aba47Smatthias.ringwald                     }
25161e6aba47Smatthias.ringwald                     break;
251738e5900eSmatthias.ringwald 
251838e5900eSmatthias.ringwald                 default:
25191e6aba47Smatthias.ringwald                     //@TODO: implement other signaling packets
252038e5900eSmatthias.ringwald                     break;
25211e6aba47Smatthias.ringwald             }
25221e6aba47Smatthias.ringwald             break;
25231e6aba47Smatthias.ringwald 
2524fa8473a4Smatthias.ringwald         case L2CAP_STATE_CONFIG:
2525ae280e73Smatthias.ringwald             switch (code) {
2526ae280e73Smatthias.ringwald                 case CONFIGURE_REQUEST:
2527e9cfb251SMatthias Ringwald                     if (cmd_len < 4){
2528e9cfb251SMatthias Ringwald                         // command incomplete
2529e9cfb251SMatthias Ringwald                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2530e9cfb251SMatthias Ringwald                         break;
2531e9cfb251SMatthias Ringwald                     }
253228ca2b46S[email protected]                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
2533ae280e73Smatthias.ringwald                     l2cap_signaling_handle_configure_request(channel, command);
253463a7246aSmatthias.ringwald                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
253563a7246aSmatthias.ringwald                         // only done if continuation not set
253663a7246aSmatthias.ringwald                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
253763a7246aSmatthias.ringwald                     }
2538ae280e73Smatthias.ringwald                     break;
25391e6aba47Smatthias.ringwald                 case CONFIGURE_RESPONSE:
2540e9cfb251SMatthias Ringwald                     if (cmd_len < 6){
2541e9cfb251SMatthias Ringwald                         // command incomplete
2542e9cfb251SMatthias Ringwald                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2543e9cfb251SMatthias Ringwald                         break;
2544e9cfb251SMatthias Ringwald                     }
2545e9cfb251SMatthias Ringwald                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
25465932bd7cS[email protected]                     l2cap_stop_rtx(channel);
2547f2fa388dSMatthias Ringwald                     l2cap_signaling_handle_configure_response(channel, result, command);
25485932bd7cS[email protected]                     switch (result){
25495932bd7cS[email protected]                         case 0: // success
25505932bd7cS[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
25515932bd7cS[email protected]                             break;
25525932bd7cS[email protected]                         case 4: // pending
25535932bd7cS[email protected]                             l2cap_start_ertx(channel);
25545932bd7cS[email protected]                             break;
25555932bd7cS[email protected]                         default:
2556a32d6a03SMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2557a32d6a03SMatthias Ringwald                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
2558a32d6a03SMatthias Ringwald                                 // remote does not offer ertm but it's required
2559a32d6a03SMatthias Ringwald                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2560a32d6a03SMatthias Ringwald                                 break;
2561a32d6a03SMatthias Ringwald                             }
2562a32d6a03SMatthias Ringwald #endif
2563fe9d8984S[email protected]                             // retry on negative result
2564fe9d8984S[email protected]                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2565fe9d8984S[email protected]                             break;
2566fe9d8984S[email protected]                     }
25675a67bd4aSmatthias.ringwald                     break;
25685a67bd4aSmatthias.ringwald                 default:
25695a67bd4aSmatthias.ringwald                     break;
25701e6aba47Smatthias.ringwald             }
2571fa8473a4Smatthias.ringwald             if (l2cap_channel_ready_for_open(channel)){
2572fa8473a4Smatthias.ringwald                 // for open:
25735a67bd4aSmatthias.ringwald                 channel->state = L2CAP_STATE_OPEN;
2574fa8473a4Smatthias.ringwald                 l2cap_emit_channel_opened(channel, 0);
2575c8e4258aSmatthias.ringwald             }
2576c8e4258aSmatthias.ringwald             break;
2577f62db1e3Smatthias.ringwald 
2578f62db1e3Smatthias.ringwald         case L2CAP_STATE_WAIT_DISCONNECT:
2579f62db1e3Smatthias.ringwald             switch (code) {
2580f62db1e3Smatthias.ringwald                 case DISCONNECTION_RESPONSE:
258127a923d0Smatthias.ringwald                     l2cap_finialize_channel_close(channel);
258227a923d0Smatthias.ringwald                     break;
25835a67bd4aSmatthias.ringwald                 default:
25845a67bd4aSmatthias.ringwald                     //@TODO: implement other signaling packets
25855a67bd4aSmatthias.ringwald                     break;
258627a923d0Smatthias.ringwald             }
258727a923d0Smatthias.ringwald             break;
258884836b65Smatthias.ringwald 
258984836b65Smatthias.ringwald         case L2CAP_STATE_CLOSED:
259084836b65Smatthias.ringwald             // @TODO handle incoming requests
259184836b65Smatthias.ringwald             break;
259284836b65Smatthias.ringwald 
259384836b65Smatthias.ringwald         case L2CAP_STATE_OPEN:
259484836b65Smatthias.ringwald             //@TODO: implement other signaling packets, e.g. re-configure
259584836b65Smatthias.ringwald             break;
259610642e45Smatthias.ringwald         default:
259710642e45Smatthias.ringwald             break;
259827a923d0Smatthias.ringwald     }
25999da54300S[email protected]     // log_info("new state %u", channel->state);
260027a923d0Smatthias.ringwald }
260127a923d0Smatthias.ringwald 
260200d93d79Smatthias.ringwald 
2603ed2ed8e1SMatthias Ringwald // @pre command len is valid, see check in l2cap_acl_classic_handler
26047f02f414SMatthias Ringwald static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
260500d93d79Smatthias.ringwald 
26061b9cb13dSMatthias Ringwald     btstack_linked_list_iterator_t it;
26071b9cb13dSMatthias Ringwald 
260800d93d79Smatthias.ringwald     // get code, signalind identifier and command len
260900d93d79Smatthias.ringwald     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
261000d93d79Smatthias.ringwald     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
26110493bf3aSMatthias Ringwald     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
261200d93d79Smatthias.ringwald 
26131b9cb13dSMatthias Ringwald     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
26141b9cb13dSMatthias Ringwald     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_RESPONSE){
2615e74c5f58SMatthias Ringwald         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
261600d93d79Smatthias.ringwald         return;
261700d93d79Smatthias.ringwald     }
261800d93d79Smatthias.ringwald 
261900d93d79Smatthias.ringwald     // general commands without an assigned channel
262000d93d79Smatthias.ringwald     switch(code) {
262100d93d79Smatthias.ringwald 
26220493bf3aSMatthias Ringwald         case CONNECTION_REQUEST:
26230493bf3aSMatthias Ringwald             if (cmd_len == 4){
2624f8fbdce0SMatthias Ringwald                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2625f8fbdce0SMatthias Ringwald                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
262600d93d79Smatthias.ringwald                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
26270493bf3aSMatthias Ringwald             } else {
26280493bf3aSMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
262900d93d79Smatthias.ringwald             }
26300493bf3aSMatthias Ringwald             return;
263100d93d79Smatthias.ringwald 
26322b360848Smatthias.ringwald         case ECHO_REQUEST:
2633e74c5f58SMatthias Ringwald             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
26342b83fb7dSmatthias.ringwald             return;
263500d93d79Smatthias.ringwald 
26360493bf3aSMatthias Ringwald         case INFORMATION_REQUEST:
26370493bf3aSMatthias Ringwald             if (cmd_len == 2) {
26383e64cb44SMatthias Ringwald                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
26393e64cb44SMatthias Ringwald                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
26400493bf3aSMatthias Ringwald             } else {
26410493bf3aSMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
264200d93d79Smatthias.ringwald             }
26430493bf3aSMatthias Ringwald             return;
264400d93d79Smatthias.ringwald 
26451b9cb13dSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
26461b9cb13dSMatthias Ringwald         case INFORMATION_RESPONSE: {
26471b9cb13dSMatthias Ringwald             hci_connection_t * connection = hci_connection_for_handle(handle);
26481b9cb13dSMatthias Ringwald             if (!connection) return;
26490493bf3aSMatthias Ringwald             if (cmd_len >= 4) {
26501b9cb13dSMatthias Ringwald                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
26511b9cb13dSMatthias Ringwald                 uint16_t result =  little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
26521b9cb13dSMatthias Ringwald                 if (result != 0) return;
26533e64cb44SMatthias Ringwald                 if (info_type != L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) return;
26540493bf3aSMatthias Ringwald                 if (cmd_len >= 6) {
26551b9cb13dSMatthias Ringwald                     connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
26561b9cb13dSMatthias Ringwald                     connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2657543b84e4SMatthias Ringwald                     log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
26581b9cb13dSMatthias Ringwald                     // trigger connection request
26591b9cb13dSMatthias Ringwald                     btstack_linked_list_iterator_init(&it, &l2cap_channels);
26601b9cb13dSMatthias Ringwald                     while (btstack_linked_list_iterator_has_next(&it)){
26611b9cb13dSMatthias Ringwald                         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2662543b84e4SMatthias Ringwald                         if (channel->con_handle != handle) continue;
2663543b84e4SMatthias Ringwald                         // bail if ERTM was requested but is not supported
2664543b84e4SMatthias Ringwald                         if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2665f073f086SMatthias Ringwald                             if (channel->ertm_mandatory){
2666543b84e4SMatthias Ringwald                                 // channel closed
2667543b84e4SMatthias Ringwald                                 channel->state = L2CAP_STATE_CLOSED;
2668543b84e4SMatthias Ringwald                                 // map l2cap connection response result to BTstack status enumeration
2669188c56a5SMatthias Ringwald                                 l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
2670543b84e4SMatthias Ringwald                                 // discard channel
2671543b84e4SMatthias Ringwald                                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2672543b84e4SMatthias Ringwald                                 btstack_memory_l2cap_channel_free(channel);
2673543b84e4SMatthias Ringwald                                 continue;
2674f073f086SMatthias Ringwald                             } else {
2675f073f086SMatthias Ringwald                                 // fallback to Basic mode
2676f073f086SMatthias Ringwald                                 channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2677f073f086SMatthias Ringwald                             }
2678543b84e4SMatthias Ringwald                         }
2679543b84e4SMatthias Ringwald                         // start connecting
26801b9cb13dSMatthias Ringwald                         if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
26811b9cb13dSMatthias Ringwald                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
26821b9cb13dSMatthias Ringwald                         }
268352606043SMatthias Ringwald                         // respond to connection request
268452606043SMatthias Ringwald                         if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
268552606043SMatthias Ringwald                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
268652606043SMatthias Ringwald                             l2cap_emit_incoming_connection(channel);
268752606043SMatthias Ringwald                         }
26881b9cb13dSMatthias Ringwald                     }
26890493bf3aSMatthias Ringwald                     return; // cmd len valid
26900493bf3aSMatthias Ringwald                 }
26910493bf3aSMatthias Ringwald             }
26920493bf3aSMatthias Ringwald             l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
26931b9cb13dSMatthias Ringwald             return;
26941b9cb13dSMatthias Ringwald         }
26951b9cb13dSMatthias Ringwald #endif
26961b9cb13dSMatthias Ringwald 
269700d93d79Smatthias.ringwald         default:
269800d93d79Smatthias.ringwald             break;
269900d93d79Smatthias.ringwald     }
270000d93d79Smatthias.ringwald 
270100d93d79Smatthias.ringwald     // Get potential destination CID
2702f8fbdce0SMatthias Ringwald     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
270300d93d79Smatthias.ringwald 
270400d93d79Smatthias.ringwald     // Find channel for this sig_id and connection handle
2705665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2706665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
2707665d90f2SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2708fc64f94aSMatthias Ringwald         if (channel->con_handle != handle) continue;
270900d93d79Smatthias.ringwald         if (code & 1) {
2710b1988dceSmatthias.ringwald             // match odd commands (responses) by previous signaling identifier
2711b1988dceSmatthias.ringwald             if (channel->local_sig_id == sig_id) {
271200d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
27134e32727eSmatthias.ringwald                 break;
271400d93d79Smatthias.ringwald             }
271500d93d79Smatthias.ringwald         } else {
2716b1988dceSmatthias.ringwald             // match even commands (requests) by local channel id
271700d93d79Smatthias.ringwald             if (channel->local_cid == dest_cid) {
271800d93d79Smatthias.ringwald                 l2cap_signaling_handler_channel(channel, command);
27194e32727eSmatthias.ringwald                 break;
272000d93d79Smatthias.ringwald             }
272100d93d79Smatthias.ringwald         }
272200d93d79Smatthias.ringwald     }
272300d93d79Smatthias.ringwald }
272409e9d05bSMatthias Ringwald #endif
272500d93d79Smatthias.ringwald 
2726e7d0c9aaSMatthias Ringwald #ifdef ENABLE_BLE
272709e9d05bSMatthias Ringwald 
272809e9d05bSMatthias Ringwald static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
272909e9d05bSMatthias Ringwald     uint8_t event[6];
273009e9d05bSMatthias Ringwald     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
273109e9d05bSMatthias Ringwald     event[1] = 4;
273209e9d05bSMatthias Ringwald     little_endian_store_16(event, 2, con_handle);
273309e9d05bSMatthias Ringwald     little_endian_store_16(event, 4, result);
273409e9d05bSMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
273509e9d05bSMatthias Ringwald     if (!l2cap_event_packet_handler) return;
273609e9d05bSMatthias Ringwald     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
273709e9d05bSMatthias Ringwald }
273809e9d05bSMatthias Ringwald 
2739c48b2a2cSMatthias Ringwald // @returns valid
2740c48b2a2cSMatthias Ringwald static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
2741e7d0c9aaSMatthias Ringwald     hci_connection_t * connection;
2742c48b2a2cSMatthias Ringwald     uint16_t result;
2743c48b2a2cSMatthias Ringwald     uint8_t  event[10];
274483fd9c76SMatthias Ringwald 
2745cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2746a3dc965aSMatthias Ringwald     btstack_linked_list_iterator_t it;
2747a3dc965aSMatthias Ringwald     l2cap_channel_t * channel;
2748a3dc965aSMatthias Ringwald     uint16_t local_cid;
274983fd9c76SMatthias Ringwald     uint16_t le_psm;
275063f0ac45SMatthias Ringwald     uint16_t new_credits;
275163f0ac45SMatthias Ringwald     uint16_t credits_before;
2752e7d0c9aaSMatthias Ringwald     l2cap_service_t * service;
275311cae19eSMilanka Ringwald     uint16_t source_cid;
275483fd9c76SMatthias Ringwald #endif
275500d93d79Smatthias.ringwald 
27561b8b8d05SMatthias Ringwald     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2757adcfabadSMatthias Ringwald     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
27581fcd10b7SMatthias Ringwald     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
27591b8b8d05SMatthias Ringwald 
27601b8b8d05SMatthias Ringwald     switch (code){
276100d93d79Smatthias.ringwald 
2762c48b2a2cSMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_REQUEST:
2763adcfabadSMatthias Ringwald             // check size
27641fcd10b7SMatthias Ringwald             if (len < 8) return 0;
2765e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
2766da886c03S[email protected]             if (connection){
27676d91fb6cSMatthias Ringwald                 if (connection->role != HCI_ROLE_MASTER){
27686d91fb6cSMatthias Ringwald                     // reject command without notifying upper layer when not in master role
2769c48b2a2cSMatthias Ringwald                     return 0;
27706d91fb6cSMatthias Ringwald                 }
2771da886c03S[email protected]                 int update_parameter = 1;
2772a4c06b28SMatthias Ringwald                 le_connection_parameter_range_t existing_range;
27734ced4e8cSMatthias Ringwald                 gap_get_connection_parameter_range(&existing_range);
2774c48b2a2cSMatthias Ringwald                 uint16_t le_conn_interval_min = little_endian_read_16(command,8);
2775c48b2a2cSMatthias Ringwald                 uint16_t le_conn_interval_max = little_endian_read_16(command,10);
2776c48b2a2cSMatthias Ringwald                 uint16_t le_conn_latency = little_endian_read_16(command,12);
2777c48b2a2cSMatthias Ringwald                 uint16_t le_supervision_timeout = little_endian_read_16(command,14);
2778da886c03S[email protected] 
2779da886c03S[email protected]                 if (le_conn_interval_min < existing_range.le_conn_interval_min) update_parameter = 0;
2780da886c03S[email protected]                 if (le_conn_interval_max > existing_range.le_conn_interval_max) update_parameter = 0;
2781da886c03S[email protected] 
2782da886c03S[email protected]                 if (le_conn_latency < existing_range.le_conn_latency_min) update_parameter = 0;
2783da886c03S[email protected]                 if (le_conn_latency > existing_range.le_conn_latency_max) update_parameter = 0;
2784da886c03S[email protected] 
2785da886c03S[email protected]                 if (le_supervision_timeout < existing_range.le_supervision_timeout_min) update_parameter = 0;
2786da886c03S[email protected]                 if (le_supervision_timeout > existing_range.le_supervision_timeout_max) update_parameter = 0;
2787da886c03S[email protected] 
2788da886c03S[email protected]                 if (update_parameter){
2789da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
2790da886c03S[email protected]                     connection->le_conn_interval_min = le_conn_interval_min;
2791da886c03S[email protected]                     connection->le_conn_interval_max = le_conn_interval_max;
2792da886c03S[email protected]                     connection->le_conn_latency = le_conn_latency;
2793da886c03S[email protected]                     connection->le_supervision_timeout = le_supervision_timeout;
2794da886c03S[email protected]                 } else {
2795da886c03S[email protected]                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
2796da886c03S[email protected]                 }
2797c48b2a2cSMatthias Ringwald                 connection->le_con_param_update_identifier = sig_id;
2798da886c03S[email protected]             }
2799da886c03S[email protected] 
280033c40538SMatthias Ringwald             if (!l2cap_event_packet_handler) break;
2801c48b2a2cSMatthias Ringwald 
2802c48b2a2cSMatthias Ringwald             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
2803c48b2a2cSMatthias Ringwald             event[1] = 8;
2804c48b2a2cSMatthias Ringwald             memcpy(&event[2], &command[4], 8);
2805c48b2a2cSMatthias Ringwald             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
280633c40538SMatthias Ringwald             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
2807ccf076adS[email protected]             break;
2808c48b2a2cSMatthias Ringwald 
28091fcd10b7SMatthias Ringwald         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
28101fcd10b7SMatthias Ringwald             // check size
28111fcd10b7SMatthias Ringwald             if (len < 2) return 0;
28121fcd10b7SMatthias Ringwald             result = little_endian_read_16(command, 4);
28131fcd10b7SMatthias Ringwald             l2cap_emit_connection_parameter_update_response(handle, result);
28141fcd10b7SMatthias Ringwald             break;
28151fcd10b7SMatthias Ringwald 
2816a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
2817a3dc965aSMatthias Ringwald 
281863f0ac45SMatthias Ringwald         case COMMAND_REJECT:
281963f0ac45SMatthias Ringwald             // Find channel for this sig_id and connection handle
282063f0ac45SMatthias Ringwald             channel = NULL;
282163f0ac45SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
282263f0ac45SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
282363f0ac45SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
282463f0ac45SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
282563f0ac45SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
282663f0ac45SMatthias Ringwald                 channel = a_channel;
282763f0ac45SMatthias Ringwald                 break;
282863f0ac45SMatthias Ringwald             }
282963f0ac45SMatthias Ringwald             if (!channel) break;
283063f0ac45SMatthias Ringwald 
283163f0ac45SMatthias Ringwald             // if received while waiting for le connection response, assume legacy device
283263f0ac45SMatthias Ringwald             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
283363f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
283463f0ac45SMatthias Ringwald                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
283544276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, 0x0002);
283663f0ac45SMatthias Ringwald 
283763f0ac45SMatthias Ringwald                 // discard channel
283863f0ac45SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
283963f0ac45SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
284063f0ac45SMatthias Ringwald                 break;
284163f0ac45SMatthias Ringwald             }
284263f0ac45SMatthias Ringwald             break;
284363f0ac45SMatthias Ringwald 
2844e7d0c9aaSMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_REQUEST:
2845adcfabadSMatthias Ringwald             // check size
2846adcfabadSMatthias Ringwald             if (len < 10) return 0;
2847e7d0c9aaSMatthias Ringwald 
2848e7d0c9aaSMatthias Ringwald             // get hci connection, bail if not found (must not happen)
2849e7d0c9aaSMatthias Ringwald             connection = hci_connection_for_handle(handle);
2850e7d0c9aaSMatthias Ringwald             if (!connection) return 0;
2851e7d0c9aaSMatthias Ringwald 
2852e7d0c9aaSMatthias Ringwald             // check if service registered
2853e7d0c9aaSMatthias Ringwald             le_psm  = little_endian_read_16(command, 4);
2854e7d0c9aaSMatthias Ringwald             service = l2cap_le_get_service(le_psm);
285511cae19eSMilanka Ringwald             source_cid = little_endian_read_16(command, 6);
2856e7d0c9aaSMatthias Ringwald 
2857e7d0c9aaSMatthias Ringwald             if (service){
2858e7d0c9aaSMatthias Ringwald                 if (source_cid < 0x40){
2859e7d0c9aaSMatthias Ringwald                     // 0x0009 Connection refused - Invalid Source CID
2860e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
2861e7d0c9aaSMatthias Ringwald                     return 1;
2862e7d0c9aaSMatthias Ringwald                 }
2863e7d0c9aaSMatthias Ringwald 
2864e7d0c9aaSMatthias Ringwald                 // go through list of channels for this ACL connection and check if we get a match
2865e7d0c9aaSMatthias Ringwald                 btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
2866e7d0c9aaSMatthias Ringwald                 while (btstack_linked_list_iterator_has_next(&it)){
28671b8b8d05SMatthias Ringwald                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
28681b8b8d05SMatthias Ringwald                     if (a_channel->con_handle != handle) continue;
28691b8b8d05SMatthias Ringwald                     if (a_channel->remote_cid != source_cid) continue;
2870e7d0c9aaSMatthias Ringwald                     // 0x000a Connection refused - Source CID already allocated
2871e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
2872e7d0c9aaSMatthias Ringwald                     return 1;
2873e7d0c9aaSMatthias Ringwald                 }
2874e7d0c9aaSMatthias Ringwald 
287583fd9c76SMatthias Ringwald                 // security: check encryption
287683fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_2){
287783fd9c76SMatthias Ringwald                     if (sm_encryption_key_size(handle) == 0){
287883fd9c76SMatthias Ringwald                         // 0x0008 Connection refused - insufficient encryption
2879e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
288083fd9c76SMatthias Ringwald                         return 1;
288183fd9c76SMatthias Ringwald                     }
288283fd9c76SMatthias Ringwald                     // anything less than 16 byte key size is insufficient
288383fd9c76SMatthias Ringwald                     if (sm_encryption_key_size(handle) < 16){
288483fd9c76SMatthias Ringwald                         // 0x0007 Connection refused – insufficient encryption key size
2885e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
288683fd9c76SMatthias Ringwald                         return 1;
288783fd9c76SMatthias Ringwald                     }
288883fd9c76SMatthias Ringwald                 }
288983fd9c76SMatthias Ringwald 
289083fd9c76SMatthias Ringwald                 // security: check authencation
289183fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_3){
289283fd9c76SMatthias Ringwald                     if (!sm_authenticated(handle)){
289383fd9c76SMatthias Ringwald                         // 0x0005 Connection refused – insufficient authentication
2894e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
289583fd9c76SMatthias Ringwald                         return 1;
289683fd9c76SMatthias Ringwald                     }
289783fd9c76SMatthias Ringwald                 }
289883fd9c76SMatthias Ringwald 
289983fd9c76SMatthias Ringwald                 // security: check authorization
290083fd9c76SMatthias Ringwald                 if (service->required_security_level >= LEVEL_4){
290183fd9c76SMatthias Ringwald                     if (sm_authorization_state(handle) != AUTHORIZATION_GRANTED){
290283fd9c76SMatthias Ringwald                         // 0x0006 Connection refused – insufficient authorization
2903e74c5f58SMatthias Ringwald                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
290483fd9c76SMatthias Ringwald                         return 1;
290583fd9c76SMatthias Ringwald                     }
290683fd9c76SMatthias Ringwald                 }
2907e7d0c9aaSMatthias Ringwald 
2908e7d0c9aaSMatthias Ringwald                 // allocate channel
29091b8b8d05SMatthias Ringwald                 channel = l2cap_create_channel_entry(service->packet_handler, connection->address,
2910e7d0c9aaSMatthias Ringwald                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
2911e7d0c9aaSMatthias Ringwald                 if (!channel){
2912e7d0c9aaSMatthias Ringwald                     // 0x0004 Connection refused – no resources available
2913e74c5f58SMatthias Ringwald                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2914e7d0c9aaSMatthias Ringwald                     return 1;
2915e7d0c9aaSMatthias Ringwald                 }
2916e7d0c9aaSMatthias Ringwald 
2917e7d0c9aaSMatthias Ringwald                 channel->con_handle = handle;
2918e7d0c9aaSMatthias Ringwald                 channel->remote_cid = source_cid;
2919e7d0c9aaSMatthias Ringwald                 channel->remote_sig_id = sig_id;
29207f107edaSMatthias Ringwald                 channel->remote_mtu = little_endian_read_16(command, 8);
29217f107edaSMatthias Ringwald                 channel->remote_mps = little_endian_read_16(command, 10);
29227f107edaSMatthias Ringwald                 channel->credits_outgoing = little_endian_read_16(command, 12);
2923e7d0c9aaSMatthias Ringwald 
2924e7d0c9aaSMatthias Ringwald                 // set initial state
2925e7d0c9aaSMatthias Ringwald                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2926c99bb618SMatthias Ringwald                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
2927e7d0c9aaSMatthias Ringwald 
2928e7d0c9aaSMatthias Ringwald                 // add to connections list
2929e7d0c9aaSMatthias Ringwald                 btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
2930e7d0c9aaSMatthias Ringwald 
2931e7d0c9aaSMatthias Ringwald                 // post connection request event
293244276248SMatthias Ringwald                 l2cap_emit_le_incoming_connection(channel);
2933e7d0c9aaSMatthias Ringwald 
2934e7d0c9aaSMatthias Ringwald             } else {
2935e7d0c9aaSMatthias Ringwald                 // Connection refused – LE_PSM not supported
2936e74c5f58SMatthias Ringwald                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2937e7d0c9aaSMatthias Ringwald             }
2938e7d0c9aaSMatthias Ringwald             break;
29391b8b8d05SMatthias Ringwald 
29401b8b8d05SMatthias Ringwald         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
2941adcfabadSMatthias Ringwald             // check size
2942adcfabadSMatthias Ringwald             if (len < 10) return 0;
2943adcfabadSMatthias Ringwald 
29441b8b8d05SMatthias Ringwald             // Find channel for this sig_id and connection handle
29451b8b8d05SMatthias Ringwald             channel = NULL;
29461b8b8d05SMatthias Ringwald             btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
29471b8b8d05SMatthias Ringwald             while (btstack_linked_list_iterator_has_next(&it)){
29481b8b8d05SMatthias Ringwald                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
29491b8b8d05SMatthias Ringwald                 if (a_channel->con_handle   != handle) continue;
29501b8b8d05SMatthias Ringwald                 if (a_channel->local_sig_id != sig_id) continue;
29511b8b8d05SMatthias Ringwald                 channel = a_channel;
29521b8b8d05SMatthias Ringwald                 break;
29531b8b8d05SMatthias Ringwald             }
29541b8b8d05SMatthias Ringwald             if (!channel) break;
29551b8b8d05SMatthias Ringwald 
29561b8b8d05SMatthias Ringwald             // cid + 0
29571b8b8d05SMatthias Ringwald             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
29581b8b8d05SMatthias Ringwald             if (result){
29591b8b8d05SMatthias Ringwald                 channel->state = L2CAP_STATE_CLOSED;
29601b8b8d05SMatthias Ringwald                 // map l2cap connection response result to BTstack status enumeration
296144276248SMatthias Ringwald                 l2cap_emit_le_channel_opened(channel, result);
29621b8b8d05SMatthias Ringwald 
29631b8b8d05SMatthias Ringwald                 // discard channel
296463f0ac45SMatthias Ringwald                 btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
29651b8b8d05SMatthias Ringwald                 btstack_memory_l2cap_channel_free(channel);
29661b8b8d05SMatthias Ringwald                 break;
29671b8b8d05SMatthias Ringwald             }
29681b8b8d05SMatthias Ringwald 
29691b8b8d05SMatthias Ringwald             // success
29701b8b8d05SMatthias Ringwald             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
29711b8b8d05SMatthias Ringwald             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
29721b8b8d05SMatthias Ringwald             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
29731b8b8d05SMatthias Ringwald             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
29741b8b8d05SMatthias Ringwald             channel->state = L2CAP_STATE_OPEN;
297544276248SMatthias Ringwald             l2cap_emit_le_channel_opened(channel, result);
29761b8b8d05SMatthias Ringwald             break;
29771b8b8d05SMatthias Ringwald 
297885aeef60SMatthias Ringwald         case LE_FLOW_CONTROL_CREDIT:
2979adcfabadSMatthias Ringwald             // check size
2980adcfabadSMatthias Ringwald             if (len < 4) return 0;
2981adcfabadSMatthias Ringwald 
298285aeef60SMatthias Ringwald             // find channel
298385aeef60SMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
298485aeef60SMatthias Ringwald             channel = l2cap_le_get_channel_for_local_cid(local_cid);
298563f0ac45SMatthias Ringwald             if (!channel) {
298663f0ac45SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
298763f0ac45SMatthias Ringwald                 break;
298863f0ac45SMatthias Ringwald             }
298963f0ac45SMatthias Ringwald             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
299063f0ac45SMatthias Ringwald             credits_before = channel->credits_outgoing;
299163f0ac45SMatthias Ringwald             channel->credits_outgoing += new_credits;
299263f0ac45SMatthias Ringwald             // check for credit overrun
299363f0ac45SMatthias Ringwald             if (credits_before > channel->credits_outgoing){
299463f0ac45SMatthias Ringwald                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
299563f0ac45SMatthias Ringwald                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
299663f0ac45SMatthias Ringwald                 break;
299763f0ac45SMatthias Ringwald             }
299863f0ac45SMatthias Ringwald             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
299985aeef60SMatthias Ringwald             break;
300085aeef60SMatthias Ringwald 
3001828a7f7aSMatthias Ringwald         case DISCONNECTION_REQUEST:
3002adcfabadSMatthias Ringwald 
3003adcfabadSMatthias Ringwald             // check size
3004adcfabadSMatthias Ringwald             if (len < 4) return 0;
3005adcfabadSMatthias Ringwald 
3006828a7f7aSMatthias Ringwald             // find channel
3007828a7f7aSMatthias Ringwald             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3008828a7f7aSMatthias Ringwald             channel = l2cap_le_get_channel_for_local_cid(local_cid);
300963f34e00SMatthias Ringwald             if (!channel) {
301063f34e00SMatthias Ringwald                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
301163f34e00SMatthias Ringwald                 break;
301263f34e00SMatthias Ringwald             }
3013828a7f7aSMatthias Ringwald             channel->remote_sig_id = sig_id;
3014828a7f7aSMatthias Ringwald             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
3015828a7f7aSMatthias Ringwald             break;
3016828a7f7aSMatthias Ringwald 
3017a3dc965aSMatthias Ringwald #endif
3018a3dc965aSMatthias Ringwald 
301963f0ac45SMatthias Ringwald         case DISCONNECTION_RESPONSE:
302063f0ac45SMatthias Ringwald             break;
302163f0ac45SMatthias Ringwald 
3022c48b2a2cSMatthias Ringwald         default:
3023c48b2a2cSMatthias Ringwald             // command unknown -> reject command
3024c48b2a2cSMatthias Ringwald             return 0;
3025ccf076adS[email protected]     }
3026c48b2a2cSMatthias Ringwald     return 1;
3027c48b2a2cSMatthias Ringwald }
3028e7d0c9aaSMatthias Ringwald #endif
3029c48b2a2cSMatthias Ringwald 
3030bb0a72a6SMatthias Ringwald static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3031bb0a72a6SMatthias Ringwald #ifdef ENABLE_CLASSIC
303209e9d05bSMatthias Ringwald     l2cap_channel_t * l2cap_channel;
303309e9d05bSMatthias Ringwald 
3034c48b2a2cSMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3035c48b2a2cSMatthias Ringwald     switch (channel_id) {
3036c48b2a2cSMatthias Ringwald 
3037c48b2a2cSMatthias Ringwald         case L2CAP_CID_SIGNALING: {
3038c48b2a2cSMatthias Ringwald             uint16_t command_offset = 8;
3039c48b2a2cSMatthias Ringwald             while (command_offset < size) {
3040ed2ed8e1SMatthias Ringwald                 // assert signaling command is fully inside packet
3041ed2ed8e1SMatthias Ringwald                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3042ed2ed8e1SMatthias Ringwald                 uint32_t next_command_offset = ((uint32_t) command_offset) + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
3043ed2ed8e1SMatthias Ringwald                 if (next_command_offset > size){
3044ed2ed8e1SMatthias Ringwald                     log_error("l2cap signaling command len invalid -> drop");
3045ed2ed8e1SMatthias Ringwald                     break;
3046ed2ed8e1SMatthias Ringwald                 }
3047ed2ed8e1SMatthias Ringwald                 // handle signaling command
3048c48b2a2cSMatthias Ringwald                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
3049ed2ed8e1SMatthias Ringwald                 // go to next command
3050ed2ed8e1SMatthias Ringwald                 command_offset = (uint16_t) next_command_offset;
3051c48b2a2cSMatthias Ringwald             }
3052c48b2a2cSMatthias Ringwald             break;
3053c48b2a2cSMatthias Ringwald         }
3054c48b2a2cSMatthias Ringwald         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
3055c48b2a2cSMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback) {
3056c48b2a2cSMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_CONNECTIONLESS_CHANNEL].callback)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3057c48b2a2cSMatthias Ringwald             }
3058c48b2a2cSMatthias Ringwald             break;
30591bbc0b23S[email protected] 
306009e9d05bSMatthias Ringwald         default:
306100d93d79Smatthias.ringwald             // Find channel for this channel_id and connection handle
306264e11ca9SMatthias Ringwald             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
3063d1fd2a88SMatthias Ringwald             if (l2cap_channel) {
306427e0774aSMatthias Ringwald #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
306527e0774aSMatthias Ringwald                 if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
306627e0774aSMatthias Ringwald 
30676574158aSMatthias Ringwald                     int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
306807c7de86SMatthias Ringwald 
30696574158aSMatthias Ringwald                     // assert control + FCS fields are inside
30706574158aSMatthias Ringwald                     if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) break;
30716574158aSMatthias Ringwald 
30726574158aSMatthias Ringwald                     if (l2cap_channel->fcs_option){
3073*fcb125edSMatthias Ringwald                         // verify FCS (required if one side requested it)
307427e0774aSMatthias Ringwald                         uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
307527e0774aSMatthias Ringwald                         uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
30766574158aSMatthias Ringwald                         if (fcs_calculated == fcs_packet){
30776574158aSMatthias Ringwald                             log_info("Packet FCS 0x%04x verified", fcs_packet);
30786574158aSMatthias Ringwald                         } else {
307927e0774aSMatthias Ringwald                             log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
308027e0774aSMatthias Ringwald                             // TODO: trigger retransmission or something like that
308127e0774aSMatthias Ringwald                             break;
308227e0774aSMatthias Ringwald                         }
30836574158aSMatthias Ringwald                     }
308427e0774aSMatthias Ringwald 
308527e0774aSMatthias Ringwald                     // switch on packet type
308627e0774aSMatthias Ringwald                     uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
308738f62777SMatthias Ringwald                     uint8_t  req_seq = (control >> 8) & 0x3f;
30882bea1b8dSMatthias Ringwald                     int final = (control >> 7) & 0x01;
308927e0774aSMatthias Ringwald                     if (control & 1){
309027e0774aSMatthias Ringwald                         // S-Frame
309178cd8a22SMatthias Ringwald                         int poll  = (control >> 4) & 0x01;
3092bdbe2e49SMatthias Ringwald                         l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
30939ffcbce4SMatthias Ringwald                         log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
30947b7901d8SMatthias Ringwald                         l2cap_ertm_tx_packet_state_t * tx_state;
3095bdbe2e49SMatthias Ringwald                         switch (s){
3096bdbe2e49SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
30979ffcbce4SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
30981e1a46bbSMatthias Ringwald                                 l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
30993233d8abSMatthias Ringwald                                 if (poll && final){
31003233d8abSMatthias Ringwald                                     // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
31013233d8abSMatthias Ringwald                                     log_error("P=F=1 in S-Frame");
31023233d8abSMatthias Ringwald                                     break;
31033233d8abSMatthias Ringwald                                 }
310478cd8a22SMatthias Ringwald                                 if (poll){
3105f85ade6bSMatthias Ringwald                                     // check if we did request selective retransmission before <==> we have stored SDU segments
3106f85ade6bSMatthias Ringwald                                     int i;
3107f85ade6bSMatthias Ringwald                                     int num_stored_out_of_order_packets = 0;
3108f85ade6bSMatthias Ringwald                                     for (i=0;i<l2cap_channel->num_rx_buffers;i++){
3109f85ade6bSMatthias Ringwald                                         int index = l2cap_channel->rx_store_index + i;
3110f85ade6bSMatthias Ringwald                                         if (index >= l2cap_channel->num_rx_buffers){
3111f85ade6bSMatthias Ringwald                                             index -= l2cap_channel->num_rx_buffers;
3112f85ade6bSMatthias Ringwald                                         }
3113f85ade6bSMatthias Ringwald                                         l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3114f85ade6bSMatthias Ringwald                                         if (!rx_state->valid) continue;
3115f85ade6bSMatthias Ringwald                                         num_stored_out_of_order_packets++;
3116f85ade6bSMatthias Ringwald                                     }
3117f85ade6bSMatthias Ringwald                                     if (num_stored_out_of_order_packets){
3118f85ade6bSMatthias Ringwald                                         l2cap_channel->send_supervisor_frame_selective_reject = 1;
3119f85ade6bSMatthias Ringwald                                     } else {
3120d2afdd38SMatthias Ringwald                                         l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
312178cd8a22SMatthias Ringwald                                     }
3122f85ade6bSMatthias Ringwald                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
3123f85ade6bSMatthias Ringwald                                 }
31243233d8abSMatthias Ringwald                                 if (final){
3125550189ffSMatthias Ringwald                                     // Stop-MonitorTimer
3126550189ffSMatthias Ringwald                                     l2cap_ertm_stop_monitor_timer(l2cap_channel);
3127550189ffSMatthias Ringwald                                     // If UnackedFrames > 0 then Start-RetransTimer
312894301352SMatthias Ringwald                                     if (l2cap_channel->unacked_frames){
3129550189ffSMatthias Ringwald                                         l2cap_ertm_start_retransmission_timer(l2cap_channel);
3130550189ffSMatthias Ringwald                                     }
3131550189ffSMatthias Ringwald 
31323233d8abSMatthias Ringwald                                     // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
31333233d8abSMatthias Ringwald                                     l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
31343233d8abSMatthias Ringwald                                 }
3135bdbe2e49SMatthias Ringwald                                 break;
31369ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
31379ffcbce4SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
31381e1a46bbSMatthias Ringwald                                 l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
31391e1a46bbSMatthias Ringwald                                 // rsetart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
31409ffcbce4SMatthias Ringwald                                 l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
31419ffcbce4SMatthias Ringwald                                 break;
31429ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
31439ffcbce4SMatthias Ringwald                                 log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
31449ffcbce4SMatthias Ringwald                                 break;
31459ffcbce4SMatthias Ringwald                             case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
31467b7901d8SMatthias Ringwald                                 log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
31477b7901d8SMatthias Ringwald                                 if (poll){
31481e1a46bbSMatthias Ringwald                                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
31497b7901d8SMatthias Ringwald                                 }
31507b7901d8SMatthias Ringwald                                 // find requested i-frame
31517b7901d8SMatthias Ringwald                                 tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
31527b7901d8SMatthias Ringwald                                 if (tx_state){
31537b7901d8SMatthias Ringwald                                     log_info("Retransmission for tx_seq %u requested", req_seq);
3154d2afdd38SMatthias Ringwald                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
31557b7901d8SMatthias Ringwald                                     tx_state->retransmission_requested = 1;
31567b7901d8SMatthias Ringwald                                     l2cap_channel->srej_active = 1;
31577b7901d8SMatthias Ringwald                                 }
31589ffcbce4SMatthias Ringwald                                 break;
3159bdbe2e49SMatthias Ringwald                             default:
3160bdbe2e49SMatthias Ringwald                                 break;
3161bdbe2e49SMatthias Ringwald                         }
316227e0774aSMatthias Ringwald                         break;
316327e0774aSMatthias Ringwald                     } else {
316427e0774aSMatthias Ringwald                         // I-Frame
316527e0774aSMatthias Ringwald                         // get control
316627e0774aSMatthias Ringwald                         l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
316738f62777SMatthias Ringwald                         uint8_t tx_seq = (control >> 1) & 0x3f;
316838f62777SMatthias Ringwald                         log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
3169e8e9809fSMatthias Ringwald                         log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
317038f62777SMatthias Ringwald                         log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
31711e1a46bbSMatthias Ringwald                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
317211b576c5SMatthias Ringwald                         if (final){
317311b576c5SMatthias Ringwald                             // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
317411b576c5SMatthias Ringwald                             l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
317511b576c5SMatthias Ringwald                         }
317607c7de86SMatthias Ringwald 
317707c7de86SMatthias Ringwald                         // get SDU
317807c7de86SMatthias Ringwald                         const uint8_t * sdu_data = &packet[COMPLETE_L2CAP_HEADER+2];
31796574158aSMatthias Ringwald                         uint16_t        sdu_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
318007c7de86SMatthias Ringwald 
318107c7de86SMatthias Ringwald                         // assert SDU size is smaller or equal to our buffers
318207c7de86SMatthias Ringwald                         if (sdu_len > l2cap_channel->local_mps) break;
318307c7de86SMatthias Ringwald 
318438f62777SMatthias Ringwald                         // check ordering
318538f62777SMatthias Ringwald                         if (l2cap_channel->expected_tx_seq == tx_seq){
318638f62777SMatthias Ringwald                             log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
318738f62777SMatthias Ringwald                             l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3188f85ade6bSMatthias Ringwald                             l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3189d48432d4SMatthias Ringwald 
3190e32be409SMatthias Ringwald                             // process SDU
319107c7de86SMatthias Ringwald                             l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, sdu_data, sdu_len);
3192d48432d4SMatthias Ringwald 
319370734707SMatthias Ringwald                             // process stored segments
319470734707SMatthias Ringwald                             while (1){
319570734707SMatthias Ringwald                                 int index = l2cap_channel->rx_store_index;
319670734707SMatthias Ringwald                                 l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
319770734707SMatthias Ringwald                                 if (!rx_state->valid) break;
3198f85ade6bSMatthias Ringwald 
3199f85ade6bSMatthias Ringwald                                 log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
3200f85ade6bSMatthias Ringwald                                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3201f85ade6bSMatthias Ringwald                                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3202f85ade6bSMatthias Ringwald 
320370734707SMatthias Ringwald                                 rx_state->valid = 0;
320470734707SMatthias Ringwald                                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
3205f85ade6bSMatthias Ringwald 
3206f85ade6bSMatthias Ringwald                                 // update rx store index
320770734707SMatthias Ringwald                                 index++;
320870734707SMatthias Ringwald                                 if (index >= l2cap_channel->num_rx_buffers){
320970734707SMatthias Ringwald                                     index = 0;
321070734707SMatthias Ringwald                                 }
321170734707SMatthias Ringwald                                 l2cap_channel->rx_store_index = index;
321270734707SMatthias Ringwald                             }
321370734707SMatthias Ringwald 
3214f85ade6bSMatthias Ringwald                             //
3215f85ade6bSMatthias Ringwald                             l2cap_channel->send_supervisor_frame_receiver_ready = 1;
3216f85ade6bSMatthias Ringwald 
3217c7309e8dSMatthias Ringwald                         } else {
3218df2191a7SMatthias Ringwald                             int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
3219df2191a7SMatthias Ringwald                             if (delta < 2){
322070734707SMatthias Ringwald                                 // store segment
322107c7de86SMatthias Ringwald                                 l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, sdu_data, sdu_len);
322270734707SMatthias Ringwald 
3223df2191a7SMatthias Ringwald                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
3224df2191a7SMatthias Ringwald                                 l2cap_channel->send_supervisor_frame_selective_reject = 1;
3225df2191a7SMatthias Ringwald                             } else {
3226df2191a7SMatthias Ringwald                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
3227c7309e8dSMatthias Ringwald                                 l2cap_channel->send_supervisor_frame_reject = 1;
322827e0774aSMatthias Ringwald                             }
322938f62777SMatthias Ringwald                         }
3230df2191a7SMatthias Ringwald                     }
323127e0774aSMatthias Ringwald                     break;
323227e0774aSMatthias Ringwald                 }
323327e0774aSMatthias Ringwald #endif
32343d50b4baSMatthias Ringwald                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
323500d93d79Smatthias.ringwald             }
3236bb0a72a6SMatthias Ringwald             break;
3237bb0a72a6SMatthias Ringwald     }
3238bb0a72a6SMatthias Ringwald #else
3239bb0a72a6SMatthias Ringwald     UNUSED(handle); // ok: no code
3240bb0a72a6SMatthias Ringwald     UNUSED(packet); // ok: no code
3241bb0a72a6SMatthias Ringwald     UNUSED(size);   // ok: no code
324209e9d05bSMatthias Ringwald #endif
3243bb0a72a6SMatthias Ringwald }
3244bb0a72a6SMatthias Ringwald 
3245bb0a72a6SMatthias Ringwald static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3246bb0a72a6SMatthias Ringwald #ifdef ENABLE_BLE
3247bb0a72a6SMatthias Ringwald 
3248bb0a72a6SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
3249bb0a72a6SMatthias Ringwald     l2cap_channel_t * l2cap_channel;
3250bb0a72a6SMatthias Ringwald #endif
3251bb0a72a6SMatthias Ringwald     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3252bb0a72a6SMatthias Ringwald     switch (channel_id) {
3253bb0a72a6SMatthias Ringwald 
3254bb0a72a6SMatthias Ringwald         case L2CAP_CID_SIGNALING_LE: {
3255bb0a72a6SMatthias Ringwald             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
3256adcfabadSMatthias Ringwald             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
3257adcfabadSMatthias Ringwald             if (COMPLETE_L2CAP_HEADER + 4 + len > size) break;
3258bb0a72a6SMatthias Ringwald             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
3259bb0a72a6SMatthias Ringwald             if (!valid){
3260bb0a72a6SMatthias Ringwald                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3261bb0a72a6SMatthias Ringwald             }
3262bb0a72a6SMatthias Ringwald             break;
3263bb0a72a6SMatthias Ringwald         }
3264bb0a72a6SMatthias Ringwald 
3265bb0a72a6SMatthias Ringwald         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
3266bb0a72a6SMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback) {
3267bb0a72a6SMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_ATTRIBUTE_PROTOCOL].callback)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3268bb0a72a6SMatthias Ringwald             }
3269bb0a72a6SMatthias Ringwald             break;
3270bb0a72a6SMatthias Ringwald 
3271bb0a72a6SMatthias Ringwald         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
3272bb0a72a6SMatthias Ringwald             if (fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback) {
3273bb0a72a6SMatthias Ringwald                 (*fixed_channels[L2CAP_FIXED_CHANNEL_TABLE_INDEX_SECURITY_MANAGER_PROTOCOL].callback)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3274bb0a72a6SMatthias Ringwald             }
3275bb0a72a6SMatthias Ringwald             break;
3276bb0a72a6SMatthias Ringwald 
3277bb0a72a6SMatthias Ringwald         default:
3278bb0a72a6SMatthias Ringwald 
3279a3dc965aSMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
328064e11ca9SMatthias Ringwald             l2cap_channel = l2cap_le_get_channel_for_local_cid(channel_id);
328164e11ca9SMatthias Ringwald             if (l2cap_channel) {
328285aeef60SMatthias Ringwald                 // credit counting
328385aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming == 0){
328485aeef60SMatthias Ringwald                     log_error("LE Data Channel packet received but no incoming credits");
328585aeef60SMatthias Ringwald                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
328685aeef60SMatthias Ringwald                     break;
328785aeef60SMatthias Ringwald                 }
328885aeef60SMatthias Ringwald                 l2cap_channel->credits_incoming--;
328985aeef60SMatthias Ringwald 
329085aeef60SMatthias Ringwald                 // automatic credits
329185aeef60SMatthias Ringwald                 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){
329285aeef60SMatthias Ringwald                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
329385aeef60SMatthias Ringwald                 }
329485aeef60SMatthias Ringwald 
3295cd529728SMatthias Ringwald                 // first fragment
3296cd529728SMatthias Ringwald                 uint16_t pos = 0;
3297cd529728SMatthias Ringwald                 if (!l2cap_channel->receive_sdu_len){
3298bb98c113SMatthias Ringwald                     uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3299bb98c113SMatthias Ringwald                     if(sdu_len > l2cap_channel->local_mtu) break;   // SDU would be larger than our buffer
3300bb98c113SMatthias Ringwald                     l2cap_channel->receive_sdu_len = sdu_len;
3301cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_pos = 0;
3302cd529728SMatthias Ringwald                     pos  += 2;
3303cd529728SMatthias Ringwald                     size -= 2;
3304cd529728SMatthias Ringwald                 }
3305bb98c113SMatthias Ringwald                 uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
3306bb98c113SMatthias Ringwald                 uint16_t remaining_space = l2cap_channel->local_mtu - l2cap_channel->receive_sdu_pos;
3307bb98c113SMatthias Ringwald                 if (fragment_size > remaining_space) break;         // SDU would cause buffer overrun
3308bb98c113SMatthias Ringwald                 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], fragment_size);
3309cd529728SMatthias Ringwald                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
3310cd529728SMatthias Ringwald                 // done?
331163f0ac45SMatthias Ringwald                 log_info("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
3312cd529728SMatthias Ringwald                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
3313cd529728SMatthias Ringwald                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
3314cd529728SMatthias Ringwald                     l2cap_channel->receive_sdu_len = 0;
3315cd529728SMatthias Ringwald                 }
331663f0ac45SMatthias Ringwald             } else {
331763f0ac45SMatthias Ringwald                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
331864e11ca9SMatthias Ringwald             }
331964e11ca9SMatthias Ringwald #endif
33205652b5ffS[email protected]             break;
33215652b5ffS[email protected]     }
3322bb0a72a6SMatthias Ringwald #else
3323bb0a72a6SMatthias Ringwald     UNUSED(handle); // ok: no code
3324bb0a72a6SMatthias Ringwald     UNUSED(packet); // ok: no code
3325bb0a72a6SMatthias Ringwald     UNUSED(size);   // ok: no code
3326bb0a72a6SMatthias Ringwald #endif
3327bb0a72a6SMatthias Ringwald }
3328bb0a72a6SMatthias Ringwald 
3329bb0a72a6SMatthias Ringwald static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
3330bb0a72a6SMatthias Ringwald     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
3331bb0a72a6SMatthias Ringwald     UNUSED(channel);        // ok: there is no channel
3332bb0a72a6SMatthias Ringwald 
3333adcfabadSMatthias Ringwald     // Assert full L2CAP header present
3334adcfabadSMatthias Ringwald     if (size < COMPLETE_L2CAP_HEADER) return;
3335adcfabadSMatthias Ringwald 
3336bb0a72a6SMatthias Ringwald     // Dispatch to Classic or LE handler
3337bb0a72a6SMatthias Ringwald     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
3338bb0a72a6SMatthias Ringwald     hci_connection_t *conn = hci_connection_for_handle(handle);
3339bb0a72a6SMatthias Ringwald     if (!conn) return;
3340bb0a72a6SMatthias Ringwald     if (conn->address_type == BD_ADDR_TYPE_CLASSIC){
3341bb0a72a6SMatthias Ringwald         l2cap_acl_classic_handler(handle, packet, size);
3342bb0a72a6SMatthias Ringwald     } else {
3343bb0a72a6SMatthias Ringwald         l2cap_acl_le_handler(handle, packet, size);
3344bb0a72a6SMatthias Ringwald     }
334500d93d79Smatthias.ringwald 
33461eb2563eS[email protected]     l2cap_run();
33472718e2e7Smatthias.ringwald }
334800d93d79Smatthias.ringwald 
334909e9d05bSMatthias Ringwald // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
335009e9d05bSMatthias Ringwald void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
335109e9d05bSMatthias Ringwald     int index = l2cap_fixed_channel_table_index_for_channel_id(channel_id);
335209e9d05bSMatthias Ringwald     if (index < 0) return;
335309e9d05bSMatthias Ringwald     fixed_channels[index].callback = the_packet_handler;
335409e9d05bSMatthias Ringwald }
335509e9d05bSMatthias Ringwald 
335609e9d05bSMatthias Ringwald #ifdef ENABLE_CLASSIC
335715ec09bbSmatthias.ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
335827a923d0Smatthias.ringwald void l2cap_finialize_channel_close(l2cap_channel_t * channel){
3359f62db1e3Smatthias.ringwald     channel->state = L2CAP_STATE_CLOSED;
3360f62db1e3Smatthias.ringwald     l2cap_emit_channel_closed(channel);
3361f62db1e3Smatthias.ringwald     // discard channel
33629dcb2fb2S[email protected]     l2cap_stop_rtx(channel);
3363665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3364d3a9df87Smatthias.ringwald     btstack_memory_l2cap_channel_free(channel);
3365c8e4258aSmatthias.ringwald }
33661e6aba47Smatthias.ringwald 
33678f2a52f4SMatthias Ringwald static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3368665d90f2SMatthias Ringwald     btstack_linked_list_iterator_t it;
3369665d90f2SMatthias Ringwald     btstack_linked_list_iterator_init(&it, services);
3370665d90f2SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
3371665d90f2SMatthias Ringwald         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
33729d9bbc01Smatthias.ringwald         if ( service->psm == psm){
33739d9bbc01Smatthias.ringwald             return service;
33749d9bbc01Smatthias.ringwald         };
33759d9bbc01Smatthias.ringwald     }
33769d9bbc01Smatthias.ringwald     return NULL;
33779d9bbc01Smatthias.ringwald }
33789d9bbc01Smatthias.ringwald 
33797192e786SMatthias Ringwald static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
33807192e786SMatthias Ringwald     return l2cap_get_service_internal(&l2cap_services, psm);
33817192e786SMatthias Ringwald }
33827192e786SMatthias Ringwald 
3383e0abb8e7S[email protected] 
3384be2053a6SMatthias 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){
3385be2053a6SMatthias Ringwald 
3386be2053a6SMatthias Ringwald     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
3387e0abb8e7S[email protected] 
33884bb582b6Smatthias.ringwald     // check for alread registered psm
33899d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
3390277abc2cSmatthias.ringwald     if (service) {
3391be2053a6SMatthias Ringwald         log_error("l2cap_register_service: PSM %u already registered", psm);
3392be2053a6SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
3393277abc2cSmatthias.ringwald     }
33949d9bbc01Smatthias.ringwald 
33954bb582b6Smatthias.ringwald     // alloc structure
3396bb69aaaeS[email protected]     service = btstack_memory_l2cap_service_get();
3397277abc2cSmatthias.ringwald     if (!service) {
3398be2053a6SMatthias Ringwald         log_error("l2cap_register_service: no memory for l2cap_service_t");
3399be2053a6SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
3400277abc2cSmatthias.ringwald     }
34019d9bbc01Smatthias.ringwald 
34029d9bbc01Smatthias.ringwald     // fill in
34039d9bbc01Smatthias.ringwald     service->psm = psm;
34049d9bbc01Smatthias.ringwald     service->mtu = mtu;
340505ae8de3SMatthias Ringwald     service->packet_handler = service_packet_handler;
3406df3354fcS[email protected]     service->required_security_level = security_level;
34079d9bbc01Smatthias.ringwald 
34089d9bbc01Smatthias.ringwald     // add to services list
3409665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
3410c0e866bfSmatthias.ringwald 
3411c0e866bfSmatthias.ringwald     // enable page scan
341215a95bd5SMatthias Ringwald     gap_connectable_control(1);
34135842b6d9Smatthias.ringwald 
3414be2053a6SMatthias Ringwald     return 0;
34159d9bbc01Smatthias.ringwald }
34169d9bbc01Smatthias.ringwald 
34177e8856ebSMatthias Ringwald uint8_t l2cap_unregister_service(uint16_t psm){
3418e0abb8e7S[email protected] 
3419e0abb8e7S[email protected]     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
3420e0abb8e7S[email protected] 
34219d9bbc01Smatthias.ringwald     l2cap_service_t *service = l2cap_get_service(psm);
34227e8856ebSMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3423665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
3424d3a9df87Smatthias.ringwald     btstack_memory_l2cap_service_free(service);
3425c0e866bfSmatthias.ringwald 
3426c0e866bfSmatthias.ringwald     // disable page scan when no services registered
34277e8856ebSMatthias Ringwald     if (btstack_linked_list_empty(&l2cap_services)) {
342815a95bd5SMatthias Ringwald         gap_connectable_control(0);
34299d9bbc01Smatthias.ringwald     }
34307e8856ebSMatthias Ringwald     return 0;
34317e8856ebSMatthias Ringwald }
343209e9d05bSMatthias Ringwald #endif
34339d9bbc01Smatthias.ringwald 
34347192e786SMatthias Ringwald 
3435cab29d48SMatthias Ringwald #ifdef ENABLE_LE_DATA_CHANNELS
343683fd9c76SMatthias Ringwald 
343757be49d6SMatthias Ringwald static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
343857be49d6SMatthias Ringwald     if (!channel->waiting_for_can_send_now) return;
343957be49d6SMatthias Ringwald     if (channel->send_sdu_buffer) return;
344057be49d6SMatthias Ringwald     channel->waiting_for_can_send_now = 0;
344157be49d6SMatthias Ringwald     log_info("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
344257be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
344357be49d6SMatthias Ringwald }
344457be49d6SMatthias Ringwald 
344557be49d6SMatthias Ringwald // 1BH2222
344657be49d6SMatthias Ringwald static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
344757be49d6SMatthias 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",
344857be49d6SMatthias Ringwald              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
344957be49d6SMatthias Ringwald     uint8_t event[19];
345057be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
345157be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
345257be49d6SMatthias Ringwald     event[2] = channel->address_type;
345357be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[3]);
345457be49d6SMatthias Ringwald     little_endian_store_16(event,  9, channel->con_handle);
345557be49d6SMatthias Ringwald     little_endian_store_16(event, 11, channel->psm);
345657be49d6SMatthias Ringwald     little_endian_store_16(event, 13, channel->local_cid);
345757be49d6SMatthias Ringwald     little_endian_store_16(event, 15, channel->remote_cid);
345857be49d6SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_mtu);
345957be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
346057be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
346157be49d6SMatthias Ringwald }
346257be49d6SMatthias Ringwald // 11BH22222
346357be49d6SMatthias Ringwald static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
346457be49d6SMatthias 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",
346557be49d6SMatthias Ringwald              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
346657be49d6SMatthias Ringwald              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
3467c99bb618SMatthias Ringwald     uint8_t event[23];
346857be49d6SMatthias Ringwald     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
346957be49d6SMatthias Ringwald     event[1] = sizeof(event) - 2;
347057be49d6SMatthias Ringwald     event[2] = status;
347157be49d6SMatthias Ringwald     event[3] = channel->address_type;
347257be49d6SMatthias Ringwald     reverse_bd_addr(channel->address, &event[4]);
347357be49d6SMatthias Ringwald     little_endian_store_16(event, 10, channel->con_handle);
3474c99bb618SMatthias Ringwald     event[12] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
3475c99bb618SMatthias Ringwald     little_endian_store_16(event, 13, channel->psm);
3476c99bb618SMatthias Ringwald     little_endian_store_16(event, 15, channel->local_cid);
3477c99bb618SMatthias Ringwald     little_endian_store_16(event, 17, channel->remote_cid);
3478c99bb618SMatthias Ringwald     little_endian_store_16(event, 19, channel->local_mtu);
3479c99bb618SMatthias Ringwald     little_endian_store_16(event, 21, channel->remote_mtu);
348057be49d6SMatthias Ringwald     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
348157be49d6SMatthias Ringwald     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
348257be49d6SMatthias Ringwald }
348357be49d6SMatthias Ringwald 
348457be49d6SMatthias Ringwald static l2cap_channel_t * l2cap_le_get_channel_for_local_cid(uint16_t local_cid){
348557be49d6SMatthias Ringwald     btstack_linked_list_iterator_t it;
348657be49d6SMatthias Ringwald     btstack_linked_list_iterator_init(&it, &l2cap_le_channels);
348757be49d6SMatthias Ringwald     while (btstack_linked_list_iterator_has_next(&it)){
348857be49d6SMatthias Ringwald         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
348957be49d6SMatthias Ringwald         if ( channel->local_cid == local_cid) {
349057be49d6SMatthias Ringwald             return channel;
349157be49d6SMatthias Ringwald         }
349257be49d6SMatthias Ringwald     }
349357be49d6SMatthias Ringwald     return NULL;
349457be49d6SMatthias Ringwald }
349557be49d6SMatthias Ringwald 
349657be49d6SMatthias Ringwald // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
349757be49d6SMatthias Ringwald void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
349857be49d6SMatthias Ringwald     channel->state = L2CAP_STATE_CLOSED;
349957be49d6SMatthias Ringwald     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
350057be49d6SMatthias Ringwald     // discard channel
350157be49d6SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_channels, (btstack_linked_item_t *) channel);
350257be49d6SMatthias Ringwald     btstack_memory_l2cap_channel_free(channel);
350357be49d6SMatthias Ringwald }
350457be49d6SMatthias Ringwald 
3505e7d0c9aaSMatthias Ringwald static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
3506e7d0c9aaSMatthias Ringwald     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
35077192e786SMatthias Ringwald }
3508efedfb4cSMatthias Ringwald 
3509da144af5SMatthias Ringwald uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
35107192e786SMatthias Ringwald 
3511da144af5SMatthias Ringwald     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
35127192e786SMatthias Ringwald 
35137192e786SMatthias Ringwald     // check for alread registered psm
35147192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
35157192e786SMatthias Ringwald     if (service) {
3516da144af5SMatthias Ringwald         return L2CAP_SERVICE_ALREADY_REGISTERED;
35177192e786SMatthias Ringwald     }
35187192e786SMatthias Ringwald 
35197192e786SMatthias Ringwald     // alloc structure
35207192e786SMatthias Ringwald     service = btstack_memory_l2cap_service_get();
35217192e786SMatthias Ringwald     if (!service) {
35227192e786SMatthias Ringwald         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
3523da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
35247192e786SMatthias Ringwald     }
35257192e786SMatthias Ringwald 
35267192e786SMatthias Ringwald     // fill in
35277192e786SMatthias Ringwald     service->psm = psm;
3528da144af5SMatthias Ringwald     service->mtu = 0;
35297192e786SMatthias Ringwald     service->packet_handler = packet_handler;
35307192e786SMatthias Ringwald     service->required_security_level = security_level;
35317192e786SMatthias Ringwald 
35327192e786SMatthias Ringwald     // add to services list
3533665d90f2SMatthias Ringwald     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
35347192e786SMatthias Ringwald 
35357192e786SMatthias Ringwald     // done
3536da144af5SMatthias Ringwald     return 0;
35377192e786SMatthias Ringwald }
35387192e786SMatthias Ringwald 
3539da144af5SMatthias Ringwald uint8_t l2cap_le_unregister_service(uint16_t psm) {
35407192e786SMatthias Ringwald     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
35417192e786SMatthias Ringwald     l2cap_service_t *service = l2cap_le_get_service(psm);
35429367f9b0SMatthias Ringwald     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3543da144af5SMatthias Ringwald 
3544665d90f2SMatthias Ringwald     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
35457192e786SMatthias Ringwald     btstack_memory_l2cap_service_free(service);
3546da144af5SMatthias Ringwald     return 0;
35477192e786SMatthias Ringwald }
3548da144af5SMatthias Ringwald 
3549da144af5SMatthias Ringwald uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
3550e7d0c9aaSMatthias Ringwald     // get channel
3551e7d0c9aaSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3552e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3553e7d0c9aaSMatthias Ringwald 
3554e7d0c9aaSMatthias Ringwald     // validate state
3555e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3556e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
3557e7d0c9aaSMatthias Ringwald     }
3558e7d0c9aaSMatthias Ringwald 
3559efedfb4cSMatthias Ringwald     // set state accept connection
356023017473SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
356123017473SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
356223017473SMatthias Ringwald     channel->local_mtu = mtu;
356385aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
356485aeef60SMatthias Ringwald     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
356585aeef60SMatthias Ringwald 
356685aeef60SMatthias Ringwald     // test
356763f0ac45SMatthias Ringwald     // channel->new_credits_incoming = 1;
3568e7d0c9aaSMatthias Ringwald 
3569e7d0c9aaSMatthias Ringwald     // go
3570e7d0c9aaSMatthias Ringwald     l2cap_run();
3571da144af5SMatthias Ringwald     return 0;
3572da144af5SMatthias Ringwald }
3573da144af5SMatthias Ringwald 
3574da144af5SMatthias Ringwald /**
3575da144af5SMatthias Ringwald  * @brief Deny incoming LE Data Channel connection due to resource constraints
3576da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3577da144af5SMatthias Ringwald  */
3578da144af5SMatthias Ringwald 
3579da144af5SMatthias Ringwald uint8_t l2cap_le_decline_connection(uint16_t local_cid){
3580e7d0c9aaSMatthias Ringwald     // get channel
3581e7d0c9aaSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3582e7d0c9aaSMatthias Ringwald     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3583e7d0c9aaSMatthias Ringwald 
3584e7d0c9aaSMatthias Ringwald     // validate state
3585e7d0c9aaSMatthias Ringwald     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3586e7d0c9aaSMatthias Ringwald         return ERROR_CODE_COMMAND_DISALLOWED;
3587e7d0c9aaSMatthias Ringwald     }
3588e7d0c9aaSMatthias Ringwald 
3589efedfb4cSMatthias Ringwald     // set state decline connection
3590e7d0c9aaSMatthias Ringwald     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
3591e7d0c9aaSMatthias Ringwald     channel->reason = 0x04; // no resources available
3592e7d0c9aaSMatthias Ringwald     l2cap_run();
3593da144af5SMatthias Ringwald     return 0;
3594da144af5SMatthias Ringwald }
3595da144af5SMatthias Ringwald 
35967dafa750SMatthias Ringwald uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
3597da144af5SMatthias Ringwald     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
3598efedfb4cSMatthias Ringwald     uint16_t * out_local_cid) {
3599efedfb4cSMatthias Ringwald 
36007dafa750SMatthias Ringwald     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
3601da144af5SMatthias Ringwald 
36027dafa750SMatthias Ringwald 
36037dafa750SMatthias Ringwald     hci_connection_t * connection = hci_connection_for_handle(con_handle);
36047dafa750SMatthias Ringwald     if (!connection) {
36057dafa750SMatthias Ringwald         log_error("no hci_connection for handle 0x%04x", con_handle);
36067dafa750SMatthias Ringwald         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
36077dafa750SMatthias Ringwald     }
36087dafa750SMatthias Ringwald 
36097dafa750SMatthias Ringwald     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, connection->address, connection->address_type, psm, mtu, security_level);
3610da144af5SMatthias Ringwald     if (!channel) {
3611da144af5SMatthias Ringwald         return BTSTACK_MEMORY_ALLOC_FAILED;
3612da144af5SMatthias Ringwald     }
3613e7d0c9aaSMatthias Ringwald     log_info("l2cap_le_create_channel %p", channel);
3614da144af5SMatthias Ringwald 
3615da144af5SMatthias Ringwald     // store local_cid
3616da144af5SMatthias Ringwald     if (out_local_cid){
3617da144af5SMatthias Ringwald        *out_local_cid = channel->local_cid;
3618da144af5SMatthias Ringwald     }
3619da144af5SMatthias Ringwald 
36207dafa750SMatthias Ringwald     // provide buffer
36217dafa750SMatthias Ringwald     channel->con_handle = con_handle;
3622cd529728SMatthias Ringwald     channel->receive_sdu_buffer = receive_sdu_buffer;
36237dafa750SMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
362485aeef60SMatthias Ringwald     channel->new_credits_incoming = initial_credits;
362585aeef60SMatthias Ringwald     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
362685aeef60SMatthias Ringwald 
3627efedfb4cSMatthias Ringwald     // add to connections list
3628efedfb4cSMatthias Ringwald     btstack_linked_list_add(&l2cap_le_channels, (btstack_linked_item_t *) channel);
3629efedfb4cSMatthias Ringwald 
36307dafa750SMatthias Ringwald     // go
363163f0ac45SMatthias Ringwald     l2cap_run();
3632da144af5SMatthias Ringwald     return 0;
3633da144af5SMatthias Ringwald }
3634da144af5SMatthias Ringwald 
3635da144af5SMatthias Ringwald /**
3636da144af5SMatthias Ringwald  * @brief Provide credtis for LE Data Channel
3637da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3638da144af5SMatthias Ringwald  * @param credits               Number additional credits for peer
3639da144af5SMatthias Ringwald  */
364064e11ca9SMatthias Ringwald uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
364163f0ac45SMatthias Ringwald 
364263f0ac45SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
364363f0ac45SMatthias Ringwald     if (!channel) {
364463f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
364563f0ac45SMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
364663f0ac45SMatthias Ringwald     }
364763f0ac45SMatthias Ringwald 
3648efedfb4cSMatthias Ringwald     // check state
364963f0ac45SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN){
365063f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
365163f0ac45SMatthias Ringwald     }
365263f0ac45SMatthias Ringwald 
365363f0ac45SMatthias Ringwald     // assert incoming credits + credits <= 0xffff
365463f0ac45SMatthias Ringwald     uint32_t total_credits = channel->credits_incoming;
365563f0ac45SMatthias Ringwald     total_credits += channel->new_credits_incoming;
365663f0ac45SMatthias Ringwald     total_credits += credits;
365763f0ac45SMatthias Ringwald     if (total_credits > 0xffff){
365863f0ac45SMatthias Ringwald         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
365963f0ac45SMatthias Ringwald             channel->new_credits_incoming, credits);
366063f0ac45SMatthias Ringwald     }
366163f0ac45SMatthias Ringwald 
3662efedfb4cSMatthias Ringwald     // set credits_granted
366363f0ac45SMatthias Ringwald     channel->new_credits_incoming += credits;
366463f0ac45SMatthias Ringwald 
366563f0ac45SMatthias Ringwald     // go
366663f0ac45SMatthias Ringwald     l2cap_run();
3667da144af5SMatthias Ringwald     return 0;
3668da144af5SMatthias Ringwald }
3669da144af5SMatthias Ringwald 
3670da144af5SMatthias Ringwald /**
3671da144af5SMatthias Ringwald  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
3672da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3673da144af5SMatthias Ringwald  */
367464e11ca9SMatthias Ringwald int l2cap_le_can_send_now(uint16_t local_cid){
367544276248SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
367644276248SMatthias Ringwald     if (!channel) {
367744276248SMatthias Ringwald         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
3678da144af5SMatthias Ringwald         return 0;
3679da144af5SMatthias Ringwald     }
3680da144af5SMatthias Ringwald 
368144276248SMatthias Ringwald     // check state
368244276248SMatthias Ringwald     if (channel->state != L2CAP_STATE_OPEN) return 0;
368344276248SMatthias Ringwald 
368444276248SMatthias Ringwald     // check queue
368544276248SMatthias Ringwald     if (channel->send_sdu_buffer) return 0;
368644276248SMatthias Ringwald 
368744276248SMatthias Ringwald     // fine, go ahead
368844276248SMatthias Ringwald     return 1;
368944276248SMatthias Ringwald }
369044276248SMatthias Ringwald 
3691da144af5SMatthias Ringwald /**
3692da144af5SMatthias Ringwald  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
3693da144af5SMatthias Ringwald  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
3694da144af5SMatthias Ringwald  *       so packet handler should be ready to handle it
3695da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3696da144af5SMatthias Ringwald  */
369764e11ca9SMatthias Ringwald uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
369844276248SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
369944276248SMatthias Ringwald     if (!channel) {
370044276248SMatthias Ringwald         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
370144276248SMatthias Ringwald         return 0;
370244276248SMatthias Ringwald     }
370344276248SMatthias Ringwald     channel->waiting_for_can_send_now = 1;
370444276248SMatthias Ringwald     l2cap_le_notify_channel_can_send(channel);
3705da144af5SMatthias Ringwald     return 0;
3706da144af5SMatthias Ringwald }
3707da144af5SMatthias Ringwald 
3708da144af5SMatthias Ringwald /**
3709da144af5SMatthias Ringwald  * @brief Send data via LE Data Channel
3710da144af5SMatthias Ringwald  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
3711da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3712da144af5SMatthias Ringwald  * @param data                  data to send
3713da144af5SMatthias Ringwald  * @param size                  data size
3714da144af5SMatthias Ringwald  */
371564e11ca9SMatthias Ringwald uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
371664e11ca9SMatthias Ringwald 
371764e11ca9SMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
371864e11ca9SMatthias Ringwald     if (!channel) {
371964e11ca9SMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
3720828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
372164e11ca9SMatthias Ringwald     }
372264e11ca9SMatthias Ringwald 
372364e11ca9SMatthias Ringwald     if (len > channel->remote_mtu){
372464e11ca9SMatthias Ringwald         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
372564e11ca9SMatthias Ringwald         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
372664e11ca9SMatthias Ringwald     }
372764e11ca9SMatthias Ringwald 
37287f107edaSMatthias Ringwald     if (channel->send_sdu_buffer){
372964e11ca9SMatthias Ringwald         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
373064e11ca9SMatthias Ringwald         return BTSTACK_ACL_BUFFERS_FULL;
373164e11ca9SMatthias Ringwald     }
373264e11ca9SMatthias Ringwald 
37337f107edaSMatthias Ringwald     channel->send_sdu_buffer = data;
37347f107edaSMatthias Ringwald     channel->send_sdu_len    = len;
37357f107edaSMatthias Ringwald     channel->send_sdu_pos    = 0;
373664e11ca9SMatthias Ringwald 
37377f107edaSMatthias Ringwald     l2cap_run();
37387f107edaSMatthias Ringwald     return 0;
3739da144af5SMatthias Ringwald }
3740da144af5SMatthias Ringwald 
3741da144af5SMatthias Ringwald /**
3742da144af5SMatthias Ringwald  * @brief Disconnect from LE Data Channel
3743da144af5SMatthias Ringwald  * @param local_cid             L2CAP LE Data Channel Identifier
3744da144af5SMatthias Ringwald  */
3745828a7f7aSMatthias Ringwald uint8_t l2cap_le_disconnect(uint16_t local_cid)
3746da144af5SMatthias Ringwald {
3747828a7f7aSMatthias Ringwald     l2cap_channel_t * channel = l2cap_le_get_channel_for_local_cid(local_cid);
3748828a7f7aSMatthias Ringwald     if (!channel) {
3749828a7f7aSMatthias Ringwald         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
3750828a7f7aSMatthias Ringwald         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3751828a7f7aSMatthias Ringwald     }
3752828a7f7aSMatthias Ringwald 
3753828a7f7aSMatthias Ringwald     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3754828a7f7aSMatthias Ringwald     l2cap_run();
3755da144af5SMatthias Ringwald     return 0;
3756da144af5SMatthias Ringwald }
3757da144af5SMatthias Ringwald 
37587f02f414SMatthias Ringwald #endif
3759