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