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