xref: /btstack/src/l2cap.c (revision 7cdc89a533ca236b2c2564b759993b788bae89d3)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 #define BTSTACK_FILE__ "l2cap.c"
39 
40 /*
41  *  l2cap.c
42  *
43  *  Logical Link Control and Adaption Protocl (L2CAP)
44  *
45  *  Created by Matthias Ringwald on 5/16/09.
46  */
47 
48 #include "l2cap.h"
49 #include "hci.h"
50 #include "hci_dump.h"
51 #include "bluetooth_sdp.h"
52 #include "bluetooth_psm.h"
53 #include "btstack_debug.h"
54 #include "btstack_event.h"
55 #include "btstack_memory.h"
56 
57 #include <stdarg.h>
58 #include <string.h>
59 
60 #include <stdio.h>
61 
62 /*
63  * @brief L2CAP Supervisory function in S-Frames
64  */
65 typedef enum {
66     L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY = 0,
67     L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT,
68     L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY,
69     L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT
70 } l2cap_supervisory_function_t;
71 
72 /**
73  * @brief L2CAP Information Types used in Information Request & Response
74  */
75 typedef enum {
76   L2CAP_INFO_TYPE_CONNECTIONLESS_MTU = 1,
77   L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED,
78   L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED,
79 } l2cap_info_type_t;
80 
81 /**
82  * @brief L2CAP Configuration Option Types used in Configurateion Request & Response
83  */
84 typedef enum {
85   L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT = 1,
86   L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT,
87   L2CAP_CONFIG_OPTION_TYPE_QUALITY_OF_SERVICE,
88   L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL,
89   L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE,
90   L2CAP_CONFIG_OPTION_TYPE_EXTENDED_FLOW_SPECIFICATION,
91   L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE,
92 } l2cap_config_option_type_t;
93 
94 
95 #define L2CAP_SIG_ID_INVALID 0
96 
97 // size of HCI ACL + L2CAP Header for regular data packets (8)
98 #define COMPLETE_L2CAP_HEADER (HCI_ACL_HEADER_SIZE + L2CAP_HEADER_SIZE)
99 
100 // L2CAP Configuration Result Codes
101 #define L2CAP_CONF_RESULT_SUCCESS                  0x0000
102 #define L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS  0x0001
103 #define L2CAP_CONF_RESULT_REJECT                   0x0002
104 #define L2CAP_CONF_RESULT_UNKNOWN_OPTIONS          0x0003
105 #define L2CAP_CONF_RESULT_PENDING                  0x0004
106 #define L2CAP_CONF_RESULT_FLOW_SPEC_REJECTED       0x0005
107 
108 // L2CAP Reject Result Codes
109 #define L2CAP_REJ_CMD_UNKNOWN                      0x0000
110 
111 // Response Timeout eXpired
112 #define L2CAP_RTX_TIMEOUT_MS   10000
113 
114 // Extended Response Timeout eXpired
115 #define L2CAP_ERTX_TIMEOUT_MS 120000
116 
117 // nr of buffered acl packets in outgoing queue to get max performance
118 #define NR_BUFFERED_ACL_PACKETS 3
119 
120 // used to cache l2cap rejects, echo, and informational requests
121 #define NR_PENDING_SIGNALING_RESPONSES 3
122 
123 // nr of credits provided to remote if credits fall below watermark
124 #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK 5
125 #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT 5
126 
127 // offsets for L2CAP SIGNALING COMMANDS
128 #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
129 #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
130 #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
131 #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
132 
133 #if defined(ENABLE_LE_DATA_CHANNELS) || defined(ENABLE_CLASSIC)
134 #define L2CAP_USES_CHANNELS
135 #endif
136 
137 // prototypes
138 static void l2cap_run(void);
139 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
140 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size );
141 static void l2cap_notify_channel_can_send(void);
142 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel);
143 static uint8_t  l2cap_next_sig_id(void);
144 static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid);
145 #ifdef ENABLE_CLASSIC
146 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel);
147 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel);
148 static void l2cap_finialize_channel_close(l2cap_channel_t *channel);
149 static inline l2cap_service_t * l2cap_get_service(uint16_t psm);
150 static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
151 static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
152 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel);
153 static int  l2cap_channel_ready_for_open(l2cap_channel_t *channel);
154 #endif
155 #ifdef ENABLE_LE_DATA_CHANNELS
156 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status);
157 static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel);
158 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel);
159 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel);
160 static void l2cap_le_finialize_channel_close(l2cap_channel_t *channel);
161 static void l2cap_le_send_pdu(l2cap_channel_t *channel);
162 static inline l2cap_service_t * l2cap_le_get_service(uint16_t psm);
163 #endif
164 #ifdef L2CAP_USES_CHANNELS
165 static uint16_t l2cap_next_local_cid(void);
166 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid);
167 static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code);
168 static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size);
169 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid);
170 static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, l2cap_channel_type_t channel_type, bd_addr_t address, bd_addr_type_t address_type,
171         uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level);
172 static void l2cap_free_channel_entry(l2cap_channel_t * channel);
173 #endif
174 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
175 static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel);
176 static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts);
177 static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts);
178 #endif
179 
180 // l2cap_fixed_channel_t entries
181 #ifdef ENABLE_BLE
182 static l2cap_fixed_channel_t l2cap_fixed_channel_att;
183 static l2cap_fixed_channel_t l2cap_fixed_channel_sm;
184 #endif
185 #ifdef ENABLE_CLASSIC
186 static l2cap_fixed_channel_t l2cap_fixed_channel_connectionless;
187 #endif
188 
189 #ifdef ENABLE_CLASSIC
190 static btstack_linked_list_t l2cap_services;
191 static uint8_t require_security_level2_for_outgoing_sdp;
192 static bd_addr_t l2cap_outgoing_classic_addr;
193 #endif
194 
195 #ifdef ENABLE_LE_DATA_CHANNELS
196 static btstack_linked_list_t l2cap_le_services;
197 #endif
198 
199 // single list of channels for Classic Channels, LE Data Channels, Classic Connectionless, ATT, and SM
200 static btstack_linked_list_t l2cap_channels;
201 #ifdef L2CAP_USES_CHANNELS
202 // next channel id for new connections
203 static uint16_t  local_source_cid  = 0x40;
204 #endif
205 // next signaling sequence number
206 static uint8_t   sig_seq_nr  = 0xff;
207 
208 // used to cache l2cap rejects, echo, and informational requests
209 static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
210 static int signaling_responses_pending;
211 static btstack_packet_callback_registration_t hci_event_callback_registration;
212 
213 #ifdef ENABLE_BLE
214 // only used for connection parameter update events
215 static btstack_packet_handler_t l2cap_event_packet_handler;
216 static uint16_t l2cap_le_custom_max_mtu;
217 #endif
218 
219 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
220 
221 // enable for testing
222 // #define L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL 16
223 
224 /*
225  * CRC lookup table for generator polynom D^16 + D^15 + D^2 + 1
226  */
227 static const uint16_t crc16_table[256] = {
228     0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
229     0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841,
230     0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41,
231     0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040,
232     0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441,
233     0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840,
234     0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40,
235     0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041,
236     0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
237     0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840,
238     0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
239     0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041,
240     0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440,
241     0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841,
242     0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41,
243     0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040,
244 };
245 
246 static uint16_t crc16_calc(uint8_t * data, uint16_t len){
247     uint16_t crc = 0;   // initial value = 0
248     while (len--){
249         crc = (crc >> 8) ^ crc16_table[ (crc ^ ((uint16_t) *data++)) & 0x00FF ];
250     }
251     return crc;
252 }
253 
254 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){
255     return (((uint16_t) sar) << 14) | (req_seq << 8) | (final << 7) | (tx_seq << 1) | 0;
256 }
257 
258 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){
259     return (req_seq << 8) | (final << 7) | (poll << 4) | (((int) supervisory_function) << 2) | 1;
260 }
261 
262 static int l2cap_next_ertm_seq_nr(int seq_nr){
263     return (seq_nr + 1) & 0x3f;
264 }
265 
266 static int l2cap_ertm_can_store_packet_now(l2cap_channel_t * channel){
267     // get num free tx buffers
268     int num_free_tx_buffers = channel->num_tx_buffers - channel->num_stored_tx_frames;
269     // calculate num tx buffers for remote MTU
270     int num_tx_buffers_for_max_remote_mtu;
271     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
272     if (channel->remote_mtu <= effective_mps){
273         // MTU fits into single packet
274         num_tx_buffers_for_max_remote_mtu = 1;
275     } else {
276         // include SDU Length
277         num_tx_buffers_for_max_remote_mtu = (channel->remote_mtu + 2 + (effective_mps - 1)) / effective_mps;
278     }
279     log_debug("num_free_tx_buffers %u, num_tx_buffers_for_max_remote_mtu %u", num_free_tx_buffers, num_tx_buffers_for_max_remote_mtu);
280     return num_tx_buffers_for_max_remote_mtu <= num_free_tx_buffers;
281 }
282 
283 static void l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel_t * l2cap_channel){
284     log_info("Retransmit unacknowleged frames");
285     l2cap_channel->unacked_frames = 0;;
286     l2cap_channel->tx_send_index  = l2cap_channel->tx_read_index;
287 }
288 
289 static void l2cap_ertm_next_tx_write_index(l2cap_channel_t * channel){
290     channel->tx_write_index++;
291     if (channel->tx_write_index < channel->num_tx_buffers) return;
292     channel->tx_write_index = 0;
293 }
294 
295 static void l2cap_ertm_start_monitor_timer(l2cap_channel_t * channel){
296     log_info("Start Monitor timer");
297     btstack_run_loop_remove_timer(&channel->monitor_timer);
298     btstack_run_loop_set_timer_handler(&channel->monitor_timer, &l2cap_ertm_monitor_timeout_callback);
299     btstack_run_loop_set_timer_context(&channel->monitor_timer, channel);
300     btstack_run_loop_set_timer(&channel->monitor_timer, channel->local_monitor_timeout_ms);
301     btstack_run_loop_add_timer(&channel->monitor_timer);
302 }
303 
304 static void l2cap_ertm_stop_monitor_timer(l2cap_channel_t * channel){
305     log_info("Stop Monitor timer");
306     btstack_run_loop_remove_timer(&channel->monitor_timer);
307 }
308 
309 static void l2cap_ertm_start_retransmission_timer(l2cap_channel_t * channel){
310     log_info("Start Retransmission timer");
311     btstack_run_loop_remove_timer(&channel->retransmission_timer);
312     btstack_run_loop_set_timer_handler(&channel->retransmission_timer, &l2cap_ertm_retransmission_timeout_callback);
313     btstack_run_loop_set_timer_context(&channel->retransmission_timer, channel);
314     btstack_run_loop_set_timer(&channel->retransmission_timer, channel->local_retransmission_timeout_ms);
315     btstack_run_loop_add_timer(&channel->retransmission_timer);
316 }
317 
318 static void l2cap_ertm_stop_retransmission_timer(l2cap_channel_t * l2cap_channel){
319     log_info("Stop Retransmission timer");
320     btstack_run_loop_remove_timer(&l2cap_channel->retransmission_timer);
321 }
322 
323 static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts){
324     log_info("Monitor timeout");
325     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
326 
327     // TODO: we assume that it's the oldest packet
328     l2cap_ertm_tx_packet_state_t * tx_state;
329     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
330 
331     // check retry count
332     if (tx_state->retry_count < l2cap_channel->remote_max_transmit){
333         // increment retry count
334         tx_state->retry_count++;
335 
336         // start retransmit
337         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
338 
339         // start monitor timer
340         l2cap_ertm_start_monitor_timer(l2cap_channel);
341 
342         // send RR/P=1
343         l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
344     } else {
345         log_info("Monitor timer expired & retry count >= max transmit -> disconnect");
346         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
347     }
348     l2cap_run();
349 }
350 
351 static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts){
352     log_info("Retransmission timeout");
353     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
354 
355     // TODO: we assume that it's the oldest packet
356     l2cap_ertm_tx_packet_state_t * tx_state;
357     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
358 
359     // set retry count = 1
360     tx_state->retry_count = 1;
361 
362     // start retransmit
363     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
364 
365     // start monitor timer
366     l2cap_ertm_start_monitor_timer(l2cap_channel);
367 
368     // send RR/P=1
369     l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
370     l2cap_run();
371 }
372 
373 static int l2cap_ertm_send_information_frame(l2cap_channel_t * channel, int index, int final){
374     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
375     hci_reserve_packet_buffer();
376     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
377     uint16_t control = l2cap_encanced_control_field_for_information_frame(tx_state->tx_seq, final, channel->req_seq, tx_state->sar);
378     log_info("I-Frame: control 0x%04x", control);
379     little_endian_store_16(acl_buffer, 8, control);
380     (void)memcpy(&acl_buffer[8 + 2],
381                  &channel->tx_packets_data[index * channel->local_mps],
382                  tx_state->len);
383     // (re-)start retransmission timer on
384     l2cap_ertm_start_retransmission_timer(channel);
385     // send
386     return l2cap_send_prepared(channel->local_cid, 2 + tx_state->len);
387 }
388 
389 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){
390     // get next index for storing packets
391     int index = channel->tx_write_index;
392 
393     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
394     tx_state->tx_seq = channel->next_tx_seq;
395     tx_state->sar = sar;
396     tx_state->retry_count = 0;
397 
398     uint8_t * tx_packet = &channel->tx_packets_data[index * channel->local_mps];
399     log_debug("index %u, local mps %u, remote mps %u, packet tx %p, len %u", index, channel->local_mps, channel->remote_mps, tx_packet, len);
400     int pos = 0;
401     if (sar == L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU){
402         little_endian_store_16(tx_packet, 0, sdu_length);
403         pos += 2;
404     }
405     (void)memcpy(&tx_packet[pos], data, len);
406     tx_state->len = pos + len;
407 
408     // update
409     channel->num_stored_tx_frames++;
410     channel->next_tx_seq = l2cap_next_ertm_seq_nr(channel->next_tx_seq);
411     l2cap_ertm_next_tx_write_index(channel);
412 
413     log_info("l2cap_ertm_store_fragment: tx_read_index %u, tx_write_index %u, num stored %u", channel->tx_read_index, channel->tx_write_index, channel->num_stored_tx_frames);
414 
415 }
416 
417 static int l2cap_ertm_send(l2cap_channel_t * channel, uint8_t * data, uint16_t len){
418     if (len > channel->remote_mtu){
419         log_error("l2cap_ertm_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
420         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
421     }
422 
423     if (!l2cap_ertm_can_store_packet_now(channel)){
424         log_error("l2cap_ertm_send cid 0x%02x, fragment store full", channel->local_cid);
425         return BTSTACK_ACL_BUFFERS_FULL;
426     }
427 
428     // check if it needs to get fragmented
429     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
430     if (len > effective_mps){
431         // fragmentation needed.
432         l2cap_segmentation_and_reassembly_t sar =  L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU;
433         int chunk_len;
434         while (len){
435             switch (sar){
436                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
437                     chunk_len = effective_mps - 2;    // sdu_length
438                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
439                     len -= chunk_len;
440                     sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU;
441                     break;
442                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
443                     chunk_len = effective_mps;
444                     if (chunk_len >= len){
445                         sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU;
446                         chunk_len = len;
447                     }
448                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
449                     len -= chunk_len;
450                     break;
451                 default:
452                     break;
453             }
454         }
455 
456     } else {
457         l2cap_ertm_store_fragment(channel, L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU, 0, data, len);
458     }
459 
460     // try to send
461     l2cap_notify_channel_can_send();
462     return 0;
463 }
464 
465 static uint16_t l2cap_setup_options_ertm_request(l2cap_channel_t * channel, uint8_t * config_options){
466     int pos = 0;
467     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
468     config_options[pos++] = 9;      // length
469     config_options[pos++] = (uint8_t) channel->mode;
470     config_options[pos++] = channel->num_rx_buffers;    // == TxWindows size
471     config_options[pos++] = channel->local_max_transmit;
472     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
473     pos += 2;
474     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
475     pos += 2;
476     little_endian_store_16( config_options, pos, channel->local_mps);
477     pos += 2;
478     //
479     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT;
480     config_options[pos++] = 2;     // length
481     little_endian_store_16(config_options, pos, channel->local_mtu);
482     pos += 2;
483 
484     // Issue: iOS (e.g. 10.2) uses "No FCS" as default while Core 5.0 specifies "FCS" as default
485     // Workaround: try to actively negotiate FCS option
486     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
487     config_options[pos++] = 1;     // length
488     config_options[pos++] = channel->fcs_option;
489     return pos; // 11+4+3=18
490 }
491 
492 static uint16_t l2cap_setup_options_ertm_response(l2cap_channel_t * channel, uint8_t * config_options){
493     int pos = 0;
494     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
495     config_options[pos++] = 9;      // length
496     config_options[pos++] = (uint8_t) channel->mode;
497     // less or equal to remote tx window size
498     config_options[pos++] = btstack_min(channel->num_tx_buffers, channel->remote_tx_window_size);
499     // max transmit in response shall be ignored -> use sender values
500     config_options[pos++] = channel->remote_max_transmit;
501     // A value for the Retransmission time-out shall be sent in a positive Configuration Response
502     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
503     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
504     pos += 2;
505     // A value for the Monitor time-out shall be sent in a positive Configuration Response
506     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
507     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
508     pos += 2;
509     // less or equal to remote mps
510     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
511     little_endian_store_16( config_options, pos, effective_mps);
512     pos += 2;
513     //
514     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
515     config_options[pos++] = 2;     // length
516     little_endian_store_16(config_options, pos, channel->remote_mtu);
517     pos += 2;
518 #if 0
519     //
520     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
521     config_options[pos++] = 1;     // length
522     config_options[pos++] = channel->fcs_option;
523 #endif
524     return pos; // 11+4=15
525 }
526 
527 static int l2cap_ertm_send_supervisor_frame(l2cap_channel_t * channel, uint16_t control){
528     hci_reserve_packet_buffer();
529     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
530     log_info("S-Frame: control 0x%04x", control);
531     little_endian_store_16(acl_buffer, 8, control);
532     return l2cap_send_prepared(channel->local_cid, 2);
533 }
534 
535 static uint8_t l2cap_ertm_validate_local_config(l2cap_ertm_config_t * ertm_config){
536 
537     uint8_t result = ERROR_CODE_SUCCESS;
538     if (ertm_config->max_transmit < 1){
539         log_error("max_transmit must be >= 1");
540         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
541     }
542     if (ertm_config->retransmission_timeout_ms < 2000){
543         log_error("retransmission_timeout_ms must be >= 2000 ms");
544         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
545     }
546     if (ertm_config->monitor_timeout_ms < 12000){
547         log_error("monitor_timeout_ms must be >= 12000 ms");
548         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
549     }
550     if (ertm_config->local_mtu < 48){
551         log_error("local_mtu must be >= 48");
552         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
553     }
554     if (ertm_config->num_rx_buffers < 1){
555         log_error("num_rx_buffers must be >= 1");
556         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
557     }
558     if (ertm_config->num_tx_buffers < 1){
559         log_error("num_rx_buffers must be >= 1");
560         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
561     }
562     return result;
563 }
564 
565 static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
566 
567     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
568     channel->ertm_mandatory = ertm_config->ertm_mandatory;
569     channel->local_max_transmit = ertm_config->max_transmit;
570     channel->local_retransmission_timeout_ms = ertm_config->retransmission_timeout_ms;
571     channel->local_monitor_timeout_ms = ertm_config->monitor_timeout_ms;
572     channel->local_mtu = ertm_config->local_mtu;
573     channel->num_rx_buffers = ertm_config->num_rx_buffers;
574     channel->num_tx_buffers = ertm_config->num_tx_buffers;
575 
576     // align buffer to 16-byte boundary to assert l2cap_ertm_rx_packet_state_t is aligned
577     int bytes_till_alignment = 16 - (((uintptr_t) buffer) & 0x0f);
578     buffer += bytes_till_alignment;
579     size   -= bytes_till_alignment;
580 
581     // setup state buffers - use void cast to avoid -Wcast-align warning
582     uint32_t pos = 0;
583     channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) (void *) &buffer[pos];
584     pos += ertm_config->num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
585     channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) (void *) &buffer[pos];
586     pos += ertm_config->num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
587 
588     // setup reassembly buffer
589     channel->reassembly_buffer = &buffer[pos];
590     pos += ertm_config->local_mtu;
591 
592     // divide rest of data equally
593     channel->local_mps = (size - pos) / (ertm_config->num_rx_buffers + ertm_config->num_tx_buffers);
594     log_info("Local MPS: %u", channel->local_mps);
595     channel->rx_packets_data = &buffer[pos];
596     pos += ertm_config->num_rx_buffers * channel->local_mps;
597     channel->tx_packets_data = &buffer[pos];
598 
599     channel->fcs_option = ertm_config->fcs_option;
600 }
601 
602 uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
603     l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
604 
605     log_info("L2CAP_CREATE_ERTM_CHANNEL addr %s, psm 0x%x, local mtu %u", bd_addr_to_str(address), psm, ertm_config->local_mtu);
606 
607     // validate local config
608     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
609     if (result) return result;
610 
611     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, address, BD_ADDR_TYPE_ACL, psm, ertm_config->local_mtu, LEVEL_0);
612     if (!channel) {
613         return BTSTACK_MEMORY_ALLOC_FAILED;
614     }
615 
616     // configure ERTM
617     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
618 
619     // add to connections list
620     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
621 
622     // store local_cid
623     if (out_local_cid){
624        *out_local_cid = channel->local_cid;
625     }
626 
627     // check if hci connection is already usable
628     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
629     if (conn){
630         log_info("l2cap_create_channel, hci connection already exists");
631         l2cap_handle_connection_complete(conn->con_handle, channel);
632         // check if remote supported fearures are already received
633         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
634             l2cap_handle_remote_supported_features_received(channel);
635         }
636     }
637 
638     l2cap_run();
639 
640     return 0;
641 }
642 
643 static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel){
644     if (l2cap_ertm_can_store_packet_now(channel)){
645         channel->waiting_for_can_send_now = 0;
646         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
647     }
648 }
649 
650 uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
651 
652     log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
653     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
654     if (!channel) {
655         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
656         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
657     }
658 
659     // validate local config
660     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
661     if (result) return result;
662 
663     // configure L2CAP ERTM
664     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
665 
666     // default: continue
667     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
668 
669     // verify remote ERTM support
670     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
671     if (connection == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
672 
673     if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
674         // ERTM not possible, select basic mode and release buffer
675         channel->mode = L2CAP_CHANNEL_MODE_BASIC;
676         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
677 
678         // bail if ERTM is mandatory
679         if (channel->ertm_mandatory){
680             // We chose 'no resources available' for "ERTM mandatory but you don't even know ERTM exists"
681             log_info("ERTM mandatory -> reject connection");
682             channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
683             channel->reason = 0x04; // no resources available
684         }  else {
685             log_info("ERTM not supported by remote -> use Basic mode");
686         }
687     }
688 
689     // process
690     l2cap_run();
691 
692     return ERROR_CODE_SUCCESS;
693 }
694 
695 uint8_t l2cap_ertm_set_busy(uint16_t local_cid){
696     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
697     if (!channel) {
698         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
699         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
700     }
701     if (!channel->local_busy){
702         channel->local_busy = 1;
703         channel->send_supervisor_frame_receiver_not_ready = 1;
704         l2cap_run();
705     }
706     return ERROR_CODE_SUCCESS;
707 }
708 
709 uint8_t l2cap_ertm_set_ready(uint16_t local_cid){
710     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
711     if (!channel) {
712         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
713         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
714     }
715     if (channel->local_busy){
716         channel->local_busy = 0;
717         channel->send_supervisor_frame_receiver_ready_poll = 1;
718         l2cap_run();
719     }
720     return ERROR_CODE_SUCCESS;
721 }
722 
723 // Process-ReqSeq
724 static void l2cap_ertm_process_req_seq(l2cap_channel_t * l2cap_channel, uint8_t req_seq){
725     int num_buffers_acked = 0;
726     l2cap_ertm_tx_packet_state_t * tx_state;
727     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);
728     while (true){
729 
730         // no unack packets left
731         if (l2cap_channel->unacked_frames == 0) {
732             // stop retransmission timer
733             l2cap_ertm_stop_retransmission_timer(l2cap_channel);
734             break;
735         }
736 
737         tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
738         // calc delta
739         int delta = (req_seq - tx_state->tx_seq) & 0x03f;
740         if (delta == 0) break;  // all packets acknowledged
741         if (delta > l2cap_channel->remote_tx_window_size) break;
742 
743         num_buffers_acked++;
744         l2cap_channel->num_stored_tx_frames--;
745         l2cap_channel->unacked_frames--;
746         log_info("RR seq %u => packet with tx_seq %u done", req_seq, tx_state->tx_seq);
747 
748         l2cap_channel->tx_read_index++;
749         if (l2cap_channel->tx_read_index >= l2cap_channel->num_rx_buffers){
750             l2cap_channel->tx_read_index = 0;
751         }
752     }
753     if (num_buffers_acked){
754         log_info("num_buffers_acked %u", num_buffers_acked);
755     l2cap_ertm_notify_channel_can_send(l2cap_channel);
756 }
757 }
758 
759 static l2cap_ertm_tx_packet_state_t * l2cap_ertm_get_tx_state(l2cap_channel_t * l2cap_channel, uint8_t tx_seq){
760     int i;
761     for (i=0;i<l2cap_channel->num_tx_buffers;i++){
762         l2cap_ertm_tx_packet_state_t * tx_state = &l2cap_channel->tx_packets_state[i];
763         if (tx_state->tx_seq == tx_seq) return tx_state;
764     }
765     return NULL;
766 }
767 
768 // @param delta number of frames in the future, >= 1
769 // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
770 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){
771     log_info("Store SDU with delta %u", delta);
772     // get rx state for packet to store
773     int index = l2cap_channel->rx_store_index + delta - 1;
774     if (index > l2cap_channel->num_rx_buffers){
775         index -= l2cap_channel->num_rx_buffers;
776     }
777     log_info("Index of packet to store %u", index);
778     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
779     // check if buffer is free
780     if (rx_state->valid){
781         log_error("Packet buffer already used");
782         return;
783     }
784     rx_state->valid = 1;
785     rx_state->sar = sar;
786     rx_state->len = size;
787     uint8_t * rx_buffer = &l2cap_channel->rx_packets_data[index];
788     (void)memcpy(rx_buffer, payload, size);
789 }
790 
791 // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
792 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){
793     uint16_t reassembly_sdu_length;
794     switch (sar){
795         case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
796             // assert total packet size <= our mtu
797             if (size > l2cap_channel->local_mtu) break;
798             // packet complete -> disapatch
799             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, (uint8_t*) payload, size);
800             break;
801         case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
802             // read SDU len
803             reassembly_sdu_length = little_endian_read_16(payload, 0);
804             payload += 2;
805             size    -= 2;
806             // assert reassembled size <= our mtu
807             if (reassembly_sdu_length > l2cap_channel->local_mtu) break;
808             // store start segment
809             l2cap_channel->reassembly_sdu_length = reassembly_sdu_length;
810             (void)memcpy(&l2cap_channel->reassembly_buffer[0], payload, size);
811             l2cap_channel->reassembly_pos = size;
812             break;
813         case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
814             // assert size of reassembled data <= our mtu
815             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
816             // store continuation segment
817             (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
818                          payload, size);
819             l2cap_channel->reassembly_pos += size;
820             break;
821         case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
822             // assert size of reassembled data <= our mtu
823             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
824             // store continuation segment
825             (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
826                          payload, size);
827             l2cap_channel->reassembly_pos += size;
828             // assert size of reassembled data matches announced sdu length
829             if (l2cap_channel->reassembly_pos != l2cap_channel->reassembly_sdu_length) break;
830             // packet complete -> disapatch
831             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->reassembly_buffer, l2cap_channel->reassembly_pos);
832             l2cap_channel->reassembly_pos = 0;
833             break;
834     }
835 }
836 
837 static void l2cap_ertm_channel_send_information_frame(l2cap_channel_t * channel){
838     channel->unacked_frames++;
839     int index = channel->tx_send_index;
840     channel->tx_send_index++;
841     if (channel->tx_send_index >= channel->num_tx_buffers){
842         channel->tx_send_index = 0;
843     }
844     l2cap_ertm_send_information_frame(channel, index, 0);   // final = 0
845 }
846 
847 #endif
848 
849 #ifdef L2CAP_USES_CHANNELS
850 static uint16_t l2cap_next_local_cid(void){
851     do {
852         if (local_source_cid == 0xffff) {
853             local_source_cid = 0x40;
854         } else {
855             local_source_cid++;
856         }
857     } while (l2cap_get_channel_for_local_cid(local_source_cid) != NULL);
858     return local_source_cid;
859 }
860 #endif
861 
862 static uint8_t l2cap_next_sig_id(void){
863     if (sig_seq_nr == 0xff) {
864         sig_seq_nr = 1;
865     } else {
866         sig_seq_nr++;
867     }
868     return sig_seq_nr;
869 }
870 
871 void l2cap_init(void){
872     signaling_responses_pending = 0;
873 
874     l2cap_channels = NULL;
875 
876 #ifdef ENABLE_CLASSIC
877     l2cap_services = NULL;
878     require_security_level2_for_outgoing_sdp = 0;
879 
880     // Setup Connectionless Channel
881     l2cap_fixed_channel_connectionless.local_cid     = L2CAP_CID_CONNECTIONLESS_CHANNEL;
882     l2cap_fixed_channel_connectionless.channel_type  = L2CAP_CHANNEL_TYPE_CONNECTIONLESS;
883     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_connectionless);
884 #endif
885 
886 #ifdef ENABLE_LE_DATA_CHANNELS
887     l2cap_le_services = NULL;
888 #endif
889 
890 #ifdef ENABLE_BLE
891     l2cap_event_packet_handler = NULL;
892     l2cap_le_custom_max_mtu = 0;
893 
894     // Setup fixed ATT Channel
895     l2cap_fixed_channel_att.local_cid    = L2CAP_CID_ATTRIBUTE_PROTOCOL;
896     l2cap_fixed_channel_att.channel_type = L2CAP_CHANNEL_TYPE_LE_FIXED;
897     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_att);
898 
899     // Setup fixed SM Channel
900     l2cap_fixed_channel_sm.local_cid     = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
901     l2cap_fixed_channel_sm.channel_type  = L2CAP_CHANNEL_TYPE_LE_FIXED;
902     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_sm);
903 #endif
904 
905     //
906     // register callback with HCI
907     //
908     hci_event_callback_registration.callback = &l2cap_hci_event_handler;
909     hci_add_event_handler(&hci_event_callback_registration);
910 
911     hci_register_acl_packet_handler(&l2cap_acl_handler);
912 
913 #ifdef ENABLE_CLASSIC
914     gap_connectable_control(0); // no services yet
915 #endif
916 }
917 
918 void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
919 #ifdef ENABLE_BLE
920     l2cap_event_packet_handler = handler;
921 #else
922     UNUSED(handler);    // ok: no code
923 #endif
924 }
925 
926 void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
927     UNUSED(con_handle);  // ok: there is no con handle
928 
929     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
930     if (!channel) return;
931     channel->waiting_for_can_send_now = 1;
932     l2cap_notify_channel_can_send();
933 }
934 
935 int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
936     UNUSED(channel_id); // ok: only depends on Controller LE buffers
937 
938     return hci_can_send_acl_packet_now(con_handle);
939 }
940 
941 uint8_t *l2cap_get_outgoing_buffer(void){
942     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
943 }
944 
945 // only for L2CAP Basic Channels
946 int l2cap_reserve_packet_buffer(void){
947     return hci_reserve_packet_buffer();
948 }
949 
950 // only for L2CAP Basic Channels
951 void l2cap_release_packet_buffer(void){
952     hci_release_packet_buffer();
953 }
954 
955 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){
956     // 0 - Connection handle : PB=pb : BC=00
957     little_endian_store_16(acl_buffer, 0, con_handle | (packet_boundary << 12) | (0 << 14));
958     // 2 - ACL length
959     little_endian_store_16(acl_buffer, 2,  len + 4);
960     // 4 - L2CAP packet length
961     little_endian_store_16(acl_buffer, 4,  len + 0);
962     // 6 - L2CAP channel DEST
963     little_endian_store_16(acl_buffer, 6,  remote_cid);
964 }
965 
966 // assumption - only on LE connections
967 int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
968 
969     if (!hci_is_packet_buffer_reserved()){
970         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
971         return BTSTACK_ACL_BUFFERS_FULL;
972     }
973 
974     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
975         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
976         return BTSTACK_ACL_BUFFERS_FULL;
977     }
978 
979     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
980 
981     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
982     l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
983     // send
984     return hci_send_acl_packet_buffer(len+8);
985 }
986 
987 // assumption - only on LE connections
988 int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
989 
990     if (!hci_can_send_acl_packet_now(con_handle)){
991         log_info("l2cap_send cid 0x%02x, cannot send", cid);
992         return BTSTACK_ACL_BUFFERS_FULL;
993     }
994 
995     hci_reserve_packet_buffer();
996     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
997 
998     (void)memcpy(&acl_buffer[8], data, len);
999 
1000     return l2cap_send_prepared_connectionless(con_handle, cid, len);
1001 }
1002 
1003 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
1004     log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
1005     uint8_t event[4];
1006     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
1007     event[1] = sizeof(event) - 2;
1008     little_endian_store_16(event, 2, channel);
1009     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1010     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
1011 }
1012 
1013 #ifdef L2CAP_USES_CHANNELS
1014 static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
1015     (* (channel->packet_handler))(type, channel->local_cid, data, size);
1016 }
1017 
1018 static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
1019     uint8_t event[4];
1020     event[0] = event_code;
1021     event[1] = sizeof(event) - 2;
1022     little_endian_store_16(event, 2, channel->local_cid);
1023     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1024     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1025 }
1026 #endif
1027 
1028 #ifdef ENABLE_CLASSIC
1029 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
1030     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",
1031              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
1032              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
1033     uint8_t event[26];
1034     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
1035     event[1] = sizeof(event) - 2;
1036     event[2] = status;
1037     reverse_bd_addr(channel->address, &event[3]);
1038     little_endian_store_16(event,  9, channel->con_handle);
1039     little_endian_store_16(event, 11, channel->psm);
1040     little_endian_store_16(event, 13, channel->local_cid);
1041     little_endian_store_16(event, 15, channel->remote_cid);
1042     little_endian_store_16(event, 17, channel->local_mtu);
1043     little_endian_store_16(event, 19, channel->remote_mtu);
1044     little_endian_store_16(event, 21, channel->flush_timeout);
1045     event[23] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
1046 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1047     log_info("ERTM mode %u, fcs enabled %u", channel->mode, channel->fcs_option);
1048     event[24] = channel->mode;
1049     event[25] = channel->fcs_option;
1050 
1051 #else
1052     event[24] = L2CAP_CHANNEL_MODE_BASIC;
1053     event[25] = 0;
1054 #endif
1055     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1056     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1057 }
1058 
1059 static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
1060     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
1061     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
1062 }
1063 
1064 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
1065     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
1066              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
1067     uint8_t event[16];
1068     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
1069     event[1] = sizeof(event) - 2;
1070     reverse_bd_addr(channel->address, &event[2]);
1071     little_endian_store_16(event,  8, channel->con_handle);
1072     little_endian_store_16(event, 10, channel->psm);
1073     little_endian_store_16(event, 12, channel->local_cid);
1074     little_endian_store_16(event, 14, channel->remote_cid);
1075     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1076     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1077 }
1078 
1079 static void l2cap_handle_channel_open_failed(l2cap_channel_t * channel, uint8_t status){
1080 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1081     // emit ertm buffer released, as it's not needed. if in basic mode, it was either not allocated or already released
1082     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1083         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1084     }
1085 #endif
1086     l2cap_emit_channel_opened(channel, status);
1087 }
1088 
1089 static void l2cap_handle_channel_closed(l2cap_channel_t * channel){
1090 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1091     // emit ertm buffer released, as it's not needed anymore. if in basic mode, it was either not allocated or already released
1092     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1093         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1094     }
1095 #endif
1096     l2cap_emit_channel_closed(channel);
1097 }
1098 #endif
1099 
1100 static l2cap_fixed_channel_t * l2cap_channel_item_by_cid(uint16_t cid){
1101     btstack_linked_list_iterator_t it;
1102     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1103     while (btstack_linked_list_iterator_has_next(&it)){
1104         l2cap_fixed_channel_t * channel = (l2cap_fixed_channel_t*) btstack_linked_list_iterator_next(&it);
1105         if (channel->local_cid == cid) {
1106             return channel;
1107         }
1108     }
1109     return NULL;
1110 }
1111 
1112 // used for fixed channels in LE (ATT/SM) and Classic (Connectionless Channel). CID < 0x04
1113 static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid){
1114     if (local_cid >= 0x40) return NULL;
1115     return (l2cap_fixed_channel_t*) l2cap_channel_item_by_cid(local_cid);
1116 }
1117 
1118 // used for Classic Channels + LE Data Channels. local_cid >= 0x40
1119 #ifdef L2CAP_USES_CHANNELS
1120 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
1121     if (local_cid < 0x40) return NULL;
1122     return (l2cap_channel_t*) l2cap_channel_item_by_cid(local_cid);
1123 }
1124 
1125 void l2cap_request_can_send_now_event(uint16_t local_cid){
1126     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1127     if (!channel) return;
1128     channel->waiting_for_can_send_now = 1;
1129 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1130     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1131         l2cap_ertm_notify_channel_can_send(channel);
1132         return;
1133     }
1134 #endif
1135     l2cap_notify_channel_can_send();
1136 }
1137 
1138 int  l2cap_can_send_packet_now(uint16_t local_cid){
1139     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1140     if (!channel) return 0;
1141 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1142     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1143         return l2cap_ertm_can_store_packet_now(channel);
1144     }
1145 #endif
1146     return hci_can_send_acl_packet_now(channel->con_handle);
1147 }
1148 
1149 int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
1150     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1151     if (!channel) return 0;
1152 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1153     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1154         return 0;
1155     }
1156 #endif
1157     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
1158 }
1159 
1160 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
1161     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1162     if (channel) {
1163         return channel->remote_mtu;
1164     }
1165     return 0;
1166 }
1167 #endif
1168 
1169 #ifdef L2CAP_USES_CHANNELS
1170 static int l2cap_is_dynamic_channel_type(l2cap_channel_type_t channel_type){
1171     switch (channel_type){
1172         case L2CAP_CHANNEL_TYPE_CLASSIC:
1173         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
1174             return 1;
1175         default:
1176             return 0;
1177     }
1178 }
1179 #endif
1180 
1181 #ifdef ENABLE_CLASSIC
1182 // RTX Timer only exist for dynamic channels
1183 static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
1184     btstack_linked_list_iterator_t it;
1185     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1186     while (btstack_linked_list_iterator_has_next(&it)){
1187         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1188         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
1189         if (&channel->rtx == ts) {
1190             return channel;
1191         }
1192     }
1193     return NULL;
1194 }
1195 
1196 static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
1197     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
1198     if (!channel) return;
1199 
1200     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
1201 
1202     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
1203     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
1204     // notify client
1205     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
1206 
1207     // discard channel
1208     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1209     l2cap_free_channel_entry(channel);
1210 }
1211 
1212 #endif
1213 
1214 #ifdef L2CAP_USES_CHANNELS
1215 static void l2cap_stop_rtx(l2cap_channel_t * channel){
1216     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
1217     btstack_run_loop_remove_timer(&channel->rtx);
1218 }
1219 #endif
1220 
1221 #ifdef ENABLE_CLASSIC
1222 
1223 static void l2cap_start_rtx(l2cap_channel_t * channel){
1224     l2cap_stop_rtx(channel);
1225     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
1226     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1227     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
1228     btstack_run_loop_add_timer(&channel->rtx);
1229 }
1230 
1231 static void l2cap_start_ertx(l2cap_channel_t * channel){
1232     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
1233     l2cap_stop_rtx(channel);
1234     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1235     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
1236     btstack_run_loop_add_timer(&channel->rtx);
1237 }
1238 
1239 void l2cap_require_security_level_2_for_outgoing_sdp(void){
1240     require_security_level2_for_outgoing_sdp = 1;
1241 }
1242 
1243 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
1244     return (psm == BLUETOOTH_PSM_SDP) && (!require_security_level2_for_outgoing_sdp);
1245 }
1246 
1247 static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1248     if (!hci_can_send_acl_packet_now(handle)){
1249         log_info("l2cap_send_signaling_packet, cannot send");
1250         return BTSTACK_ACL_BUFFERS_FULL;
1251     }
1252 
1253     // log_info("l2cap_send_signaling_packet type %u", cmd);
1254     hci_reserve_packet_buffer();
1255     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1256     va_list argptr;
1257     va_start(argptr, identifier);
1258     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
1259     va_end(argptr);
1260     // log_info("l2cap_send_signaling_packet con %u!", handle);
1261     return hci_send_acl_packet_buffer(len);
1262 }
1263 
1264 // assumption - only on Classic connections
1265 // cannot be used for L2CAP ERTM
1266 int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
1267 
1268     if (!hci_is_packet_buffer_reserved()){
1269         log_error("l2cap_send_prepared called without reserving packet first");
1270         return BTSTACK_ACL_BUFFERS_FULL;
1271     }
1272 
1273     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1274     if (!channel) {
1275         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
1276         return -1;   // TODO: define error
1277     }
1278 
1279     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
1280         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
1281         return BTSTACK_ACL_BUFFERS_FULL;
1282     }
1283 
1284     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
1285 
1286     int fcs_size = 0;
1287 
1288 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1289     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->fcs_option){
1290         fcs_size = 2;
1291     }
1292 #endif
1293 
1294     // set non-flushable packet boundary flag if supported on Controller
1295     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1296     uint8_t packet_boundary_flag = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
1297     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
1298 
1299 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1300     if (fcs_size){
1301         // calculate FCS over l2cap data
1302         uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
1303         log_info("I-Frame: fcs 0x%04x", fcs);
1304         little_endian_store_16(acl_buffer, 8 + len, fcs);
1305     }
1306 #endif
1307 
1308     // send
1309     return hci_send_acl_packet_buffer(len+8+fcs_size);
1310 }
1311 
1312 // assumption - only on Classic connections
1313 int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
1314     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1315     if (!channel) {
1316         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
1317         return -1;   // TODO: define error
1318     }
1319 
1320 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1321     // send in ERTM
1322     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1323         return l2cap_ertm_send(channel, data, len);
1324     }
1325 #endif
1326 
1327     if (len > channel->remote_mtu){
1328         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
1329         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
1330     }
1331 
1332     if (!hci_can_send_acl_packet_now(channel->con_handle)){
1333         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
1334         return BTSTACK_ACL_BUFFERS_FULL;
1335     }
1336 
1337     hci_reserve_packet_buffer();
1338     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1339     (void)memcpy(&acl_buffer[8], data, len);
1340     return l2cap_send_prepared(local_cid, len);
1341 }
1342 
1343 int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
1344     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
1345 }
1346 
1347 static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
1348     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
1349 }
1350 
1351 static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
1352     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
1353 }
1354 #endif
1355 
1356 
1357 #ifdef ENABLE_BLE
1358 static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1359 
1360     if (!hci_can_send_acl_packet_now(handle)){
1361         log_info("l2cap_send_le_signaling_packet, cannot send");
1362         return BTSTACK_ACL_BUFFERS_FULL;
1363     }
1364 
1365     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
1366     hci_reserve_packet_buffer();
1367     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1368     va_list argptr;
1369     va_start(argptr, identifier);
1370     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
1371     va_end(argptr);
1372     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
1373     return hci_send_acl_packet_buffer(len);
1374 }
1375 #endif
1376 
1377 uint16_t l2cap_max_mtu(void){
1378     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
1379 }
1380 
1381 #ifdef ENABLE_BLE
1382 uint16_t l2cap_max_le_mtu(void){
1383     if (l2cap_le_custom_max_mtu != 0) return l2cap_le_custom_max_mtu;
1384     return l2cap_max_mtu();
1385 }
1386 
1387 void l2cap_set_max_le_mtu(uint16_t max_mtu){
1388     if (max_mtu < l2cap_max_mtu()){
1389         l2cap_le_custom_max_mtu = max_mtu;
1390     }
1391 }
1392 #endif
1393 
1394 #ifdef ENABLE_CLASSIC
1395 
1396 static uint16_t l2cap_setup_options_mtu(uint8_t * config_options, uint16_t mtu){
1397     config_options[0] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
1398     config_options[1] = 2; // len param
1399     little_endian_store_16(config_options, 2, mtu);
1400     return 4;
1401 }
1402 
1403 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1404 static int l2cap_ertm_mode(l2cap_channel_t * channel){
1405     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
1406     return ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE)
1407         &&  (connection->l2cap_state.extended_feature_mask & 0x08));
1408 }
1409 #endif
1410 
1411 static uint16_t l2cap_setup_options_request(l2cap_channel_t * channel, uint8_t * config_options){
1412 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1413     // use ERTM options if supported by remote and channel ready to use it
1414     if (l2cap_ertm_mode(channel) && channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1415         return l2cap_setup_options_ertm_request(channel, config_options);
1416     }
1417 #endif
1418     uint16_t mtu = channel->local_mtu;
1419     return l2cap_setup_options_mtu(config_options, mtu);
1420 }
1421 
1422 static uint16_t l2cap_setup_options_mtu_response(l2cap_channel_t * channel, uint8_t * config_options){
1423     uint16_t mtu = btstack_min(channel->local_mtu, channel->remote_mtu);
1424     return l2cap_setup_options_mtu(config_options, mtu);
1425 }
1426 
1427 static uint32_t l2cap_extended_features_mask(void){
1428     // extended features request supported, features: fixed channels, unicast connectionless data reception
1429     uint32_t features = 0x280;
1430 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1431     features |= 0x0028;
1432 #endif
1433     return features;
1434 }
1435 #endif
1436 
1437 //
1438 #ifdef ENABLE_CLASSIC
1439 static void l2cap_run_for_classic_channel(l2cap_channel_t * channel){
1440 
1441 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1442     uint8_t  config_options[18];
1443 #else
1444     uint8_t  config_options[10];
1445 #endif
1446 
1447     switch (channel->state){
1448 
1449         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1450         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
1451             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1452             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
1453                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
1454                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
1455             }
1456             break;
1457 
1458         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1459             if (!hci_can_send_command_packet_now()) break;
1460             // send connection request - set state first
1461             channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
1462             // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
1463             (void)memcpy(l2cap_outgoing_classic_addr, channel->address, 6);
1464             hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
1465             break;
1466 
1467         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
1468             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1469             channel->state = L2CAP_STATE_INVALID;
1470             l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
1471             // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1472             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1473             l2cap_free_channel_entry(channel);
1474             channel = NULL;
1475             break;
1476 
1477         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
1478             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1479             channel->state = L2CAP_STATE_CONFIG;
1480             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1481             l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
1482             break;
1483 
1484         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
1485             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1486             // success, start l2cap handshake
1487             channel->local_sig_id = l2cap_next_sig_id();
1488             channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
1489             l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
1490             l2cap_start_rtx(channel);
1491             break;
1492 
1493         case L2CAP_STATE_CONFIG:
1494             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1495 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1496             // fallback to basic mode if ERTM requested but not not supported by remote
1497             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1498                 if (!l2cap_ertm_mode(channel)){
1499                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1500                     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
1501                 }
1502             }
1503 #endif
1504             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
1505                 uint16_t flags = 0;
1506                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1507                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
1508                     flags = 1;
1509                 } else {
1510                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1511                 }
1512                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
1513                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1514                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS, 0, NULL);
1515 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1516                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
1517                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1518                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1519                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1520                     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);
1521                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM){
1522                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
1523                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1524                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1525                     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);
1526 #endif
1527                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
1528                     channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1529                     uint16_t options_size = l2cap_setup_options_mtu_response(channel, config_options);
1530                     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);
1531                 } else {
1532                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
1533                 }
1534                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1535             }
1536             else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
1537                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1538                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
1539                 channel->local_sig_id = l2cap_next_sig_id();
1540                 uint16_t options_size = l2cap_setup_options_request(channel, config_options);
1541                 l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options);
1542                 l2cap_start_rtx(channel);
1543             }
1544             if (l2cap_channel_ready_for_open(channel)){
1545                 channel->state = L2CAP_STATE_OPEN;
1546                 l2cap_emit_channel_opened(channel, 0);  // success
1547             }
1548             break;
1549 
1550         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1551             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1552             channel->state = L2CAP_STATE_INVALID;
1553             l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1554             // 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 :)
1555             l2cap_finialize_channel_close(channel);  // -- remove from list
1556             channel = NULL;
1557             break;
1558 
1559         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1560             if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1561             channel->local_sig_id = l2cap_next_sig_id();
1562             channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1563             l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1564             break;
1565         default:
1566             break;
1567     }
1568 
1569 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1570 
1571     // handle channel finalize on L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE and L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE
1572     if (!channel) return;
1573 
1574     // ERTM mode
1575     if (channel->mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) return;
1576 
1577     // check if we can still send
1578     if (channel->con_handle == HCI_CON_HANDLE_INVALID) return;
1579     if (!hci_can_send_acl_packet_now(channel->con_handle)) return;
1580 
1581     if (channel->send_supervisor_frame_receiver_ready){
1582         channel->send_supervisor_frame_receiver_ready = 0;
1583         log_info("Send S-Frame: RR %u, final %u", channel->req_seq, channel->set_final_bit_after_packet_with_poll_bit_set);
1584         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);
1585         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1586         l2cap_ertm_send_supervisor_frame(channel, control);
1587         return;
1588     }
1589     if (channel->send_supervisor_frame_receiver_ready_poll){
1590         channel->send_supervisor_frame_receiver_ready_poll = 0;
1591         log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
1592         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
1593         l2cap_ertm_send_supervisor_frame(channel, control);
1594         return;
1595     }
1596     if (channel->send_supervisor_frame_receiver_not_ready){
1597         channel->send_supervisor_frame_receiver_not_ready = 0;
1598         log_info("Send S-Frame: RNR %u", channel->req_seq);
1599         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
1600         l2cap_ertm_send_supervisor_frame(channel, control);
1601         return;
1602     }
1603     if (channel->send_supervisor_frame_reject){
1604         channel->send_supervisor_frame_reject = 0;
1605         log_info("Send S-Frame: REJ %u", channel->req_seq);
1606         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 0, 0, channel->req_seq);
1607         l2cap_ertm_send_supervisor_frame(channel, control);
1608         return;
1609     }
1610     if (channel->send_supervisor_frame_selective_reject){
1611         channel->send_supervisor_frame_selective_reject = 0;
1612         log_info("Send S-Frame: SREJ %u", channel->expected_tx_seq);
1613         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);
1614         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1615         l2cap_ertm_send_supervisor_frame(channel, control);
1616         return;
1617     }
1618 
1619     if (channel->srej_active){
1620         int i;
1621         for (i=0;i<channel->num_tx_buffers;i++){
1622             l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
1623             if (tx_state->retransmission_requested) {
1624                 tx_state->retransmission_requested = 0;
1625                 uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set;
1626                 channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1627                 l2cap_ertm_send_information_frame(channel, i, final);
1628                 break;
1629             }
1630         }
1631         if (i == channel->num_tx_buffers){
1632             // no retransmission request found
1633             channel->srej_active = 0;
1634         } else {
1635             // packet was sent
1636             return;
1637         }
1638     }
1639 #endif
1640 }
1641 #endif
1642 
1643 // MARK: L2CAP_RUN
1644 // process outstanding signaling tasks
1645 static void l2cap_run(void){
1646 
1647     // log_info("l2cap_run: entered");
1648 
1649     // check pending signaling responses
1650     while (signaling_responses_pending){
1651 
1652         hci_con_handle_t handle = signaling_responses[0].handle;
1653 
1654         if (!hci_can_send_acl_packet_now(handle)) break;
1655 
1656         uint8_t  sig_id        = signaling_responses[0].sig_id;
1657         uint8_t  response_code = signaling_responses[0].code;
1658         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
1659 #ifdef ENABLE_CLASSIC
1660         uint16_t info_type     = signaling_responses[0].data;  // INFORMATION_REQUEST
1661         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
1662 #endif
1663 
1664         // remove first item before sending (to avoid sending response mutliple times)
1665         signaling_responses_pending--;
1666         int i;
1667         for (i=0; i < signaling_responses_pending; i++){
1668             (void)memcpy(&signaling_responses[i],
1669                          &signaling_responses[i + 1],
1670                          sizeof(l2cap_signaling_response_t));
1671         }
1672 
1673         switch (response_code){
1674 #ifdef ENABLE_CLASSIC
1675             case CONNECTION_REQUEST:
1676                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
1677                 // also disconnect if result is 0x0003 - security blocked
1678                 if (result == 0x0003){
1679                     hci_disconnect_security_block(handle);
1680                 }
1681                 break;
1682             case ECHO_REQUEST:
1683                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
1684                 break;
1685             case INFORMATION_REQUEST:
1686                 switch (info_type){
1687                     case L2CAP_INFO_TYPE_CONNECTIONLESS_MTU: {
1688                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
1689                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(connectionless_mtu), &connectionless_mtu);
1690                         }
1691                         break;
1692                     case L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED: {
1693                             uint32_t features = l2cap_extended_features_mask();
1694                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(features), &features);
1695                         }
1696                         break;
1697                     case L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED: {
1698                             uint8_t map[8];
1699                             memset(map, 0, 8);
1700                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
1701                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(map), &map);
1702                         }
1703                         break;
1704                     default:
1705                         // all other types are not supported
1706                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 1, 0, NULL);
1707                         break;
1708                 }
1709                 break;
1710             case COMMAND_REJECT:
1711                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
1712                 break;
1713 #endif
1714 #ifdef ENABLE_BLE
1715             case LE_CREDIT_BASED_CONNECTION_REQUEST:
1716                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
1717                 break;
1718             case COMMAND_REJECT_LE:
1719                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
1720                 break;
1721 #endif
1722             default:
1723                 // should not happen
1724                 break;
1725         }
1726     }
1727 
1728 #if defined(ENABLE_CLASSIC) || defined(ENABLE_BLE)
1729     btstack_linked_list_iterator_t it;
1730 #endif
1731 
1732 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1733     // send l2cap information request if neccessary
1734     hci_connections_get_iterator(&it);
1735     while(btstack_linked_list_iterator_has_next(&it)){
1736         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1737         if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST){
1738             if (!hci_can_send_acl_packet_now(connection->con_handle)) break;
1739             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
1740             uint8_t sig_id = l2cap_next_sig_id();
1741             uint8_t info_type = L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED;
1742             l2cap_send_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
1743             return;
1744         }
1745     }
1746 #endif
1747 
1748 #ifdef ENABLE_CLASSIC
1749     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1750     while (btstack_linked_list_iterator_has_next(&it)){
1751 
1752         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1753 
1754         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CLASSIC) continue;
1755 
1756         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1757         l2cap_run_for_classic_channel(channel);
1758     }
1759 #endif
1760 
1761 #ifdef ENABLE_LE_DATA_CHANNELS
1762     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1763     while (btstack_linked_list_iterator_has_next(&it)){
1764         uint16_t mps;
1765         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1766 
1767         if (channel->channel_type != L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL) continue;
1768 
1769         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1770         switch (channel->state){
1771             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
1772                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1773                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
1774                 // le psm, source cid, mtu, mps, initial credits
1775                 channel->local_sig_id = l2cap_next_sig_id();
1776                 channel->credits_incoming =  channel->new_credits_incoming;
1777                 channel->new_credits_incoming = 0;
1778                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
1779                 l2cap_send_le_signaling_packet( channel->con_handle, LE_CREDIT_BASED_CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid, channel->local_mtu, mps, channel->credits_incoming);
1780                 break;
1781             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
1782                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1783                 // TODO: support larger MPS
1784                 channel->state = L2CAP_STATE_OPEN;
1785                 channel->credits_incoming =  channel->new_credits_incoming;
1786                 channel->new_credits_incoming = 0;
1787                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
1788                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->local_mtu, mps, channel->credits_incoming, 0);
1789                 // notify client
1790                 l2cap_emit_le_channel_opened(channel, 0);
1791                 break;
1792             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
1793                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1794                 channel->state = L2CAP_STATE_INVALID;
1795                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
1796                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1797                 btstack_linked_list_iterator_remove(&it);
1798                 l2cap_free_channel_entry(channel);
1799                 break;
1800             case L2CAP_STATE_OPEN:
1801                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1802 
1803                 // send credits
1804                 if (channel->new_credits_incoming){
1805                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
1806                     channel->local_sig_id = l2cap_next_sig_id();
1807                     uint16_t new_credits = channel->new_credits_incoming;
1808                     channel->new_credits_incoming = 0;
1809                     channel->credits_incoming += new_credits;
1810                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
1811                 }
1812                 break;
1813 
1814             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1815                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1816                 channel->local_sig_id = l2cap_next_sig_id();
1817                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1818                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1819                 break;
1820             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1821                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1822                 channel->state = L2CAP_STATE_INVALID;
1823                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1824                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
1825                 break;
1826             default:
1827                 break;
1828         }
1829     }
1830 #endif
1831 
1832 #ifdef ENABLE_BLE
1833     // send l2cap con paramter update if necessary
1834     hci_connections_get_iterator(&it);
1835     while(btstack_linked_list_iterator_has_next(&it)){
1836         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1837         if ((connection->address_type != BD_ADDR_TYPE_LE_PUBLIC) && (connection->address_type != BD_ADDR_TYPE_LE_RANDOM)) continue;
1838         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
1839         switch (connection->le_con_parameter_update_state){
1840             case CON_PARAMETER_UPDATE_SEND_REQUEST:
1841                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1842                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, l2cap_next_sig_id(),
1843                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
1844                 break;
1845             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
1846                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
1847                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
1848                 break;
1849             case CON_PARAMETER_UPDATE_DENY:
1850                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1851                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
1852                 break;
1853             default:
1854                 break;
1855         }
1856     }
1857 #endif
1858 
1859     // log_info("l2cap_run: exit");
1860 }
1861 
1862 #ifdef ENABLE_CLASSIC
1863 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
1864     if ((channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE) || (channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION)) {
1865         log_info("connection complete con_handle %04x - for channel %p cid 0x%04x", (int) con_handle, channel, channel->local_cid);
1866         // success, start l2cap handshake
1867         channel->con_handle = con_handle;
1868         // check remote SSP feature first
1869         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
1870     }
1871 }
1872 
1873 static void l2cap_ready_to_connect(l2cap_channel_t * channel){
1874 
1875 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1876     // assumption: outgoing connection
1877     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
1878     if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
1879         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
1880         channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
1881         return;
1882     }
1883 #endif
1884 
1885     // fine, go ahead
1886     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
1887 }
1888 
1889 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
1890     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
1891 
1892     // we have been waiting for remote supported features, if both support SSP,
1893     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));
1894     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
1895         // request security level 2
1896         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
1897         channel->required_security_level = LEVEL_2;
1898         gap_request_security_level(channel->con_handle, LEVEL_2);
1899         return;
1900     }
1901 
1902     l2cap_ready_to_connect(channel);
1903 }
1904 #endif
1905 
1906 #ifdef L2CAP_USES_CHANNELS
1907 static l2cap_channel_t * l2cap_create_channel_entry(btstack_packet_handler_t packet_handler, l2cap_channel_type_t channel_type, bd_addr_t address, bd_addr_type_t address_type,
1908     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
1909 
1910     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1911     if (!channel) {
1912         return NULL;
1913     }
1914 
1915     // fill in
1916     channel->packet_handler = packet_handler;
1917     channel->channel_type   = channel_type;
1918     bd_addr_copy(channel->address, address);
1919     channel->address_type = address_type;
1920     channel->psm = psm;
1921     channel->local_mtu  = local_mtu;
1922     channel->remote_mtu = L2CAP_DEFAULT_MTU;
1923     channel->required_security_level = security_level;
1924 
1925     //
1926     channel->local_cid = l2cap_next_local_cid();
1927     channel->con_handle = HCI_CON_HANDLE_INVALID;
1928 
1929     // set initial state
1930     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
1931     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
1932     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
1933     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
1934 
1935     log_info("create channel %p, local_cid 0x%04x", channel, channel->local_cid);
1936 
1937     return channel;
1938 }
1939 
1940 static void l2cap_free_channel_entry(l2cap_channel_t * channel){
1941     log_info("free channel %p, local_cid 0x%04x", channel, channel->local_cid);
1942     // assert all timers are stopped
1943     l2cap_stop_rtx(channel);
1944 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1945     l2cap_ertm_stop_retransmission_timer(channel);
1946     l2cap_ertm_stop_monitor_timer(channel);
1947 #endif
1948     // free  memory
1949     btstack_memory_l2cap_channel_free(channel);
1950 }
1951 #endif
1952 
1953 #ifdef ENABLE_CLASSIC
1954 
1955 /**
1956  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
1957  * @param packet_handler
1958  * @param address
1959  * @param psm
1960  * @param mtu
1961  * @param local_cid
1962  */
1963 
1964 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){
1965     // limit MTU to the size of our outtgoing HCI buffer
1966     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1967 
1968     log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x mtu %u -> local mtu %u", bd_addr_to_str(address), psm, mtu, local_mtu);
1969 
1970     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, address, BD_ADDR_TYPE_ACL, psm, local_mtu, LEVEL_0);
1971     if (!channel) {
1972         return BTSTACK_MEMORY_ALLOC_FAILED;
1973     }
1974 
1975 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1976     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
1977 #endif
1978 
1979     // add to connections list
1980     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1981 
1982     // store local_cid
1983     if (out_local_cid){
1984        *out_local_cid = channel->local_cid;
1985     }
1986 
1987     // check if hci connection is already usable
1988     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
1989     if (conn && conn->con_handle != HCI_CON_HANDLE_INVALID){
1990         log_info("l2cap_create_channel, hci connection 0x%04x already exists", conn->con_handle);
1991         l2cap_handle_connection_complete(conn->con_handle, channel);
1992         // check if remote supported fearures are already received
1993         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
1994             l2cap_handle_remote_supported_features_received(channel);
1995         }
1996     }
1997 
1998     l2cap_run();
1999 
2000     return ERROR_CODE_SUCCESS;
2001 }
2002 
2003 void l2cap_disconnect(uint16_t local_cid, uint8_t reason){
2004     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
2005     // find channel for local_cid
2006     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2007     if (channel) {
2008         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2009     }
2010     // process
2011     l2cap_run();
2012 }
2013 
2014 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
2015     // mark all channels before emitting open events as these could trigger new connetion requests to the same device
2016     btstack_linked_list_iterator_t it;
2017     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2018     while (btstack_linked_list_iterator_has_next(&it)){
2019         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2020         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2021         if (bd_addr_cmp( channel->address, address) != 0) continue;
2022         // channel for this address found
2023         switch (channel->state){
2024             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2025             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2026                 channel->state = L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD;
2027                 break;
2028             default:
2029                 break;
2030         }
2031     }
2032     // emit and free marked entries. restart loop to deal with list changes
2033     int done = 0;
2034     while (!done) {
2035         done = 1;
2036         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2037         while (btstack_linked_list_iterator_has_next(&it)){
2038             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2039             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2040             if (channel->state == L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD){
2041                 done = 0;
2042                 // failure, forward error code
2043                 l2cap_handle_channel_open_failed(channel, status);
2044                 // discard channel
2045                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2046                 l2cap_free_channel_entry(channel);
2047                 break;
2048             }
2049         }
2050     }
2051 
2052 }
2053 
2054 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
2055     btstack_linked_list_iterator_t it;
2056     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2057     while (btstack_linked_list_iterator_has_next(&it)){
2058         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2059         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2060         if ( ! bd_addr_cmp( channel->address, address) ){
2061             l2cap_handle_connection_complete(handle, channel);
2062         }
2063     }
2064     // process
2065     l2cap_run();
2066 }
2067 #endif
2068 
2069 static bool l2cap_channel_ready_to_send(l2cap_channel_t * channel){
2070     switch (channel->channel_type){
2071 #ifdef ENABLE_CLASSIC
2072         case L2CAP_CHANNEL_TYPE_CLASSIC:
2073 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2074             // send if we have more data and remote windows isn't full yet
2075             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2076                 if (channel->unacked_frames >= btstack_min(channel->num_stored_tx_frames, channel->remote_tx_window_size)) return false;
2077                 return hci_can_send_acl_classic_packet_now() != 0;
2078             }
2079 #endif
2080             if (!channel->waiting_for_can_send_now) return false;
2081             return (hci_can_send_acl_classic_packet_now() != 0);
2082         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2083             if (!channel->waiting_for_can_send_now) return false;
2084             return hci_can_send_acl_classic_packet_now() != 0;
2085 #endif
2086 #ifdef ENABLE_BLE
2087         case L2CAP_CHANNEL_TYPE_LE_FIXED:
2088             if (!channel->waiting_for_can_send_now) return false;
2089             return hci_can_send_acl_le_packet_now() != 0;
2090 #ifdef ENABLE_LE_DATA_CHANNELS
2091         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
2092             if (channel->send_sdu_buffer == NULL) return false;
2093             if (channel->credits_outgoing == 0) return false;
2094             return hci_can_send_acl_le_packet_now() != 0;
2095 #endif
2096 #endif
2097         default:
2098             return false;
2099     }
2100 }
2101 
2102 static void l2cap_channel_trigger_send(l2cap_channel_t * channel){
2103     switch (channel->channel_type){
2104 #ifdef ENABLE_CLASSIC
2105         case L2CAP_CHANNEL_TYPE_CLASSIC:
2106 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2107             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2108                 l2cap_ertm_channel_send_information_frame(channel);
2109                 return;
2110             }
2111 #endif
2112             channel->waiting_for_can_send_now = 0;
2113             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2114             break;
2115         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2116             channel->waiting_for_can_send_now = 0;
2117             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2118             break;
2119 #endif
2120 #ifdef ENABLE_BLE
2121         case L2CAP_CHANNEL_TYPE_LE_FIXED:
2122             channel->waiting_for_can_send_now = 0;
2123             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2124             break;
2125 #ifdef ENABLE_LE_DATA_CHANNELS
2126         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
2127             l2cap_le_send_pdu(channel);
2128             break;
2129 #endif
2130 #endif
2131         default:
2132             break;
2133     }
2134 }
2135 
2136 static void l2cap_notify_channel_can_send(void){
2137     bool done = false;
2138     while (!done){
2139         done = true;
2140         btstack_linked_list_iterator_t it;
2141         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2142         while (btstack_linked_list_iterator_has_next(&it)){
2143             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2144             bool ready = l2cap_channel_ready_to_send(channel);
2145             if (!ready) continue;
2146 
2147             // requeue channel for fairness
2148             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2149             btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2150 
2151             // trigger sending
2152             l2cap_channel_trigger_send(channel);
2153 
2154             // exit inner loop as we just broke the iterator, but try again
2155             done = false;
2156             break;
2157         }
2158     }
2159 }
2160 
2161 #ifdef L2CAP_USES_CHANNELS
2162 
2163 static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){
2164     // open cannot fail for for incoming connections
2165     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0;
2166 
2167     // check state
2168     switch (channel->state){
2169         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2170         case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2171         case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES:
2172         case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2173         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
2174         case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES:
2175         case L2CAP_STATE_WAIT_CONNECT_RSP:
2176         case L2CAP_STATE_CONFIG:
2177         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
2178         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
2179         case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE:
2180         case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD:
2181             return 1;
2182 
2183         case L2CAP_STATE_OPEN:
2184         case L2CAP_STATE_CLOSED:
2185         case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES:
2186         case L2CAP_STATE_WAIT_DISCONNECT:
2187         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY:
2188         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
2189         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
2190         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2191         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
2192         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
2193         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
2194         case L2CAP_STATE_INVALID:
2195         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2196             return 0;
2197         // no default here, to get a warning about new states
2198     }
2199     // still, the compiler insists on a return value
2200     return 0;
2201 }
2202 #endif
2203 
2204 #ifdef ENABLE_CLASSIC
2205 static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){
2206     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2207         l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2208     } else {
2209         l2cap_handle_channel_closed(channel);
2210     }
2211     l2cap_free_channel_entry(channel);
2212 }
2213 #endif
2214 
2215 #ifdef ENABLE_LE_DATA_CHANNELS
2216 static void l2cap_handle_hci_le_disconnect_event(l2cap_channel_t * channel){
2217     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2218         l2cap_emit_le_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2219     } else {
2220         l2cap_emit_le_channel_closed(channel);
2221     }
2222     l2cap_free_channel_entry(channel);
2223 }
2224 #endif
2225 
2226 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
2227 
2228     UNUSED(packet_type); // ok: registered with hci_event_callback_registration
2229     UNUSED(cid);         // ok: there is no channel
2230     UNUSED(size);        // ok: fixed format events read from HCI buffer
2231 
2232 #ifdef ENABLE_CLASSIC
2233     bd_addr_t address;
2234     int hci_con_used;
2235 #endif
2236 #ifdef L2CAP_USES_CHANNELS
2237     hci_con_handle_t handle;
2238     btstack_linked_list_iterator_t it;
2239 #endif
2240 
2241     switch(hci_event_packet_get_type(packet)){
2242 
2243         // Notify channel packet handler if they can send now
2244         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2245         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
2246         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
2247             l2cap_run();    // try sending signaling packets first
2248             l2cap_notify_channel_can_send();
2249             break;
2250 
2251         case HCI_EVENT_COMMAND_STATUS:
2252 #ifdef ENABLE_CLASSIC
2253             // check command status for create connection for errors
2254             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
2255                 // cache outgoing address and reset
2256                 (void)memcpy(address, l2cap_outgoing_classic_addr, 6);
2257                 memset(l2cap_outgoing_classic_addr, 0, 6);
2258                 // error => outgoing connection failed
2259                 uint8_t status = hci_event_command_status_get_status(packet);
2260                 if (status){
2261                     l2cap_handle_connection_failed_for_addr(address, status);
2262                 }
2263             }
2264 #endif
2265             l2cap_run();    // try sending signaling packets first
2266             break;
2267 
2268 #ifdef ENABLE_CLASSIC
2269         // handle connection complete events
2270         case HCI_EVENT_CONNECTION_COMPLETE:
2271             reverse_bd_addr(&packet[5], address);
2272             if (packet[2] == 0){
2273                 handle = little_endian_read_16(packet, 3);
2274                 l2cap_handle_connection_success_for_addr(address, handle);
2275             } else {
2276                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
2277             }
2278             break;
2279 
2280         // handle successful create connection cancel command
2281         case HCI_EVENT_COMMAND_COMPLETE:
2282             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
2283                 if (packet[5] == 0){
2284                     reverse_bd_addr(&packet[6], address);
2285                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
2286                     l2cap_handle_connection_failed_for_addr(address, 0x16);
2287                 }
2288             }
2289             l2cap_run();    // try sending signaling packets first
2290             break;
2291 #endif
2292 
2293 #ifdef L2CAP_USES_CHANNELS
2294         // handle disconnection complete events
2295         case HCI_EVENT_DISCONNECTION_COMPLETE:
2296             handle = little_endian_read_16(packet, 3);
2297             // send l2cap open failed or closed events for all channels on this handle and free them
2298             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2299             while (btstack_linked_list_iterator_has_next(&it)){
2300                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2301                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2302                 if (channel->con_handle != handle) continue;
2303                 btstack_linked_list_iterator_remove(&it);
2304                 switch(channel->channel_type){
2305 #ifdef ENABLE_CLASSIC
2306                     case L2CAP_CHANNEL_TYPE_CLASSIC:
2307                         l2cap_handle_hci_disconnect_event(channel);
2308                         break;
2309 #endif
2310 #ifdef ENABLE_LE_DATA_CHANNELS
2311                     case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
2312                         l2cap_handle_hci_le_disconnect_event(channel);
2313                         break;
2314 #endif
2315                     default:
2316                         break;
2317                 }
2318             }
2319             break;
2320 #endif
2321 
2322 
2323         // HCI Connection Timeouts
2324 #ifdef ENABLE_CLASSIC
2325         case L2CAP_EVENT_TIMEOUT_CHECK:
2326             handle = little_endian_read_16(packet, 2);
2327             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
2328             if (hci_authentication_active_for_handle(handle)) break;
2329             hci_con_used = 0;
2330             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2331             while (btstack_linked_list_iterator_has_next(&it)){
2332                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2333                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2334                 if (channel->con_handle != handle) continue;
2335                 hci_con_used = 1;
2336                 break;
2337             }
2338             if (hci_con_used) break;
2339             if (!hci_can_send_command_packet_now()) break;
2340             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
2341             break;
2342 
2343         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2344             handle = little_endian_read_16(packet, 3);
2345             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2346             while (btstack_linked_list_iterator_has_next(&it)){
2347                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2348                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2349                 if (channel->con_handle != handle) continue;
2350                 log_info("remote supported features, channel %p, cid %04x - state %u", channel, channel->local_cid, channel->state);
2351                 l2cap_handle_remote_supported_features_received(channel);
2352             }
2353             break;
2354 
2355         case GAP_EVENT_SECURITY_LEVEL:
2356             handle = little_endian_read_16(packet, 2);
2357             log_info("l2cap - security level update for handle 0x%04x", handle);
2358             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2359             while (btstack_linked_list_iterator_has_next(&it)){
2360                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2361                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2362                 if (channel->con_handle != handle) continue;
2363 
2364                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
2365                 gap_security_level_t required_level = channel->required_security_level;
2366 
2367                 log_info("channel %p, cid %04x - state %u: actual %u >= required %u?", channel, channel->local_cid, channel->state, actual_level, required_level);
2368 
2369                 switch (channel->state){
2370                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2371                         if (actual_level >= required_level){
2372 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2373                             // we need to know if ERTM is supported before sending a config response
2374                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
2375                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2376                             channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
2377 #else
2378                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2379                             l2cap_emit_incoming_connection(channel);
2380 #endif
2381                         } else {
2382                             channel->reason = 0x0003; // security block
2383                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2384                         }
2385                         break;
2386 
2387                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2388                         if (actual_level >= required_level){
2389                             l2cap_ready_to_connect(channel);
2390                         } else {
2391                             // disconnnect, authentication not good enough
2392                             hci_disconnect_security_block(handle);
2393                         }
2394                         break;
2395 
2396                     default:
2397                         break;
2398                 }
2399             }
2400             break;
2401 #endif
2402 
2403         default:
2404             break;
2405     }
2406 
2407     l2cap_run();
2408 }
2409 
2410 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t cid, uint16_t data){
2411     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused."
2412     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
2413         signaling_responses[signaling_responses_pending].handle = handle;
2414         signaling_responses[signaling_responses_pending].code = code;
2415         signaling_responses[signaling_responses_pending].sig_id = sig_id;
2416         signaling_responses[signaling_responses_pending].cid = cid;
2417         signaling_responses[signaling_responses_pending].data = data;
2418         signaling_responses_pending++;
2419         l2cap_run();
2420     }
2421 }
2422 
2423 #ifdef ENABLE_CLASSIC
2424 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
2425     channel->remote_sig_id = identifier;
2426     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
2427     l2cap_run();
2428 }
2429 
2430 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
2431 
2432     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
2433     l2cap_service_t *service = l2cap_get_service(psm);
2434     if (!service) {
2435         // 0x0002 PSM not supported
2436         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2437         return;
2438     }
2439 
2440     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
2441     if (!hci_connection) {
2442         //
2443         log_error("no hci_connection for handle %u", handle);
2444         return;
2445     }
2446 
2447     // alloc structure
2448     // log_info("l2cap_handle_connection_request register channel");
2449     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, hci_connection->address, BD_ADDR_TYPE_ACL,
2450     psm, service->mtu, service->required_security_level);
2451     if (!channel){
2452         // 0x0004 No resources available
2453         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2454         return;
2455     }
2456 
2457     channel->con_handle = handle;
2458     channel->remote_cid = source_cid;
2459     channel->remote_sig_id = sig_id;
2460 
2461     // limit local mtu to max acl packet length - l2cap header
2462     if (channel->local_mtu > l2cap_max_mtu()) {
2463         channel->local_mtu = l2cap_max_mtu();
2464     }
2465 
2466     // set initial state
2467     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
2468     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
2469 
2470     // add to connections list
2471     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
2472 
2473     // assert security requirements
2474     gap_request_security_level(handle, channel->required_security_level);
2475 }
2476 
2477 void l2cap_accept_connection(uint16_t local_cid){
2478     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
2479     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2480     if (!channel) {
2481         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
2482         return;
2483     }
2484 
2485 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2486     // configure L2CAP Basic mode
2487     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
2488 #endif
2489 
2490     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
2491 
2492     // process
2493     l2cap_run();
2494 }
2495 
2496 void l2cap_decline_connection(uint16_t local_cid){
2497     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
2498     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
2499     if (!channel) {
2500         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
2501         return;
2502     }
2503     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2504     channel->reason = 0x04; // no resources available
2505     l2cap_run();
2506 }
2507 
2508 // @pre command len is valid, see check in l2cap_signaling_handler_channel
2509 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
2510 
2511 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2512     uint8_t use_fcs = 1;
2513 #endif
2514 
2515     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2516 
2517     uint16_t flags = little_endian_read_16(command, 6);
2518     if (flags & 1) {
2519         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
2520     }
2521 
2522     // accept the other's configuration options
2523     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2524     uint16_t pos     = 8;
2525     while (pos < end_pos){
2526         uint8_t option_hint = command[pos] >> 7;
2527         uint8_t option_type = command[pos] & 0x7f;
2528         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
2529         pos++;
2530         uint8_t length = command[pos++];
2531         // MTU { type(8): 1, len(8):2, MTU(16) }
2532         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) && (length == 2)){
2533             channel->remote_mtu = little_endian_read_16(command, pos);
2534             log_info("Remote MTU %u", channel->remote_mtu);
2535             if (channel->remote_mtu > l2cap_max_mtu()){
2536                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
2537                 channel->remote_mtu = l2cap_max_mtu();
2538             }
2539             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
2540         }
2541         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
2542         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT) && (length == 2)){
2543             channel->flush_timeout = little_endian_read_16(command, pos);
2544             log_info("Flush timeout: %u ms", channel->flush_timeout);
2545         }
2546 
2547 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2548         // Retransmission and Flow Control Option
2549         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2550             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
2551             switch(channel->mode){
2552                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2553                     // Store remote config
2554                     channel->remote_tx_window_size = command[pos+1];
2555                     channel->remote_max_transmit   = command[pos+2];
2556                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
2557                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
2558                     channel->remote_mps = little_endian_read_16(command, pos + 7);
2559                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
2560                         channel->remote_tx_window_size,
2561                         channel->remote_max_transmit,
2562                         channel->remote_retransmission_timeout_ms,
2563                         channel->remote_monitor_timeout_ms,
2564                         channel->remote_mps);
2565                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
2566                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
2567                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2568                     } else {
2569                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2570                     }
2571                     break;
2572                 case L2CAP_CHANNEL_MODE_BASIC:
2573                     switch (mode){
2574                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2575                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
2576                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
2577                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2578                             }
2579                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
2580                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
2581                             break;
2582                         default: // case L2CAP_CHANNEL_MODE_BASIC:
2583                             // TODO store and evaluate configuration
2584                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2585                             break;
2586                     }
2587                     break;
2588                 default:
2589                     break;
2590             }
2591         }
2592         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
2593             use_fcs = command[pos];
2594         }
2595 #endif
2596         // check for unknown options
2597         if ((option_hint == 0) && ((option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) || (option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE))){
2598             log_info("l2cap cid %u, unknown options", channel->local_cid);
2599             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
2600         }
2601         pos += length;
2602     }
2603 
2604 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2605         // "FCS" has precedence over "No FCS"
2606         uint8_t update = channel->fcs_option || use_fcs;
2607         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
2608         channel->fcs_option = update;
2609         // If ERTM mandatory, but remote didn't send Retransmission and Flowcontrol options -> disconnect
2610         if (((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM) == 0) & (channel->ertm_mandatory)){
2611             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2612         }
2613 #endif
2614 }
2615 
2616 // @pre command len is valid, see check in l2cap_signaling_handler_channel
2617 static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
2618     log_info("l2cap_signaling_handle_configure_response");
2619 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2620     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2621     uint16_t pos     = 10;
2622     while (pos < end_pos){
2623         uint8_t option_hint = command[pos] >> 7;
2624         uint8_t option_type = command[pos] & 0x7f;
2625         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
2626         pos++;
2627         uint8_t length = command[pos++];
2628 
2629         // Retransmission and Flow Control Option
2630         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2631             switch (channel->mode){
2632                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2633                     if (channel->ertm_mandatory){
2634                         // ??
2635                     } else {
2636                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
2637                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2638                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
2639                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2640                         }
2641                     }
2642                     break;
2643                 case L2CAP_CHANNEL_MODE_BASIC:
2644                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2645                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
2646                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2647                     }
2648                     break;
2649                 default:
2650                     break;
2651             }
2652         }
2653 
2654         // check for unknown options
2655         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
2656             log_info("l2cap cid %u, unknown options", channel->local_cid);
2657             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
2658         }
2659 
2660         pos += length;
2661     }
2662 #else
2663     UNUSED(channel);  // ok: no code
2664     UNUSED(result);   // ok: no code
2665     UNUSED(command);  // ok: no code
2666 #endif
2667 }
2668 
2669 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
2670     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
2671     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
2672     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
2673     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
2674     if (channel->state == L2CAP_STATE_OPEN) return 0;
2675     return 1;
2676 }
2677 
2678 
2679 // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
2680 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
2681 
2682     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2683     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2684     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2685     uint16_t result = 0;
2686 
2687     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
2688 
2689     // handle DISCONNECT REQUESTS seperately
2690     if (code == DISCONNECTION_REQUEST){
2691         switch (channel->state){
2692             case L2CAP_STATE_CONFIG:
2693             case L2CAP_STATE_OPEN:
2694             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2695             case L2CAP_STATE_WAIT_DISCONNECT:
2696                 l2cap_handle_disconnect_request(channel, identifier);
2697                 break;
2698 
2699             default:
2700                 // ignore in other states
2701                 break;
2702         }
2703         return;
2704     }
2705 
2706     // @STATEMACHINE(l2cap)
2707     switch (channel->state) {
2708 
2709         case L2CAP_STATE_WAIT_CONNECT_RSP:
2710             switch (code){
2711                 case CONNECTION_RESPONSE:
2712                     if (cmd_len < 8){
2713                         // command imcomplete
2714                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2715                         break;
2716                     }
2717                     l2cap_stop_rtx(channel);
2718                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2719                     switch (result) {
2720                         case 0:
2721                             // successful connection
2722                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2723                             channel->state = L2CAP_STATE_CONFIG;
2724                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2725                             break;
2726                         case 1:
2727                             // connection pending. get some coffee, but start the ERTX
2728                             l2cap_start_ertx(channel);
2729                             break;
2730                         default:
2731                             // channel closed
2732                             channel->state = L2CAP_STATE_CLOSED;
2733                             // map l2cap connection response result to BTstack status enumeration
2734                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
2735 
2736                             // drop link key if security block
2737                             if ((L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result) == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
2738                                 gap_drop_link_key_for_bd_addr(channel->address);
2739                             }
2740 
2741                             // discard channel
2742                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2743                             l2cap_free_channel_entry(channel);
2744                             break;
2745                     }
2746                     break;
2747 
2748                 default:
2749                     //@TODO: implement other signaling packets
2750                     break;
2751             }
2752             break;
2753 
2754         case L2CAP_STATE_CONFIG:
2755             switch (code) {
2756                 case CONFIGURE_REQUEST:
2757                     if (cmd_len < 4){
2758                         // command incomplete
2759                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2760                         break;
2761                     }
2762                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
2763                     l2cap_signaling_handle_configure_request(channel, command);
2764                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
2765                         // only done if continuation not set
2766                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
2767                     }
2768                     break;
2769                 case CONFIGURE_RESPONSE:
2770                     if (cmd_len < 6){
2771                         // command incomplete
2772                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2773                         break;
2774                     }
2775                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2776                     l2cap_stop_rtx(channel);
2777                     l2cap_signaling_handle_configure_response(channel, result, command);
2778                     switch (result){
2779                         case 0: // success
2780                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
2781                             break;
2782                         case 4: // pending
2783                             l2cap_start_ertx(channel);
2784                             break;
2785                         default:
2786 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2787                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
2788                                 // remote does not offer ertm but it's required
2789                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2790                                 break;
2791                             }
2792 #endif
2793                             // retry on negative result
2794                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2795                             break;
2796                     }
2797                     break;
2798                 default:
2799                     break;
2800             }
2801             if (l2cap_channel_ready_for_open(channel)){
2802 
2803 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2804                 // assert that packet can be stored in fragment buffers in ertm
2805                 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
2806                     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
2807                     uint16_t usable_mtu = channel->num_tx_buffers == 1 ? effective_mps : channel->num_tx_buffers * effective_mps - 2;
2808                     if (usable_mtu < channel->remote_mtu){
2809                         log_info("Remote MTU %u > max storable ERTM packet, only using MTU = %u", channel->remote_mtu, usable_mtu);
2810                         channel->remote_mtu = usable_mtu;
2811                     }
2812                 }
2813 #endif
2814                 // for open:
2815                 channel->state = L2CAP_STATE_OPEN;
2816                 l2cap_emit_channel_opened(channel, 0);
2817             }
2818             break;
2819 
2820         case L2CAP_STATE_WAIT_DISCONNECT:
2821             switch (code) {
2822                 case DISCONNECTION_RESPONSE:
2823                     l2cap_finialize_channel_close(channel);
2824                     break;
2825                 default:
2826                     //@TODO: implement other signaling packets
2827                     break;
2828             }
2829             break;
2830 
2831         case L2CAP_STATE_CLOSED:
2832             // @TODO handle incoming requests
2833             break;
2834 
2835         case L2CAP_STATE_OPEN:
2836             //@TODO: implement other signaling packets, e.g. re-configure
2837             break;
2838         default:
2839             break;
2840     }
2841     // log_info("new state %u", channel->state);
2842 }
2843 
2844 
2845 // @pre command len is valid, see check in l2cap_acl_classic_handler
2846 static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
2847 
2848     btstack_linked_list_iterator_t it;
2849 
2850     // get code, signalind identifier and command len
2851     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2852     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2853     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2854 
2855     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
2856     if ((code < 1) || (code == ECHO_RESPONSE) || (code > INFORMATION_RESPONSE)){
2857         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2858         return;
2859     }
2860 
2861     // general commands without an assigned channel
2862     switch(code) {
2863 
2864         case CONNECTION_REQUEST:
2865             if (cmd_len == 4){
2866                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2867                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
2868                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
2869             } else {
2870                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2871             }
2872             return;
2873 
2874         case ECHO_REQUEST:
2875             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
2876             return;
2877 
2878         case INFORMATION_REQUEST:
2879             if (cmd_len == 2) {
2880                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2881                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
2882             } else {
2883                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2884             }
2885             return;
2886 
2887 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2888         case INFORMATION_RESPONSE: {
2889             hci_connection_t * connection = hci_connection_for_handle(handle);
2890             if (!connection) return;
2891             if (connection->l2cap_state.information_state != L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE) return;
2892 
2893             // get extended features from response if valid
2894             connection->l2cap_state.extended_feature_mask = 0;
2895             if (cmd_len >= 6) {
2896                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2897                 uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
2898                 if (result == 0 && info_type == L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) {
2899                     connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2900                 }
2901             }
2902             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
2903             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
2904 
2905             // trigger connection request
2906             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2907             while (btstack_linked_list_iterator_has_next(&it)){
2908                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2909                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2910                 if (channel->con_handle != handle) continue;
2911 
2912                 // incoming connection: ask user for channel configuration, esp. if ertm will be mandatory
2913                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
2914                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2915                     l2cap_emit_incoming_connection(channel);
2916                     continue;
2917                 }
2918 
2919                 // outgoing connection
2920                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
2921 
2922                     // if ERTM was requested, but is not listed in extended feature mask:
2923                     if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2924 
2925                         if (channel->ertm_mandatory){
2926                             // bail if ERTM is mandatory
2927                             channel->state = L2CAP_STATE_CLOSED;
2928                             // map l2cap connection response result to BTstack status enumeration
2929                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
2930                             // discard channel
2931                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2932                             l2cap_free_channel_entry(channel);
2933                             continue;
2934 
2935                         } else {
2936                             // fallback to Basic mode
2937                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
2938                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2939                         }
2940                     }
2941 
2942                     // respond to connection request
2943                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
2944                     continue;
2945                 }
2946             }
2947             return;
2948         }
2949 #endif
2950 
2951         default:
2952             break;
2953     }
2954 
2955     // Get potential destination CID
2956     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2957 
2958     // Find channel for this sig_id and connection handle
2959     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2960     while (btstack_linked_list_iterator_has_next(&it)){
2961         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2962         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2963         if (channel->con_handle != handle) continue;
2964         if (code & 1) {
2965             // match odd commands (responses) by previous signaling identifier
2966             if (channel->local_sig_id == sig_id) {
2967                 l2cap_signaling_handler_channel(channel, command);
2968                 break;
2969             }
2970         } else {
2971             // match even commands (requests) by local channel id
2972             if (channel->local_cid == dest_cid) {
2973                 l2cap_signaling_handler_channel(channel, command);
2974                 break;
2975             }
2976         }
2977     }
2978 }
2979 #endif
2980 
2981 #ifdef ENABLE_BLE
2982 
2983 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
2984     uint8_t event[6];
2985     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
2986     event[1] = 4;
2987     little_endian_store_16(event, 2, con_handle);
2988     little_endian_store_16(event, 4, result);
2989     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2990     if (!l2cap_event_packet_handler) return;
2991     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
2992 }
2993 
2994 // @returns valid
2995 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
2996     hci_connection_t * connection;
2997     uint16_t result;
2998     uint8_t  event[12];
2999 
3000 #ifdef ENABLE_LE_DATA_CHANNELS
3001     btstack_linked_list_iterator_t it;
3002     l2cap_channel_t * channel;
3003     uint16_t local_cid;
3004     uint16_t le_psm;
3005     uint16_t new_credits;
3006     uint16_t credits_before;
3007     l2cap_service_t * service;
3008     uint16_t source_cid;
3009 #endif
3010 
3011     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3012     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3013     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
3014 
3015     switch (code){
3016 
3017         case CONNECTION_PARAMETER_UPDATE_REQUEST:
3018             // check size
3019             if (len < 8) return 0;
3020             connection = hci_connection_for_handle(handle);
3021             if (connection){
3022                 if (connection->role != HCI_ROLE_MASTER){
3023                     // reject command without notifying upper layer when not in master role
3024                     return 0;
3025                 }
3026                 le_connection_parameter_range_t existing_range;
3027                 gap_get_connection_parameter_range(&existing_range);
3028                 uint16_t le_conn_interval_min   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3029                 uint16_t le_conn_interval_max   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3030                 uint16_t le_conn_latency        = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3031                 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
3032 
3033                 int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
3034                 if (update_parameter){
3035                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
3036                     connection->le_conn_interval_min = le_conn_interval_min;
3037                     connection->le_conn_interval_max = le_conn_interval_max;
3038                     connection->le_conn_latency = le_conn_latency;
3039                     connection->le_supervision_timeout = le_supervision_timeout;
3040                 } else {
3041                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
3042                 }
3043                 connection->le_con_param_update_identifier = sig_id;
3044             }
3045 
3046             if (!l2cap_event_packet_handler) break;
3047 
3048             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
3049             event[1] = 8;
3050             little_endian_store_16(event, 2, handle);
3051             (void)memcpy(&event[4], &command[4], 8);
3052             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3053             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
3054             break;
3055 
3056         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
3057             // check size
3058             if (len < 2) return 0;
3059             result = little_endian_read_16(command, 4);
3060             l2cap_emit_connection_parameter_update_response(handle, result);
3061             break;
3062 
3063 #ifdef ENABLE_LE_DATA_CHANNELS
3064 
3065         case COMMAND_REJECT:
3066             // Find channel for this sig_id and connection handle
3067             channel = NULL;
3068             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3069             while (btstack_linked_list_iterator_has_next(&it)){
3070                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3071                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
3072                 if (a_channel->con_handle   != handle) continue;
3073                 if (a_channel->local_sig_id != sig_id) continue;
3074                 channel = a_channel;
3075                 break;
3076             }
3077             if (!channel) break;
3078 
3079             // if received while waiting for le connection response, assume legacy device
3080             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
3081                 channel->state = L2CAP_STATE_CLOSED;
3082                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
3083                 l2cap_emit_le_channel_opened(channel, 0x0002);
3084 
3085                 // discard channel
3086                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3087                 l2cap_free_channel_entry(channel);
3088                 break;
3089             }
3090             break;
3091 
3092         case LE_CREDIT_BASED_CONNECTION_REQUEST:
3093             // check size
3094             if (len < 10) return 0;
3095 
3096             // get hci connection, bail if not found (must not happen)
3097             connection = hci_connection_for_handle(handle);
3098             if (!connection) return 0;
3099 
3100             // check if service registered
3101             le_psm  = little_endian_read_16(command, 4);
3102             service = l2cap_le_get_service(le_psm);
3103             source_cid = little_endian_read_16(command, 6);
3104 
3105             if (service){
3106                 if (source_cid < 0x40){
3107                     // 0x0009 Connection refused - Invalid Source CID
3108                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
3109                     return 1;
3110                 }
3111 
3112                 // go through list of channels for this ACL connection and check if we get a match
3113                 btstack_linked_list_iterator_init(&it, &l2cap_channels);
3114                 while (btstack_linked_list_iterator_has_next(&it)){
3115                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3116                     if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
3117                     if (a_channel->con_handle != handle) continue;
3118                     if (a_channel->remote_cid != source_cid) continue;
3119                     // 0x000a Connection refused - Source CID already allocated
3120                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
3121                     return 1;
3122                 }
3123 
3124                 // security: check encryption
3125                 if (service->required_security_level >= LEVEL_2){
3126                     if (gap_encryption_key_size(handle) == 0){
3127                         // 0x0008 Connection refused - insufficient encryption
3128                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
3129                         return 1;
3130                     }
3131                     // anything less than 16 byte key size is insufficient
3132                     if (gap_encryption_key_size(handle) < 16){
3133                         // 0x0007 Connection refused – insufficient encryption key size
3134                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
3135                         return 1;
3136                     }
3137                 }
3138 
3139                 // security: check authencation
3140                 if (service->required_security_level >= LEVEL_3){
3141                     if (!gap_authenticated(handle)){
3142                         // 0x0005 Connection refused – insufficient authentication
3143                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
3144                         return 1;
3145                     }
3146                 }
3147 
3148                 // security: check authorization
3149                 if (service->required_security_level >= LEVEL_4){
3150                     if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
3151                         // 0x0006 Connection refused – insufficient authorization
3152                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
3153                         return 1;
3154                     }
3155                 }
3156 
3157                 // allocate channel
3158                 channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL, connection->address,
3159                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
3160                 if (!channel){
3161                     // 0x0004 Connection refused – no resources available
3162                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
3163                     return 1;
3164                 }
3165 
3166                 channel->con_handle = handle;
3167                 channel->remote_cid = source_cid;
3168                 channel->remote_sig_id = sig_id;
3169                 channel->remote_mtu = little_endian_read_16(command, 8);
3170                 channel->remote_mps = little_endian_read_16(command, 10);
3171                 channel->credits_outgoing = little_endian_read_16(command, 12);
3172 
3173                 // set initial state
3174                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
3175                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
3176 
3177                 // add to connections list
3178                 btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
3179 
3180                 // post connection request event
3181                 l2cap_emit_le_incoming_connection(channel);
3182 
3183             } else {
3184                 // Connection refused – LE_PSM not supported
3185                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
3186             }
3187             break;
3188 
3189         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
3190             // check size
3191             if (len < 10) return 0;
3192 
3193             // Find channel for this sig_id and connection handle
3194             channel = NULL;
3195             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3196             while (btstack_linked_list_iterator_has_next(&it)){
3197                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3198                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
3199                 if (a_channel->con_handle   != handle) continue;
3200                 if (a_channel->local_sig_id != sig_id) continue;
3201                 channel = a_channel;
3202                 break;
3203             }
3204             if (!channel) break;
3205 
3206             // cid + 0
3207             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
3208             if (result){
3209                 channel->state = L2CAP_STATE_CLOSED;
3210                 // map l2cap connection response result to BTstack status enumeration
3211                 l2cap_emit_le_channel_opened(channel, result);
3212 
3213                 // discard channel
3214                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3215                 l2cap_free_channel_entry(channel);
3216                 break;
3217             }
3218 
3219             // success
3220             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3221             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3222             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3223             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
3224             channel->state = L2CAP_STATE_OPEN;
3225             l2cap_emit_le_channel_opened(channel, result);
3226             break;
3227 
3228         case LE_FLOW_CONTROL_CREDIT:
3229             // check size
3230             if (len < 4) return 0;
3231 
3232             // find channel
3233             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3234             channel = l2cap_get_channel_for_local_cid(local_cid);
3235             if (!channel) {
3236                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
3237                 break;
3238             }
3239             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3240             credits_before = channel->credits_outgoing;
3241             channel->credits_outgoing += new_credits;
3242             // check for credit overrun
3243             if (credits_before > channel->credits_outgoing){
3244                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
3245                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3246                 break;
3247             }
3248             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
3249             break;
3250 
3251         case DISCONNECTION_REQUEST:
3252 
3253             // check size
3254             if (len < 4) return 0;
3255 
3256             // find channel
3257             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3258             channel = l2cap_get_channel_for_local_cid(local_cid);
3259             if (!channel) {
3260                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
3261                 break;
3262             }
3263             channel->remote_sig_id = sig_id;
3264             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
3265             break;
3266 
3267 #endif
3268 
3269         case DISCONNECTION_RESPONSE:
3270             break;
3271 
3272         default:
3273             // command unknown -> reject command
3274             return 0;
3275     }
3276     return 1;
3277 }
3278 #endif
3279 
3280 #ifdef ENABLE_CLASSIC
3281 static void l2cap_acl_classic_handler_for_channel(l2cap_channel_t * l2cap_channel, uint8_t * packet, uint16_t size){
3282 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3283     if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3284 
3285         int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
3286 
3287         // assert control + FCS fields are inside
3288         if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) return;
3289 
3290         if (l2cap_channel->fcs_option){
3291             // verify FCS (required if one side requested it)
3292             uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
3293             uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
3294 
3295 #ifdef L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL
3296             // simulate fcs error
3297                         static int counter = 0;
3298                         if (++counter == L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL) {
3299                             log_info("Simulate fcs error");
3300                             fcs_calculated++;
3301                             counter = 0;
3302                         }
3303 #endif
3304 
3305             if (fcs_calculated == fcs_packet){
3306                 log_info("Packet FCS 0x%04x verified", fcs_packet);
3307             } else {
3308                 log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
3309                 // ERTM State Machine in Bluetooth Spec does not handle 'I-Frame with invalid FCS'
3310                 return;
3311             }
3312         }
3313 
3314         // switch on packet type
3315         uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3316         uint8_t  req_seq = (control >> 8) & 0x3f;
3317         int final = (control >> 7) & 0x01;
3318         if (control & 1){
3319             // S-Frame
3320             int poll  = (control >> 4) & 0x01;
3321             l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
3322             log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
3323             l2cap_ertm_tx_packet_state_t * tx_state;
3324             switch (s){
3325                 case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
3326                     log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
3327                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3328                     if (poll && final){
3329                         // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
3330                         log_error("P=F=1 in S-Frame");
3331                         break;
3332                     }
3333                     if (poll){
3334                         // check if we did request selective retransmission before <==> we have stored SDU segments
3335                         int i;
3336                         int num_stored_out_of_order_packets = 0;
3337                         for (i=0;i<l2cap_channel->num_rx_buffers;i++){
3338                             int index = l2cap_channel->rx_store_index + i;
3339                             if (index >= l2cap_channel->num_rx_buffers){
3340                                 index -= l2cap_channel->num_rx_buffers;
3341                             }
3342                             l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3343                             if (!rx_state->valid) continue;
3344                             num_stored_out_of_order_packets++;
3345                         }
3346                         if (num_stored_out_of_order_packets){
3347                             l2cap_channel->send_supervisor_frame_selective_reject = 1;
3348                         } else {
3349                             l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
3350                         }
3351                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
3352                     }
3353                     if (final){
3354                         // Stop-MonitorTimer
3355                         l2cap_ertm_stop_monitor_timer(l2cap_channel);
3356                         // If UnackedFrames > 0 then Start-RetransTimer
3357                         if (l2cap_channel->unacked_frames){
3358                             l2cap_ertm_start_retransmission_timer(l2cap_channel);
3359                         }
3360                         // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3361                         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
3362                     }
3363                     break;
3364                 case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
3365                     log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
3366                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3367                     // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
3368                     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
3369                     break;
3370                 case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
3371                     log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
3372                     break;
3373                 case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
3374                     log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
3375                     if (poll){
3376                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3377                     }
3378                     // find requested i-frame
3379                     tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
3380                     if (tx_state){
3381                         log_info("Retransmission for tx_seq %u requested", req_seq);
3382                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
3383                         tx_state->retransmission_requested = 1;
3384                         l2cap_channel->srej_active = 1;
3385                     }
3386                     break;
3387                 default:
3388                     break;
3389             }
3390         } else {
3391             // I-Frame
3392             // get control
3393             l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
3394             uint8_t tx_seq = (control >> 1) & 0x3f;
3395             log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
3396             log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
3397             log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
3398             l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3399             if (final){
3400                 // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3401                 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
3402             }
3403 
3404             // get SDU
3405             const uint8_t * payload_data = &packet[COMPLETE_L2CAP_HEADER+2];
3406             uint16_t        payload_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
3407 
3408             // assert SDU size is smaller or equal to our buffers
3409             uint16_t max_payload_size = 0;
3410             switch (sar){
3411                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
3412                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
3413                     // SDU Length + MPS
3414                     max_payload_size = l2cap_channel->local_mps + 2;
3415                     break;
3416                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
3417                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
3418                     max_payload_size = l2cap_channel->local_mps;
3419                     break;
3420             }
3421             if (payload_len > max_payload_size){
3422                 log_info("payload len %u > max payload %u -> drop packet", payload_len, max_payload_size);
3423                 return;
3424             }
3425 
3426             // check ordering
3427             if (l2cap_channel->expected_tx_seq == tx_seq){
3428                 log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
3429                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3430                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3431 
3432                 // process SDU
3433                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, payload_data, payload_len);
3434 
3435                 // process stored segments
3436                 while (true){
3437                     int index = l2cap_channel->rx_store_index;
3438                     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3439                     if (!rx_state->valid) break;
3440 
3441                     log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
3442                     l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3443                     l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3444 
3445                     rx_state->valid = 0;
3446                     l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
3447 
3448                     // update rx store index
3449                     index++;
3450                     if (index >= l2cap_channel->num_rx_buffers){
3451                         index = 0;
3452                     }
3453                     l2cap_channel->rx_store_index = index;
3454                 }
3455 
3456                 //
3457                 l2cap_channel->send_supervisor_frame_receiver_ready = 1;
3458 
3459             } else {
3460                 int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
3461                 if (delta < 2){
3462                     // store segment
3463                     l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, payload_data, payload_len);
3464 
3465                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
3466                     l2cap_channel->send_supervisor_frame_selective_reject = 1;
3467                 } else {
3468                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
3469                     l2cap_channel->send_supervisor_frame_reject = 1;
3470                 }
3471             }
3472         }
3473         return;
3474     }
3475 #endif
3476     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3477 
3478 }
3479 #endif
3480 
3481 static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3482 #ifdef ENABLE_CLASSIC
3483     l2cap_channel_t * l2cap_channel;
3484     l2cap_fixed_channel_t * l2cap_fixed_channel;
3485 
3486     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3487     switch (channel_id) {
3488 
3489         case L2CAP_CID_SIGNALING: {
3490             uint32_t command_offset = 8;
3491             while ((command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET) < size) {
3492                 // assert signaling command is fully inside packet
3493                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3494                 uint32_t next_command_offset = command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
3495                 if (next_command_offset > size){
3496                     log_error("l2cap signaling command len invalid -> drop");
3497                     break;
3498                 }
3499                 // handle signaling command
3500                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
3501                 // go to next command
3502                 command_offset = next_command_offset;
3503             }
3504             break;
3505         }
3506         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
3507             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL);
3508             if (!l2cap_fixed_channel) break;
3509             if (!l2cap_fixed_channel->packet_handler) break;
3510             (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3511             break;
3512 
3513         default:
3514             // Find channel for this channel_id and connection handle
3515             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
3516             if (l2cap_channel) {
3517                 l2cap_acl_classic_handler_for_channel(l2cap_channel, packet, size);
3518             }
3519             break;
3520     }
3521 #else
3522     UNUSED(handle); // ok: no code
3523     UNUSED(packet); // ok: no code
3524     UNUSED(size);   // ok: no code
3525 #endif
3526 }
3527 
3528 static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3529 #ifdef ENABLE_BLE
3530 
3531     l2cap_fixed_channel_t * l2cap_fixed_channel;
3532 
3533 #ifdef ENABLE_LE_DATA_CHANNELS
3534     l2cap_channel_t * l2cap_channel;
3535 #endif
3536     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3537     switch (channel_id) {
3538 
3539         case L2CAP_CID_SIGNALING_LE: {
3540             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
3541             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
3542             if ((COMPLETE_L2CAP_HEADER + 4 + len) > size) break;
3543             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
3544             if (!valid){
3545                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3546             }
3547             break;
3548         }
3549 
3550         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
3551             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL);
3552             if (!l2cap_fixed_channel) break;
3553             if (!l2cap_fixed_channel->packet_handler) break;
3554             (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3555             break;
3556 
3557         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
3558             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
3559             if (!l2cap_fixed_channel) break;
3560             if (!l2cap_fixed_channel->packet_handler) break;
3561             (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3562             break;
3563 
3564         default:
3565 
3566 #ifdef ENABLE_LE_DATA_CHANNELS
3567             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
3568             if (l2cap_channel) {
3569                 // credit counting
3570                 if (l2cap_channel->credits_incoming == 0){
3571                     log_error("LE Data Channel packet received but no incoming credits");
3572                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3573                     break;
3574                 }
3575                 l2cap_channel->credits_incoming--;
3576 
3577                 // automatic credits
3578                 if ((l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK) && l2cap_channel->automatic_credits){
3579                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
3580                 }
3581 
3582                 // first fragment
3583                 uint16_t pos = 0;
3584                 if (!l2cap_channel->receive_sdu_len){
3585                     uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3586                     if(sdu_len > l2cap_channel->local_mtu) break;   // SDU would be larger than our buffer
3587                     l2cap_channel->receive_sdu_len = sdu_len;
3588                     l2cap_channel->receive_sdu_pos = 0;
3589                     pos  += 2;
3590                     size -= 2;
3591                 }
3592                 uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
3593                 uint16_t remaining_space = l2cap_channel->local_mtu - l2cap_channel->receive_sdu_pos;
3594                 if (fragment_size > remaining_space) break;         // SDU would cause buffer overrun
3595                 (void)memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos],
3596                              &packet[COMPLETE_L2CAP_HEADER + pos],
3597                              fragment_size);
3598                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
3599                 // done?
3600                 log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
3601                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
3602                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
3603                     l2cap_channel->receive_sdu_len = 0;
3604                 }
3605             } else {
3606                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
3607             }
3608 #endif
3609             break;
3610     }
3611 #else
3612     UNUSED(handle); // ok: no code
3613     UNUSED(packet); // ok: no code
3614     UNUSED(size);   // ok: no code
3615 #endif
3616 }
3617 
3618 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
3619     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
3620     UNUSED(channel);        // ok: there is no channel
3621 
3622     // Assert full L2CAP header present
3623     if (size < COMPLETE_L2CAP_HEADER) return;
3624 
3625     // Dispatch to Classic or LE handler (SCO packets are not dispatched to L2CAP)
3626     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
3627     hci_connection_t *conn = hci_connection_for_handle(handle);
3628     if (!conn) return;
3629     if (conn->address_type == BD_ADDR_TYPE_ACL){
3630         l2cap_acl_classic_handler(handle, packet, size);
3631     } else {
3632         l2cap_acl_le_handler(handle, packet, size);
3633     }
3634 
3635     l2cap_run();
3636 }
3637 
3638 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
3639 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
3640     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
3641     if (!channel) return;
3642     channel->packet_handler = the_packet_handler;
3643 }
3644 
3645 #ifdef ENABLE_CLASSIC
3646 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
3647 void l2cap_finialize_channel_close(l2cap_channel_t * channel){
3648     channel->state = L2CAP_STATE_CLOSED;
3649     l2cap_handle_channel_closed(channel);
3650     // discard channel
3651     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3652     l2cap_free_channel_entry(channel);
3653 }
3654 #endif
3655 
3656 #ifdef L2CAP_USES_CHANNELS
3657 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3658     btstack_linked_list_iterator_t it;
3659     btstack_linked_list_iterator_init(&it, services);
3660     while (btstack_linked_list_iterator_has_next(&it)){
3661         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
3662         if ( service->psm == psm){
3663             return service;
3664         };
3665     }
3666     return NULL;
3667 }
3668 #endif
3669 
3670 #ifdef ENABLE_CLASSIC
3671 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
3672     return l2cap_get_service_internal(&l2cap_services, psm);
3673 }
3674 
3675 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
3676 
3677     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
3678 
3679     // check for alread registered psm
3680     l2cap_service_t *service = l2cap_get_service(psm);
3681     if (service) {
3682         log_error("l2cap_register_service: PSM %u already registered", psm);
3683         return L2CAP_SERVICE_ALREADY_REGISTERED;
3684     }
3685 
3686     // alloc structure
3687     service = btstack_memory_l2cap_service_get();
3688     if (!service) {
3689         log_error("l2cap_register_service: no memory for l2cap_service_t");
3690         return BTSTACK_MEMORY_ALLOC_FAILED;
3691     }
3692 
3693     // fill in
3694     service->psm = psm;
3695     service->mtu = mtu;
3696     service->packet_handler = service_packet_handler;
3697     service->required_security_level = security_level;
3698 
3699     // add to services list
3700     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
3701 
3702     // enable page scan
3703     gap_connectable_control(1);
3704 
3705     return ERROR_CODE_SUCCESS;
3706 }
3707 
3708 uint8_t l2cap_unregister_service(uint16_t psm){
3709 
3710     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
3711 
3712     l2cap_service_t *service = l2cap_get_service(psm);
3713     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3714     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
3715     btstack_memory_l2cap_service_free(service);
3716 
3717     // disable page scan when no services registered
3718     if (btstack_linked_list_empty(&l2cap_services)) {
3719         gap_connectable_control(0);
3720     }
3721     return ERROR_CODE_SUCCESS;
3722 }
3723 #endif
3724 
3725 
3726 #ifdef ENABLE_LE_DATA_CHANNELS
3727 
3728 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
3729     if (!channel->waiting_for_can_send_now) return;
3730     if (channel->send_sdu_buffer) return;
3731     channel->waiting_for_can_send_now = 0;
3732     log_debug("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
3733     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
3734 }
3735 
3736 // 1BH2222
3737 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
3738     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",
3739              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
3740     uint8_t event[19];
3741     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
3742     event[1] = sizeof(event) - 2;
3743     event[2] = channel->address_type;
3744     reverse_bd_addr(channel->address, &event[3]);
3745     little_endian_store_16(event,  9, channel->con_handle);
3746     little_endian_store_16(event, 11, channel->psm);
3747     little_endian_store_16(event, 13, channel->local_cid);
3748     little_endian_store_16(event, 15, channel->remote_cid);
3749     little_endian_store_16(event, 17, channel->remote_mtu);
3750     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3751     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3752 }
3753 // 11BH22222
3754 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
3755     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",
3756              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
3757              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
3758     uint8_t event[23];
3759     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
3760     event[1] = sizeof(event) - 2;
3761     event[2] = status;
3762     event[3] = channel->address_type;
3763     reverse_bd_addr(channel->address, &event[4]);
3764     little_endian_store_16(event, 10, channel->con_handle);
3765     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
3766     little_endian_store_16(event, 13, channel->psm);
3767     little_endian_store_16(event, 15, channel->local_cid);
3768     little_endian_store_16(event, 17, channel->remote_cid);
3769     little_endian_store_16(event, 19, channel->local_mtu);
3770     little_endian_store_16(event, 21, channel->remote_mtu);
3771     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3772     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3773 }
3774 // 2
3775 static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel){
3776     log_info("L2CAP_EVENT_LE_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
3777     uint8_t event[4];
3778     event[0] = L2CAP_EVENT_LE_CHANNEL_CLOSED;
3779     event[1] = sizeof(event) - 2;
3780     little_endian_store_16(event, 2, channel->local_cid);
3781     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3782     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3783 }
3784 
3785 static void l2cap_le_send_pdu(l2cap_channel_t *channel){
3786     btstack_assert(channel != NULL);
3787     btstack_assert(channel->send_pdu_buffer != NULL);
3788     btstack_assert(channel->credits_outgoing > 0);
3789 
3790     // send part of SDU
3791     hci_reserve_packet_buffer();
3792     uint8_t * acl_buffer = hci_get_outgoing_packet_buffer();
3793     uint8_t * l2cap_payload = acl_buffer + 8;
3794     uint16_t pos = 0;
3795     if (!channel->send_sdu_pos){
3796         // store SDU len
3797         channel->send_sdu_pos += 2;
3798         little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
3799         pos += 2;
3800     }
3801     uint16_t payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
3802     log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
3803     (void)memcpy(&l2cap_payload[pos],
3804                  &channel->send_sdu_buffer[channel->send_sdu_pos - 2],
3805                  payload_size); // -2 for virtual SDU len
3806     pos += payload_size;
3807     channel->send_sdu_pos += payload_size;
3808     l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
3809 
3810     channel->credits_outgoing--;
3811 
3812     hci_send_acl_packet_buffer(8 + pos);
3813 
3814     if (channel->send_sdu_pos >= (channel->send_sdu_len + 2)){
3815         channel->send_sdu_buffer = NULL;
3816         // send done event
3817         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
3818         // inform about can send now
3819         l2cap_le_notify_channel_can_send(channel);
3820     }
3821 }
3822 
3823 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
3824 void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
3825     channel->state = L2CAP_STATE_CLOSED;
3826     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
3827     // discard channel
3828     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3829     l2cap_free_channel_entry(channel);
3830 }
3831 
3832 static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
3833     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
3834 }
3835 
3836 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
3837 
3838     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
3839 
3840     // check for alread registered psm
3841     l2cap_service_t *service = l2cap_le_get_service(psm);
3842     if (service) {
3843         return L2CAP_SERVICE_ALREADY_REGISTERED;
3844     }
3845 
3846     // alloc structure
3847     service = btstack_memory_l2cap_service_get();
3848     if (!service) {
3849         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
3850         return BTSTACK_MEMORY_ALLOC_FAILED;
3851     }
3852 
3853     // fill in
3854     service->psm = psm;
3855     service->mtu = 0;
3856     service->packet_handler = packet_handler;
3857     service->required_security_level = security_level;
3858 
3859     // add to services list
3860     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
3861 
3862     // done
3863     return ERROR_CODE_SUCCESS;
3864 }
3865 
3866 uint8_t l2cap_le_unregister_service(uint16_t psm) {
3867     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
3868     l2cap_service_t *service = l2cap_le_get_service(psm);
3869     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3870 
3871     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
3872     btstack_memory_l2cap_service_free(service);
3873     return ERROR_CODE_SUCCESS;
3874 }
3875 
3876 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
3877     // get channel
3878     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3879     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3880 
3881     // validate state
3882     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3883         return ERROR_CODE_COMMAND_DISALLOWED;
3884     }
3885 
3886     // set state accept connection
3887     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
3888     channel->receive_sdu_buffer = receive_sdu_buffer;
3889     channel->local_mtu = mtu;
3890     channel->new_credits_incoming = initial_credits;
3891     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
3892 
3893     // test
3894     // channel->new_credits_incoming = 1;
3895 
3896     // go
3897     l2cap_run();
3898     return ERROR_CODE_SUCCESS;
3899 }
3900 
3901 /**
3902  * @brief Deny incoming LE Data Channel connection due to resource constraints
3903  * @param local_cid             L2CAP LE Data Channel Identifier
3904  */
3905 
3906 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
3907     // get channel
3908     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3909     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3910 
3911     // validate state
3912     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3913         return ERROR_CODE_COMMAND_DISALLOWED;
3914     }
3915 
3916     // set state decline connection
3917     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
3918     channel->reason = 0x04; // no resources available
3919     l2cap_run();
3920     return ERROR_CODE_SUCCESS;
3921 }
3922 
3923 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
3924     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
3925     uint16_t * out_local_cid) {
3926 
3927     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
3928 
3929 
3930     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3931     if (!connection) {
3932         log_error("no hci_connection for handle 0x%04x", con_handle);
3933         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3934     }
3935 
3936     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL, connection->address, connection->address_type, psm, mtu, security_level);
3937     if (!channel) {
3938         return BTSTACK_MEMORY_ALLOC_FAILED;
3939     }
3940     log_info("l2cap_le_create_channel %p", channel);
3941 
3942     // store local_cid
3943     if (out_local_cid){
3944        *out_local_cid = channel->local_cid;
3945     }
3946 
3947     // provide buffer
3948     channel->con_handle = con_handle;
3949     channel->receive_sdu_buffer = receive_sdu_buffer;
3950     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
3951     channel->new_credits_incoming = initial_credits;
3952     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
3953 
3954     // add to connections list
3955     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
3956 
3957     // go
3958     l2cap_run();
3959     return ERROR_CODE_SUCCESS;
3960 }
3961 
3962 /**
3963  * @brief Provide credtis for LE Data Channel
3964  * @param local_cid             L2CAP LE Data Channel Identifier
3965  * @param credits               Number additional credits for peer
3966  */
3967 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
3968 
3969     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3970     if (!channel) {
3971         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
3972         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3973     }
3974 
3975     // check state
3976     if (channel->state != L2CAP_STATE_OPEN){
3977         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
3978     }
3979 
3980     // assert incoming credits + credits <= 0xffff
3981     uint32_t total_credits = channel->credits_incoming;
3982     total_credits += channel->new_credits_incoming;
3983     total_credits += credits;
3984     if (total_credits > 0xffff){
3985         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
3986             channel->new_credits_incoming, credits);
3987     }
3988 
3989     // set credits_granted
3990     channel->new_credits_incoming += credits;
3991 
3992     // go
3993     l2cap_run();
3994     return ERROR_CODE_SUCCESS;
3995 }
3996 
3997 /**
3998  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
3999  * @param local_cid             L2CAP LE Data Channel Identifier
4000  */
4001 int l2cap_le_can_send_now(uint16_t local_cid){
4002     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4003     if (!channel) {
4004         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
4005         return 0;
4006     }
4007 
4008     // check state
4009     if (channel->state != L2CAP_STATE_OPEN) return 0;
4010 
4011     // check queue
4012     if (channel->send_sdu_buffer) return 0;
4013 
4014     // fine, go ahead
4015     return 1;
4016 }
4017 
4018 /**
4019  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
4020  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
4021  *       so packet handler should be ready to handle it
4022  * @param local_cid             L2CAP LE Data Channel Identifier
4023  */
4024 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
4025     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4026     if (!channel) {
4027         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
4028         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4029     }
4030     channel->waiting_for_can_send_now = 1;
4031     l2cap_le_notify_channel_can_send(channel);
4032     return ERROR_CODE_SUCCESS;
4033 }
4034 
4035 /**
4036  * @brief Send data via LE Data Channel
4037  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
4038  * @param local_cid             L2CAP LE Data Channel Identifier
4039  * @param data                  data to send
4040  * @param size                  data size
4041  */
4042 uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
4043 
4044     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4045     if (!channel) {
4046         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4047         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4048     }
4049 
4050     if (len > channel->remote_mtu){
4051         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
4052         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
4053     }
4054 
4055     if (channel->send_sdu_buffer){
4056         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
4057         return BTSTACK_ACL_BUFFERS_FULL;
4058     }
4059 
4060     channel->send_sdu_buffer = data;
4061     channel->send_sdu_len    = len;
4062     channel->send_sdu_pos    = 0;
4063 
4064     l2cap_notify_channel_can_send();
4065     return ERROR_CODE_SUCCESS;
4066 }
4067 
4068 /**
4069  * @brief Disconnect from LE Data Channel
4070  * @param local_cid             L2CAP LE Data Channel Identifier
4071  */
4072 uint8_t l2cap_le_disconnect(uint16_t local_cid)
4073 {
4074     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4075     if (!channel) {
4076         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4077         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4078     }
4079 
4080     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4081     l2cap_run();
4082     return ERROR_CODE_SUCCESS;
4083 }
4084 
4085 #endif
4086