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