xref: /btstack/src/l2cap.c (revision d9f55599ce29794416a96ae0ee52b96b5b2a006e)
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 BLUEKITCHEN
24  * GMBH 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  *  Logical Link Control and Adaption Protocol (L2CAP)
43  */
44 
45 #include "l2cap.h"
46 #include "hci.h"
47 #include "hci_dump.h"
48 #include "bluetooth_sdp.h"
49 #include "bluetooth_psm.h"
50 #include "btstack_bool.h"
51 #include "btstack_debug.h"
52 #include "btstack_event.h"
53 #include "btstack_memory.h"
54 
55 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
56 // TODO avoid dependency on higher layer: used to trigger pairing for outgoing connections
57 #include "ble/sm.h"
58 #endif
59 
60 #include <stdarg.h>
61 #include <string.h>
62 
63 /*
64  * @brief L2CAP Supervisory function in S-Frames
65  */
66 typedef enum {
67     L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY = 0,
68     L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT,
69     L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY,
70     L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT
71 } l2cap_supervisory_function_t;
72 
73 /**
74  * @brief L2CAP Information Types used in Information Request & Response
75  */
76 typedef enum {
77   L2CAP_INFO_TYPE_CONNECTIONLESS_MTU = 1,
78   L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED,
79   L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED,
80 } l2cap_info_type_t;
81 
82 /**
83  * @brief L2CAP Configuration Option Types used in Configurateion Request & Response
84  */
85 typedef enum {
86   L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT = 1,
87   L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT,
88   L2CAP_CONFIG_OPTION_TYPE_QUALITY_OF_SERVICE,
89   L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL,
90   L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE,
91   L2CAP_CONFIG_OPTION_TYPE_EXTENDED_FLOW_SPECIFICATION,
92   L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE,
93 } l2cap_config_option_type_t;
94 
95 
96 #define L2CAP_SIG_ID_INVALID 0
97 
98 // size of HCI ACL + L2CAP Header for regular data packets (8)
99 #define COMPLETE_L2CAP_HEADER (HCI_ACL_HEADER_SIZE + L2CAP_HEADER_SIZE)
100 
101 // L2CAP Configuration Result Codes
102 #define L2CAP_CONF_RESULT_SUCCESS                  0x0000
103 #define L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS  0x0001
104 #define L2CAP_CONF_RESULT_REJECT                   0x0002
105 #define L2CAP_CONF_RESULT_UNKNOWN_OPTIONS          0x0003
106 #define L2CAP_CONF_RESULT_PENDING                  0x0004
107 #define L2CAP_CONF_RESULT_FLOW_SPEC_REJECTED       0x0005
108 
109 // L2CAP Reject Result Codes
110 #define L2CAP_REJ_CMD_UNKNOWN                      0x0000
111 
112 // Response Timeout eXpired
113 #define L2CAP_RTX_TIMEOUT_MS   10000
114 
115 // Extended Response Timeout eXpired
116 #define L2CAP_ERTX_TIMEOUT_MS 120000
117 
118 // nr of buffered acl packets in outgoing queue to get max performance
119 #define NR_BUFFERED_ACL_PACKETS 3
120 
121 // used to cache l2cap rejects, echo, and informational requests
122 #define NR_PENDING_SIGNALING_RESPONSES 3
123 
124 // nr of credits provided to remote if credits fall below watermark
125 #define L2CAP_CREDIT_BASED_FLOW_CONTROL_MODE_AUTOMATIC_CREDITS_WATERMARK 5
126 #define L2CAP_CREDIT_BASED_FLOW_CONTROL_MODE_AUTOMATIC_CREDITS_INCREMENT 5
127 
128 // offsets for L2CAP SIGNALING COMMANDS
129 #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
130 #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
131 #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
132 #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
133 
134 #if defined(ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE) && !defined(ENABLE_CLASSIC)
135 #error "ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE depends on ENABLE_CLASSIC."
136 #error "Please remove ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE or add ENABLE_CLASSIC in btstack_config.h"
137 #endif
138 
139 
140 #ifdef ENABLE_LE_DATA_CHANNELS
141 #warning "ENABLE_LE_DATA_CHANNELS has been deprecated."
142 #warning "Please use ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE instead in btstack_config.h"
143 #define ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
144 #endif
145 
146 #if defined(ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE) || defined(ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE)
147 #define L2CAP_USES_CREDIT_BASED_CHANNELS
148 #endif
149 
150 #if defined(L2CAP_USES_CREDIT_BASED_CHANNELS) || defined(ENABLE_CLASSIC)
151 #define L2CAP_USES_CHANNELS
152 #endif
153 
154 // prototypes
155 static void l2cap_run(void);
156 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
157 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size );
158 static void l2cap_notify_channel_can_send(void);
159 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel);
160 static uint8_t  l2cap_next_sig_id(void);
161 static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid);
162 #ifdef ENABLE_CLASSIC
163 static void l2cap_handle_security_level_incoming_sufficient(l2cap_channel_t * channel);
164 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm);
165 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel);
166 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel);
167 static void l2cap_handle_information_request_complete(hci_connection_t * connection);
168 static inline l2cap_service_t * l2cap_get_service(uint16_t psm);
169 static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
170 static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
171 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel);
172 static int  l2cap_channel_ready_for_open(l2cap_channel_t *channel);
173 static uint8_t l2cap_classic_send(l2cap_channel_t * channel, const uint8_t *data, uint16_t len);
174 #endif
175 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
176 static void l2cap_cbm_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
177 static void l2cap_cbm_emit_incoming_connection(l2cap_channel_t *channel);
178 static void l2cap_credit_based_notify_channel_can_send(l2cap_channel_t *channel);
179 static void l2cap_cbm_finialize_channel_close(l2cap_channel_t *channel);
180 static inline l2cap_service_t * l2cap_cbm_get_service(uint16_t le_psm);
181 #endif
182 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
183 static uint8_t l2cap_credit_based_send_data(l2cap_channel_t * channel, const uint8_t * data, uint16_t size);
184 static void l2cap_credit_based_send_pdu(l2cap_channel_t *channel);
185 static void l2cap_credit_based_send_credits(l2cap_channel_t *channel);
186 static bool l2cap_credit_based_handle_credit_indication(hci_con_handle_t handle, const uint8_t * command, uint16_t len);
187 static void l2cap_credit_based_handle_pdu(l2cap_channel_t * l2cap_channel, const uint8_t * packet, uint16_t size);
188 #endif
189 #ifdef L2CAP_USES_CHANNELS
190 static uint16_t l2cap_next_local_cid(void);
191 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid);
192 static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code);
193 static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size);
194 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,
195         uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level);
196 static void l2cap_finalize_channel_close(l2cap_channel_t *channel);
197 static void l2cap_free_channel_entry(l2cap_channel_t * channel);
198 #endif
199 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
200 static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel);
201 static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts);
202 static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts);
203 #endif
204 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
205 static void l2cap_ecbm_handle_security_level_incoming(l2cap_channel_t *channel);
206 static int l2cap_ecbm_signaling_handler_dispatch(hci_con_handle_t handle, uint16_t signaling_cid, uint8_t * command, uint8_t sig_id);
207 static void l2cap_run_trigger_callback(void * context);
208 #endif
209 
210 // l2cap_fixed_channel_t entries
211 #ifdef ENABLE_BLE
212 static l2cap_fixed_channel_t l2cap_fixed_channel_le_att;
213 static l2cap_fixed_channel_t l2cap_fixed_channel_le_sm;
214 #endif
215 #ifdef ENABLE_CLASSIC
216 static l2cap_fixed_channel_t l2cap_fixed_channel_classic_connectionless;
217 static l2cap_fixed_channel_t l2cap_fixed_channel_classic_sm;
218 #endif
219 
220 #ifdef ENABLE_CLASSIC
221 static btstack_linked_list_t l2cap_services;
222 static uint8_t l2cap_require_security_level2_for_outgoing_sdp;
223 static bd_addr_t l2cap_outgoing_classic_addr;
224 #endif
225 
226 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
227 static btstack_linked_list_t l2cap_le_services;
228 #endif
229 
230 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
231 static btstack_linked_list_t l2cap_enhanced_services;
232 static uint16_t l2cap_enhanced_mps_min;
233 static uint16_t l2cap_enhanced_mps_max;
234 static btstack_context_callback_registration_t l2cap_trigger_run_registration;
235 #endif
236 
237 // single list of channels for connection-oriented channels (basic, ertm, cbm, ecbf) Classic Connectionless, ATT, and SM
238 static btstack_linked_list_t l2cap_channels;
239 #ifdef L2CAP_USES_CHANNELS
240 // next channel id for new connections
241 static uint16_t  l2cap_local_source_cid;
242 #endif
243 // next signaling sequence number
244 static uint8_t   l2cap_sig_seq_nr;
245 
246 // used to cache l2cap rejects, echo, and informational requests
247 static l2cap_signaling_response_t l2cap_signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
248 static int l2cap_signaling_responses_pending;
249 static btstack_packet_callback_registration_t l2cap_hci_event_callback_registration;
250 
251 static bool l2cap_call_notify_channel_in_run;
252 
253 #ifdef ENABLE_BLE
254 // only used for connection parameter update events
255 static uint16_t l2cap_le_custom_max_mtu;
256 #endif
257 
258 /* callbacks for events */
259 static btstack_linked_list_t l2cap_event_handlers;
260 
261 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
262 
263 // enable for testing
264 // #define L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL 16
265 
266 /*
267  * CRC lookup table for generator polynom D^16 + D^15 + D^2 + 1
268  */
269 static const uint16_t crc16_table[256] = {
270     0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
271     0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841,
272     0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41,
273     0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040,
274     0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441,
275     0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840,
276     0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40,
277     0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041,
278     0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
279     0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840,
280     0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
281     0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041,
282     0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440,
283     0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841,
284     0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41,
285     0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040,
286 };
287 
288 static uint16_t crc16_calc(uint8_t * data, uint16_t len){
289     uint16_t crc = 0;   // initial value = 0
290     while (len--){
291         crc = (crc >> 8) ^ crc16_table[ (crc ^ ((uint16_t) *data++)) & 0x00FF ];
292     }
293     return crc;
294 }
295 
296 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){
297     return (((uint16_t) sar) << 14) | (req_seq << 8) | (final << 7) | (tx_seq << 1) | 0;
298 }
299 
300 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){
301     return (req_seq << 8) | (final << 7) | (poll << 4) | (((int) supervisory_function) << 2) | 1;
302 }
303 
304 static int l2cap_next_ertm_seq_nr(int seq_nr){
305     return (seq_nr + 1) & 0x3f;
306 }
307 
308 static bool l2cap_ertm_can_store_packet_now(l2cap_channel_t * channel){
309     // get num free tx buffers
310     int num_free_tx_buffers = channel->num_tx_buffers - channel->num_stored_tx_frames;
311     // calculate num tx buffers for remote MTU
312     int num_tx_buffers_for_max_remote_mtu;
313     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
314     if (channel->remote_mtu <= effective_mps){
315         // MTU fits into single packet
316         num_tx_buffers_for_max_remote_mtu = 1;
317     } else {
318         // include SDU Length
319         num_tx_buffers_for_max_remote_mtu = (channel->remote_mtu + 2 + (effective_mps - 1)) / effective_mps;
320     }
321     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);
322     return num_tx_buffers_for_max_remote_mtu <= num_free_tx_buffers;
323 }
324 
325 static void l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel_t * l2cap_channel){
326     log_info("Retransmit unacknowleged frames");
327     l2cap_channel->unacked_frames = 0;;
328     l2cap_channel->tx_send_index  = l2cap_channel->tx_read_index;
329 }
330 
331 static void l2cap_ertm_next_tx_write_index(l2cap_channel_t * channel){
332     channel->tx_write_index++;
333     if (channel->tx_write_index < channel->num_tx_buffers) return;
334     channel->tx_write_index = 0;
335 }
336 
337 static void l2cap_ertm_start_monitor_timer(l2cap_channel_t * channel){
338     log_info("Start Monitor timer");
339     btstack_run_loop_remove_timer(&channel->monitor_timer);
340     btstack_run_loop_set_timer_handler(&channel->monitor_timer, &l2cap_ertm_monitor_timeout_callback);
341     btstack_run_loop_set_timer_context(&channel->monitor_timer, channel);
342     btstack_run_loop_set_timer(&channel->monitor_timer, channel->local_monitor_timeout_ms);
343     btstack_run_loop_add_timer(&channel->monitor_timer);
344 }
345 
346 static void l2cap_ertm_stop_monitor_timer(l2cap_channel_t * channel){
347     log_info("Stop Monitor timer");
348     btstack_run_loop_remove_timer(&channel->monitor_timer);
349 }
350 
351 static void l2cap_ertm_start_retransmission_timer(l2cap_channel_t * channel){
352     log_info("Start Retransmission timer");
353     btstack_run_loop_remove_timer(&channel->retransmission_timer);
354     btstack_run_loop_set_timer_handler(&channel->retransmission_timer, &l2cap_ertm_retransmission_timeout_callback);
355     btstack_run_loop_set_timer_context(&channel->retransmission_timer, channel);
356     btstack_run_loop_set_timer(&channel->retransmission_timer, channel->local_retransmission_timeout_ms);
357     btstack_run_loop_add_timer(&channel->retransmission_timer);
358 }
359 
360 static void l2cap_ertm_stop_retransmission_timer(l2cap_channel_t * l2cap_channel){
361     log_info("Stop Retransmission timer");
362     btstack_run_loop_remove_timer(&l2cap_channel->retransmission_timer);
363 }
364 
365 static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts){
366     log_info("Monitor timeout");
367     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
368 
369     // TODO: we assume that it's the oldest packet
370     l2cap_ertm_tx_packet_state_t * tx_state;
371     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
372 
373     // check retry count
374     if (tx_state->retry_count < l2cap_channel->remote_max_transmit){
375         // increment retry count
376         tx_state->retry_count++;
377 
378         // start retransmit
379         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
380 
381         // start monitor timer
382         l2cap_ertm_start_monitor_timer(l2cap_channel);
383 
384         // send RR/P=1
385         l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
386     } else {
387         log_info("Monitor timer expired & retry count >= max transmit -> disconnect");
388         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
389     }
390     l2cap_run();
391 }
392 
393 static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts){
394     log_info("Retransmission timeout");
395     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
396 
397     // TODO: we assume that it's the oldest packet
398     l2cap_ertm_tx_packet_state_t * tx_state;
399     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
400 
401     // set retry count = 1
402     tx_state->retry_count = 1;
403 
404     // start retransmit
405     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
406 
407     // start monitor timer
408     l2cap_ertm_start_monitor_timer(l2cap_channel);
409 
410     // send RR/P=1
411     l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
412     l2cap_run();
413 }
414 
415 static int l2cap_ertm_send_information_frame(l2cap_channel_t * channel, int index, int final){
416     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
417     hci_reserve_packet_buffer();
418     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
419     uint16_t control = l2cap_encanced_control_field_for_information_frame(tx_state->tx_seq, final, channel->req_seq, tx_state->sar);
420     log_info("I-Frame: control 0x%04x", control);
421     little_endian_store_16(acl_buffer, 8, control);
422     (void)memcpy(&acl_buffer[8 + 2],
423                  &channel->tx_packets_data[index * channel->local_mps],
424                  tx_state->len);
425     // (re-)start retransmission timer on
426     l2cap_ertm_start_retransmission_timer(channel);
427     // send
428     return l2cap_send_prepared(channel->local_cid, 2 + tx_state->len);
429 }
430 
431 static void l2cap_ertm_store_fragment(l2cap_channel_t * channel, l2cap_segmentation_and_reassembly_t sar, uint16_t sdu_length, const uint8_t * data, uint16_t len){
432     // get next index for storing packets
433     int index = channel->tx_write_index;
434 
435     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
436     tx_state->tx_seq = channel->next_tx_seq;
437     tx_state->sar = sar;
438     tx_state->retry_count = 0;
439 
440     uint8_t * tx_packet = &channel->tx_packets_data[index * channel->local_mps];
441     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);
442     int pos = 0;
443     if (sar == L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU){
444         little_endian_store_16(tx_packet, 0, sdu_length);
445         pos += 2;
446     }
447     (void)memcpy(&tx_packet[pos], data, len);
448     tx_state->len = pos + len;
449 
450     // update
451     channel->num_stored_tx_frames++;
452     channel->next_tx_seq = l2cap_next_ertm_seq_nr(channel->next_tx_seq);
453     l2cap_ertm_next_tx_write_index(channel);
454 
455     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);
456 
457 }
458 
459 static uint8_t l2cap_ertm_send(l2cap_channel_t * channel, const uint8_t * data, uint16_t len){
460     if (len > channel->remote_mtu){
461         log_error("l2cap_ertm_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
462         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
463     }
464 
465     if (!l2cap_ertm_can_store_packet_now(channel)){
466         log_error("l2cap_ertm_send cid 0x%02x, fragment store full", channel->local_cid);
467         return BTSTACK_ACL_BUFFERS_FULL;
468     }
469 
470     // check if it needs to get fragmented
471     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
472     if (len > effective_mps){
473         // fragmentation needed.
474         l2cap_segmentation_and_reassembly_t sar =  L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU;
475         uint16_t chunk_len = 0;
476         while (len){
477             switch (sar){
478                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
479                     chunk_len = effective_mps - 2;    // sdu_length
480                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
481                     sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU;
482                     break;
483                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
484                     chunk_len = effective_mps;
485                     if (chunk_len >= len){
486                         sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU;
487                         chunk_len = len;
488                     }
489                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
490                     break;
491                 default:
492                     btstack_unreachable();
493                     break;
494             }
495             len  -= chunk_len;
496             data += chunk_len;
497         }
498 
499     } else {
500         l2cap_ertm_store_fragment(channel, L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU, 0, data, len);
501     }
502 
503     // try to send
504     l2cap_notify_channel_can_send();
505     return ERROR_CODE_SUCCESS;
506 }
507 
508 static uint16_t l2cap_setup_options_ertm_request(l2cap_channel_t * channel, uint8_t * config_options){
509     int pos = 0;
510     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
511     config_options[pos++] = 9;      // length
512     config_options[pos++] = (uint8_t) channel->mode;
513     config_options[pos++] = channel->num_rx_buffers;    // == TxWindows size
514     config_options[pos++] = channel->local_max_transmit;
515     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
516     pos += 2;
517     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
518     pos += 2;
519     little_endian_store_16( config_options, pos, channel->local_mps);
520     pos += 2;
521     //
522     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT;
523     config_options[pos++] = 2;     // length
524     little_endian_store_16(config_options, pos, channel->local_mtu);
525     pos += 2;
526 
527     // Issue: iOS (e.g. 10.2) uses "No FCS" as default while Core 5.0 specifies "FCS" as default
528     // Workaround: try to actively negotiate FCS option
529     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
530     config_options[pos++] = 1;     // length
531     config_options[pos++] = channel->fcs_option;
532     return pos; // 11+4+3=18
533 }
534 
535 static uint16_t l2cap_setup_options_ertm_response(l2cap_channel_t * channel, uint8_t * config_options){
536     int pos = 0;
537     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
538     config_options[pos++] = 9;      // length
539     config_options[pos++] = (uint8_t) channel->mode;
540     // less or equal to remote tx window size
541     config_options[pos++] = btstack_min(channel->num_tx_buffers, channel->remote_tx_window_size);
542     // max transmit in response shall be ignored -> use sender values
543     config_options[pos++] = channel->remote_max_transmit;
544     // A value for the Retransmission time-out shall be sent in a positive Configuration Response
545     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
546     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
547     pos += 2;
548     // A value for the Monitor time-out shall be sent in a positive Configuration Response
549     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
550     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
551     pos += 2;
552     // less or equal to remote mps
553     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
554     little_endian_store_16( config_options, pos, effective_mps);
555     pos += 2;
556     //
557     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
558     config_options[pos++] = 2;     // length
559     little_endian_store_16(config_options, pos, channel->remote_mtu);
560     pos += 2;
561 #if 0
562     //
563     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
564     config_options[pos++] = 1;     // length
565     config_options[pos++] = channel->fcs_option;
566 #endif
567     return pos; // 11+4=15
568 }
569 
570 static int l2cap_ertm_send_supervisor_frame(l2cap_channel_t * channel, uint16_t control){
571     hci_reserve_packet_buffer();
572     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
573     log_info("S-Frame: control 0x%04x", control);
574     little_endian_store_16(acl_buffer, 8, control);
575     return l2cap_send_prepared(channel->local_cid, 2);
576 }
577 
578 static uint8_t l2cap_ertm_validate_local_config(l2cap_ertm_config_t * ertm_config){
579 
580     uint8_t result = ERROR_CODE_SUCCESS;
581     if (ertm_config->max_transmit < 1){
582         log_error("max_transmit must be >= 1");
583         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
584     }
585     if (ertm_config->retransmission_timeout_ms < 2000){
586         log_error("retransmission_timeout_ms must be >= 2000 ms");
587         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
588     }
589     if (ertm_config->monitor_timeout_ms < 12000){
590         log_error("monitor_timeout_ms must be >= 12000 ms");
591         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
592     }
593     if (ertm_config->local_mtu < 48){
594         log_error("local_mtu must be >= 48");
595         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
596     }
597     if (ertm_config->num_rx_buffers < 1){
598         log_error("num_rx_buffers must be >= 1");
599         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
600     }
601     if (ertm_config->num_tx_buffers < 1){
602         log_error("num_rx_buffers must be >= 1");
603         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
604     }
605     return result;
606 }
607 
608 static void l2cap_ertm_setup_buffers(l2cap_channel_t * channel, uint8_t * buffer, uint32_t size){
609     btstack_assert( (((uintptr_t) buffer) & 0x0f) == 0);
610 
611     // setup state buffers - use void cast to avoid -Wcast-align warning
612     uint32_t pos = 0;
613     channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) (void *) &buffer[pos];
614     pos += channel->num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
615     channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) (void *) &buffer[pos];
616     pos += channel->num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
617 
618     // setup reassembly buffer
619     channel->reassembly_buffer = &buffer[pos];
620     pos += channel->local_mtu;
621 
622     // setup rx buffers
623     channel->rx_packets_data = &buffer[pos];
624     pos += channel->num_rx_buffers * channel->local_mps;
625 
626     // setup tx buffers
627     channel->tx_packets_data = &buffer[pos];
628     pos += channel->num_rx_buffers * channel->remote_mps;
629 
630     btstack_assert(pos <= size);
631     UNUSED(pos);
632 }
633 
634 static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
635 
636     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
637     channel->ertm_mandatory = ertm_config->ertm_mandatory;
638     channel->local_max_transmit = ertm_config->max_transmit;
639     channel->local_retransmission_timeout_ms = ertm_config->retransmission_timeout_ms;
640     channel->local_monitor_timeout_ms = ertm_config->monitor_timeout_ms;
641     channel->local_mtu = ertm_config->local_mtu;
642     channel->num_rx_buffers = ertm_config->num_rx_buffers;
643     channel->num_tx_buffers = ertm_config->num_tx_buffers;
644     channel->fcs_option = ertm_config->fcs_option;
645 
646     // align buffer to 16-byte boundary to assert l2cap_ertm_rx_packet_state_t is aligned
647     int bytes_till_alignment = 16 - (((uintptr_t) buffer) & 0x0f);
648     buffer += bytes_till_alignment;
649     size   -= bytes_till_alignment;
650 
651     // calculate space for rx and tx buffers
652     uint32_t state_len = channel->num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t) + channel->num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
653     uint32_t buffer_space = size - state_len - channel->local_mtu;
654 
655     // divide rest of data equally for initial config
656     uint16_t mps = buffer_space / (ertm_config->num_rx_buffers + ertm_config->num_tx_buffers);
657     channel->local_mps  = mps;
658     channel->remote_mps = mps;
659     l2cap_ertm_setup_buffers(channel, buffer, size);
660 
661     log_info("Local MPS: %u", channel->local_mps);
662 }
663 
664 uint8_t l2cap_ertm_create_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
665     l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
666 
667     log_info("l2cap_ertm_create_channel addr %s, psm 0x%x, local mtu %u", bd_addr_to_str(address), psm, ertm_config->local_mtu);
668 
669     // validate local config
670     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
671     if (result) return result;
672 
673     // determine security level based on psm
674     const gap_security_level_t security_level = l2cap_security_level_0_allowed_for_PSM(psm) ? LEVEL_0 : gap_get_security_level();
675 
676     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, address, BD_ADDR_TYPE_ACL, psm, ertm_config->local_mtu, security_level);
677     if (!channel) {
678         return BTSTACK_MEMORY_ALLOC_FAILED;
679     }
680 
681     // configure ERTM
682     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
683 
684     // add to connections list
685     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
686 
687     // store local_cid
688     if (out_local_cid){
689        *out_local_cid = channel->local_cid;
690     }
691 
692     // check if hci connection is already usable
693     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
694     if (conn){
695         log_info("l2cap_create_channel, hci connection already exists");
696         l2cap_handle_connection_complete(conn->con_handle, channel);
697         // check if remote supported fearures are already received
698         if (hci_remote_features_available(conn->con_handle)) {
699             l2cap_handle_remote_supported_features_received(channel);
700         } else {
701             hci_remote_features_query(conn->con_handle);
702         };
703     }
704 
705     l2cap_run();
706 
707     return 0;
708 }
709 
710 static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel){
711     if (l2cap_ertm_can_store_packet_now(channel)){
712         channel->waiting_for_can_send_now = 0;
713         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
714     }
715 }
716 
717 uint8_t l2cap_ertm_accept_connection(uint16_t local_cid, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
718 
719     log_info("l2cap_ertm_accept_connection local_cid 0x%x", local_cid);
720     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
721     if (!channel) {
722         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
723         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
724     }
725 
726     // validate local config
727     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
728     if (result) return result;
729 
730     // configure L2CAP ERTM
731     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
732 
733     // we need to know if ERTM is supported before sending a config response
734     channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
735     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
736     btstack_assert(connection != NULL);
737     switch (connection->l2cap_state.information_state){
738         case L2CAP_INFORMATION_STATE_IDLE:
739             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
740             break;
741         case L2CAP_INFORMATION_STATE_DONE:
742             l2cap_handle_information_request_complete(connection);
743             break;
744         default:
745             break;
746     }
747 
748     l2cap_run();
749 
750     return ERROR_CODE_SUCCESS;
751 }
752 
753 uint8_t l2cap_ertm_decline_connection(uint16_t local_cid){
754     l2cap_decline_connection(local_cid);
755     return ERROR_CODE_SUCCESS;
756 }
757 
758 uint8_t l2cap_ertm_set_busy(uint16_t local_cid){
759     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
760     if (!channel) {
761         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
762         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
763     }
764     if (!channel->local_busy){
765         channel->local_busy = 1;
766         channel->send_supervisor_frame_receiver_not_ready = 1;
767         l2cap_run();
768     }
769     return ERROR_CODE_SUCCESS;
770 }
771 
772 uint8_t l2cap_ertm_set_ready(uint16_t local_cid){
773     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
774     if (!channel) {
775         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
776         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
777     }
778     if (channel->local_busy){
779         channel->local_busy = 0;
780         channel->send_supervisor_frame_receiver_ready_poll = 1;
781         l2cap_run();
782     }
783     return ERROR_CODE_SUCCESS;
784 }
785 
786 // Process-ReqSeq
787 static void l2cap_ertm_process_req_seq(l2cap_channel_t * l2cap_channel, uint8_t req_seq){
788     int num_buffers_acked = 0;
789     l2cap_ertm_tx_packet_state_t * tx_state;
790     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);
791     while (true){
792 
793         // no unack packets left
794         if (l2cap_channel->unacked_frames == 0) {
795             // stop retransmission timer
796             l2cap_ertm_stop_retransmission_timer(l2cap_channel);
797             break;
798         }
799 
800         tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
801         // calc delta
802         int delta = (req_seq - tx_state->tx_seq) & 0x03f;
803         if (delta == 0) break;  // all packets acknowledged
804         if (delta > l2cap_channel->remote_tx_window_size) break;
805 
806         num_buffers_acked++;
807         l2cap_channel->num_stored_tx_frames--;
808         l2cap_channel->unacked_frames--;
809         log_info("RR seq %u => packet with tx_seq %u done", req_seq, tx_state->tx_seq);
810 
811         l2cap_channel->tx_read_index++;
812         if (l2cap_channel->tx_read_index >= l2cap_channel->num_rx_buffers){
813             l2cap_channel->tx_read_index = 0;
814         }
815     }
816     if (num_buffers_acked){
817         log_info("num_buffers_acked %u", num_buffers_acked);
818     l2cap_ertm_notify_channel_can_send(l2cap_channel);
819 }
820 }
821 
822 static l2cap_ertm_tx_packet_state_t * l2cap_ertm_get_tx_state(l2cap_channel_t * l2cap_channel, uint8_t tx_seq){
823     int i;
824     for (i=0;i<l2cap_channel->num_tx_buffers;i++){
825         l2cap_ertm_tx_packet_state_t * tx_state = &l2cap_channel->tx_packets_state[i];
826         if (tx_state->tx_seq == tx_seq) return tx_state;
827     }
828     return NULL;
829 }
830 
831 // @param delta number of frames in the future, >= 1
832 // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
833 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){
834     log_info("Store SDU with delta %u", delta);
835     // get rx state for packet to store
836     int index = l2cap_channel->rx_store_index + delta - 1;
837     if (index > l2cap_channel->num_rx_buffers){
838         index -= l2cap_channel->num_rx_buffers;
839     }
840     log_info("Index of packet to store %u", index);
841     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
842     // check if buffer is free
843     if (rx_state->valid){
844         log_error("Packet buffer already used");
845         return;
846     }
847     rx_state->valid = 1;
848     rx_state->sar = sar;
849     rx_state->len = size;
850     uint8_t * rx_buffer = &l2cap_channel->rx_packets_data[index];
851     (void)memcpy(rx_buffer, payload, size);
852 }
853 
854 // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
855 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){
856     uint16_t reassembly_sdu_length;
857     switch (sar){
858         case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
859             // assert total packet size <= our mtu
860             if (size > l2cap_channel->local_mtu) break;
861             // packet complete -> disapatch
862             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, (uint8_t*) payload, size);
863             break;
864         case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
865             // read SDU len
866             reassembly_sdu_length = little_endian_read_16(payload, 0);
867             payload += 2;
868             size    -= 2;
869             // assert reassembled size <= our mtu
870             if (reassembly_sdu_length > l2cap_channel->local_mtu) break;
871             // store start segment
872             l2cap_channel->reassembly_sdu_length = reassembly_sdu_length;
873             (void)memcpy(&l2cap_channel->reassembly_buffer[0], payload, size);
874             l2cap_channel->reassembly_pos = size;
875             break;
876         case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
877             // assert size of reassembled data <= our mtu
878             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
879             // store continuation segment
880             (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
881                          payload, size);
882             l2cap_channel->reassembly_pos += size;
883             break;
884         case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
885             // assert size of reassembled data <= our mtu
886             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
887             // store continuation segment
888             (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
889                          payload, size);
890             l2cap_channel->reassembly_pos += size;
891             // assert size of reassembled data matches announced sdu length
892             if (l2cap_channel->reassembly_pos != l2cap_channel->reassembly_sdu_length) break;
893             // packet complete -> disapatch
894             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->reassembly_buffer, l2cap_channel->reassembly_pos);
895             l2cap_channel->reassembly_pos = 0;
896             break;
897         default:
898             btstack_assert(false);
899             break;
900     }
901 }
902 
903 static void l2cap_ertm_channel_send_information_frame(l2cap_channel_t * channel){
904     channel->unacked_frames++;
905     int index = channel->tx_send_index;
906     channel->tx_send_index++;
907     if (channel->tx_send_index >= channel->num_tx_buffers){
908         channel->tx_send_index = 0;
909     }
910     l2cap_ertm_send_information_frame(channel, index, 0);   // final = 0
911 }
912 
913 #endif
914 
915 #ifdef L2CAP_USES_CHANNELS
916 static uint16_t l2cap_next_local_cid(void){
917     do {
918         if (l2cap_local_source_cid == 0xfffeu) {
919             l2cap_local_source_cid = 0x40;
920         } else {
921             l2cap_local_source_cid++;
922         }
923     } while (l2cap_get_channel_for_local_cid(l2cap_local_source_cid) != NULL);
924     return l2cap_local_source_cid;
925 }
926 #endif
927 
928 static uint8_t l2cap_next_sig_id(void){
929     if (l2cap_sig_seq_nr == 0xffu) {
930         l2cap_sig_seq_nr = 1;
931     } else {
932         l2cap_sig_seq_nr++;
933     }
934     return l2cap_sig_seq_nr;
935 }
936 
937 void l2cap_init(void){
938 #ifdef L2CAP_USES_CHANNELS
939     l2cap_local_source_cid  = 0x40;
940 #endif
941     l2cap_sig_seq_nr  = 0xff;
942 
943 #ifdef ENABLE_CLASSIC
944     // Setup Connectionless Channel
945     l2cap_fixed_channel_classic_connectionless.local_cid     = L2CAP_CID_CONNECTIONLESS_CHANNEL;
946     l2cap_fixed_channel_classic_connectionless.channel_type  = L2CAP_CHANNEL_TYPE_CONNECTIONLESS;
947     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_classic_connectionless);
948 #endif
949 
950 #ifdef ENABLE_BLE
951     // Setup fixed ATT Channel
952     l2cap_fixed_channel_le_att.local_cid    = L2CAP_CID_ATTRIBUTE_PROTOCOL;
953     l2cap_fixed_channel_le_att.channel_type = L2CAP_CHANNEL_TYPE_FIXED_LE;
954     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_le_att);
955 
956     // Setup fixed SM Channel
957     l2cap_fixed_channel_le_sm.local_cid     = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
958     l2cap_fixed_channel_le_sm.channel_type  = L2CAP_CHANNEL_TYPE_FIXED_LE;
959     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_le_sm);
960 #endif
961 #ifdef ENABLE_CLASSIC
962     // Setup fixed SM Channel
963     l2cap_fixed_channel_classic_sm.local_cid     = L2CAP_CID_BR_EDR_SECURITY_MANAGER;
964     l2cap_fixed_channel_classic_sm.channel_type  = L2CAP_CHANNEL_TYPE_FIXED_CLASSIC;
965     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_classic_sm);
966 #endif
967 
968 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
969     l2cap_enhanced_mps_min = 0x0001;
970     l2cap_enhanced_mps_max = 0xffff;
971     l2cap_trigger_run_registration.callback = &l2cap_run_trigger_callback;
972 #endif
973 
974     //
975     // register callback with HCI
976     //
977     l2cap_hci_event_callback_registration.callback = &l2cap_hci_event_handler;
978     hci_add_event_handler(&l2cap_hci_event_callback_registration);
979 
980     hci_register_acl_packet_handler(&l2cap_acl_handler);
981 
982 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
983 #ifdef ENABLE_CLASSIC
984     gap_connectable_control(0); // no services yet
985 #endif
986 #endif
987 }
988 
989 /**
990  * @brief De-Init L2CAP
991  */
992 void l2cap_deinit(void){
993     l2cap_channels = NULL;
994     l2cap_signaling_responses_pending = 0;
995 #ifdef ENABLE_CLASSIC
996     l2cap_require_security_level2_for_outgoing_sdp = 0;
997     (void)memset(&l2cap_fixed_channel_classic_connectionless, 0, sizeof(l2cap_fixed_channel_classic_connectionless));
998     l2cap_services = NULL;
999     (void)memset(l2cap_outgoing_classic_addr, 0, 6);
1000     (void)memset(&l2cap_fixed_channel_classic_sm, 0, sizeof(l2cap_fixed_channel_classic_sm));
1001 #endif
1002 #ifdef ENABLE_BLE
1003     l2cap_le_custom_max_mtu = 0;
1004     (void)memset(&l2cap_fixed_channel_le_att, 0, sizeof(l2cap_fixed_channel_le_att));
1005     (void)memset(&l2cap_fixed_channel_le_sm, 0, sizeof(l2cap_fixed_channel_le_sm));
1006 #endif
1007 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
1008     l2cap_le_services = NULL;
1009 #endif
1010 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1011     l2cap_enhanced_services = NULL;
1012 #endif
1013     l2cap_event_handlers = NULL;
1014 }
1015 
1016 void l2cap_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
1017     btstack_linked_list_add_tail(&l2cap_event_handlers, (btstack_linked_item_t*) callback_handler);
1018 }
1019 
1020 void l2cap_remove_event_handler(btstack_packet_callback_registration_t * callback_handler){
1021     btstack_linked_list_remove(&l2cap_event_handlers, (btstack_linked_item_t*) callback_handler);
1022 }
1023 
1024 static void l2cap_emit_event(uint8_t *event, uint16_t size) {
1025     hci_dump_packet( HCI_EVENT_PACKET, 1, event, size);
1026     // dispatch to all event handlers
1027     btstack_linked_list_iterator_t it;
1028     btstack_linked_list_iterator_init(&it, &l2cap_event_handlers);
1029     while (btstack_linked_list_iterator_has_next(&it)){
1030         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
1031         entry->callback(HCI_EVENT_PACKET, 0, event, size);
1032     }
1033 }
1034 
1035 void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
1036     UNUSED(con_handle);  // ok: there is no con handle
1037 
1038     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
1039     if (!channel) return;
1040     channel->waiting_for_can_send_now = 1;
1041     l2cap_notify_channel_can_send();
1042 }
1043 
1044 bool l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
1045     UNUSED(channel_id); // ok: only depends on Controller LE buffers
1046 
1047     return hci_can_send_acl_packet_now(con_handle);
1048 }
1049 
1050 uint8_t *l2cap_get_outgoing_buffer(void){
1051     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
1052 }
1053 
1054 // only for L2CAP Basic Channels
1055 bool l2cap_reserve_packet_buffer(void){
1056     return hci_reserve_packet_buffer();
1057 }
1058 
1059 // only for L2CAP Basic Channels
1060 void l2cap_release_packet_buffer(void){
1061     hci_release_packet_buffer();
1062 }
1063 
1064 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){
1065     // 0 - Connection handle : PB=pb : BC=00
1066     little_endian_store_16(acl_buffer, 0u, con_handle | (packet_boundary << 12u) | (0u << 14u));
1067     // 2 - ACL length
1068     little_endian_store_16(acl_buffer, 2u,  len + 4u);
1069     // 4 - L2CAP packet length
1070     little_endian_store_16(acl_buffer, 4u,  len + 0u);
1071     // 6 - L2CAP channel DEST
1072     little_endian_store_16(acl_buffer, 6,  remote_cid);
1073 }
1074 
1075 // assumption - only on LE connections
1076 uint8_t l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
1077 
1078     if (!hci_is_packet_buffer_reserved()){
1079         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
1080         return BTSTACK_ACL_BUFFERS_FULL;
1081     }
1082 
1083     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
1084         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
1085         return BTSTACK_ACL_BUFFERS_FULL;
1086     }
1087 
1088     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
1089 
1090     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1091     l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
1092     // send
1093     return hci_send_acl_packet_buffer(len+8u);
1094 }
1095 
1096 // assumption - only on LE connections
1097 uint8_t l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
1098 
1099     if (!hci_can_send_acl_packet_now(con_handle)){
1100         log_info("l2cap_send cid 0x%02x, cannot send", cid);
1101         return BTSTACK_ACL_BUFFERS_FULL;
1102     }
1103 
1104     hci_reserve_packet_buffer();
1105     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1106 
1107     (void)memcpy(&acl_buffer[8], data, len);
1108 
1109     return l2cap_send_prepared_connectionless(con_handle, cid, len);
1110 }
1111 
1112 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
1113     log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
1114     uint8_t event[4];
1115     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
1116     event[1] = sizeof(event) - 2u;
1117     little_endian_store_16(event, 2, channel);
1118     hci_dump_packet( HCI_EVENT_PACKET, 1, event, sizeof(event));
1119     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
1120 }
1121 
1122 #ifdef L2CAP_USES_CHANNELS
1123 static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
1124     (* (channel->packet_handler))(type, channel->local_cid, data, size);
1125 }
1126 
1127 static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
1128     uint8_t event[4];
1129     event[0] = event_code;
1130     event[1] = sizeof(event) - 2u;
1131     little_endian_store_16(event, 2, channel->local_cid);
1132     hci_dump_packet( HCI_EVENT_PACKET, 1, event, sizeof(event));
1133     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1134 }
1135 #endif
1136 
1137 #ifdef ENABLE_CLASSIC
1138 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
1139     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",
1140              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
1141              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
1142     uint8_t event[26];
1143     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
1144     event[1] = sizeof(event) - 2;
1145     event[2] = status;
1146     reverse_bd_addr(channel->address, &event[3]);
1147     little_endian_store_16(event,  9, channel->con_handle);
1148     little_endian_store_16(event, 11, channel->psm);
1149     little_endian_store_16(event, 13, channel->local_cid);
1150     little_endian_store_16(event, 15, channel->remote_cid);
1151     little_endian_store_16(event, 17, channel->local_mtu);
1152     little_endian_store_16(event, 19, channel->remote_mtu);
1153     little_endian_store_16(event, 21, channel->flush_timeout);
1154     event[23] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
1155 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1156     log_info("ERTM mode %u, fcs enabled %u", channel->mode, channel->fcs_option);
1157     event[24] = channel->mode;
1158     event[25] = channel->fcs_option;
1159 
1160 #else
1161     event[24] = L2CAP_CHANNEL_MODE_BASIC;
1162     event[25] = 0;
1163 #endif
1164     hci_dump_packet( HCI_EVENT_PACKET, 1, event, sizeof(event));
1165     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1166 }
1167 
1168 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
1169     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
1170              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
1171     uint8_t event[16];
1172     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
1173     event[1] = sizeof(event) - 2;
1174     reverse_bd_addr(channel->address, &event[2]);
1175     little_endian_store_16(event,  8, channel->con_handle);
1176     little_endian_store_16(event, 10, channel->psm);
1177     little_endian_store_16(event, 12, channel->local_cid);
1178     little_endian_store_16(event, 14, channel->remote_cid);
1179     hci_dump_packet( HCI_EVENT_PACKET, 1, event, sizeof(event));
1180     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1181 }
1182 
1183 static void l2cap_handle_channel_open_failed(l2cap_channel_t * channel, uint8_t status){
1184 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1185     // emit ertm buffer released, as it's not needed. if in basic mode, it was either not allocated or already released
1186     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1187         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1188     }
1189 #endif
1190     l2cap_emit_channel_opened(channel, status);
1191 }
1192 
1193 #endif
1194 
1195 #ifdef L2CAP_USES_CHANNELS
1196 
1197 static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
1198     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
1199     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
1200 }
1201 
1202 static void l2cap_handle_channel_closed(l2cap_channel_t * channel){
1203 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1204     // emit ertm buffer released, as it's not needed anymore. if in basic mode, it was either not allocated or already released
1205     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1206         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1207     }
1208 #endif
1209     l2cap_emit_channel_closed(channel);
1210 }
1211 #endif
1212 
1213 static l2cap_fixed_channel_t * l2cap_channel_item_by_cid(uint16_t cid){
1214     btstack_linked_list_iterator_t it;
1215     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1216     while (btstack_linked_list_iterator_has_next(&it)){
1217         l2cap_fixed_channel_t * channel = (l2cap_fixed_channel_t*) btstack_linked_list_iterator_next(&it);
1218         if (channel->local_cid == cid) {
1219             return channel;
1220         }
1221     }
1222     return NULL;
1223 }
1224 
1225 // used for fixed channels in LE (ATT/SM) and Classic (Connectionless Channel). CID < 0x04
1226 static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid){
1227     if (local_cid >= 0x40u) return NULL;
1228     return (l2cap_fixed_channel_t*) l2cap_channel_item_by_cid(local_cid);
1229 }
1230 
1231 #ifdef L2CAP_USES_CHANNELS
1232 
1233 static int l2cap_is_dynamic_channel_type(l2cap_channel_type_t channel_type) {
1234     switch (channel_type) {
1235         case L2CAP_CHANNEL_TYPE_CLASSIC:
1236         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
1237         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
1238             return 1;
1239         default:
1240             return 0;
1241     }
1242 }
1243 
1244 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
1245     if (local_cid < 0x40u) return NULL;
1246     return (l2cap_channel_t*) l2cap_channel_item_by_cid(local_cid);
1247 }
1248 
1249 static l2cap_channel_t * l2cap_get_channel_for_local_cid_and_handle(uint16_t local_cid, hci_con_handle_t con_handle){
1250     if (local_cid < 0x40u) return NULL;
1251     l2cap_channel_t * l2cap_channel = (l2cap_channel_t*) l2cap_channel_item_by_cid(local_cid);
1252     if (l2cap_channel == NULL)  return NULL;
1253     if (l2cap_channel->con_handle != con_handle) return NULL;
1254     return l2cap_channel;
1255 }
1256 #endif
1257 
1258 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
1259 static l2cap_channel_t * l2cap_get_channel_for_remote_handle_and_cid(hci_con_handle_t con_handle, uint16_t remote_cid){
1260     btstack_linked_list_iterator_t it;
1261     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1262     while (btstack_linked_list_iterator_has_next(&it)){
1263         l2cap_fixed_channel_t * channel = (l2cap_fixed_channel_t*) btstack_linked_list_iterator_next(&it);
1264         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
1265         l2cap_channel_t * dynamic_channel = (l2cap_channel_t *) channel;
1266         if (dynamic_channel->con_handle != con_handle) continue;
1267         if (dynamic_channel->remote_cid != remote_cid) continue;
1268         return dynamic_channel;
1269     }
1270     return NULL;
1271 }
1272 #endif
1273 
1274 #ifdef L2CAP_USES_CHANNELS
1275 uint8_t l2cap_request_can_send_now_event(uint16_t local_cid){
1276     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1277     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
1278     channel->waiting_for_can_send_now = 1;
1279     switch (channel->channel_type){
1280         case L2CAP_CHANNEL_TYPE_CLASSIC:
1281 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1282             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1283                 l2cap_ertm_notify_channel_can_send(channel);
1284                 return ERROR_CODE_SUCCESS;
1285             }
1286 #endif
1287             l2cap_notify_channel_can_send();
1288             break;
1289 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
1290         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
1291             l2cap_credit_based_notify_channel_can_send(channel);
1292             break;
1293 #endif
1294 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1295         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
1296             l2cap_credit_based_notify_channel_can_send(channel);
1297             break;
1298 #endif
1299         default:
1300             break;
1301     }
1302     return ERROR_CODE_SUCCESS;
1303 }
1304 
1305 bool l2cap_can_send_packet_now(uint16_t local_cid){
1306     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1307     if (!channel) return false;
1308     if (channel->state != L2CAP_STATE_OPEN) return false;
1309     switch (channel->channel_type){
1310         case L2CAP_CHANNEL_TYPE_CLASSIC:
1311 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1312             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1313                 return l2cap_ertm_can_store_packet_now(channel);
1314             }
1315 #endif
1316             return hci_can_send_acl_packet_now(channel->con_handle);
1317 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
1318         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
1319             return channel->send_sdu_buffer == NULL;
1320 #endif
1321 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1322         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
1323             return channel->send_sdu_buffer == NULL;
1324 #endif
1325         default:
1326             return false;
1327     }
1328 }
1329 
1330 uint8_t l2cap_send(uint16_t local_cid, const uint8_t *data, uint16_t len){
1331     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1332     if (!channel) {
1333         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
1334         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
1335     }
1336     switch (channel->channel_type){
1337 #ifdef ENABLE_CLASSIC
1338         case L2CAP_CHANNEL_TYPE_CLASSIC:
1339             return l2cap_classic_send(channel, data, len);
1340 #endif
1341 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
1342         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
1343             return l2cap_credit_based_send_data(channel, data, len);
1344 #endif
1345 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1346         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
1347             return l2cap_credit_based_send_data(channel, data, len);
1348 #endif
1349         default:
1350             return ERROR_CODE_UNSPECIFIED_ERROR;
1351     }
1352 }
1353 #endif
1354 
1355 #ifdef ENABLE_CLASSIC
1356 bool l2cap_can_send_prepared_packet_now(uint16_t local_cid){
1357     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1358     if (!channel) return false;
1359 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1360     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1361         return false;
1362     }
1363 #endif
1364     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
1365 }
1366 
1367 #endif
1368 
1369 #ifdef L2CAP_USES_CHANNELS
1370 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
1371     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1372     if (channel) {
1373         return channel->remote_mtu;
1374     }
1375     return 0;
1376 }
1377 #endif
1378 
1379 #ifdef ENABLE_CLASSIC
1380 // RTX Timer only exist for dynamic channels
1381 static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
1382     btstack_linked_list_iterator_t it;
1383     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1384     while (btstack_linked_list_iterator_has_next(&it)){
1385         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1386         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
1387         if (&channel->rtx == ts) {
1388             return channel;
1389         }
1390     }
1391     return NULL;
1392 }
1393 
1394 static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
1395     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
1396     if (!channel) return;
1397 
1398     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
1399 
1400     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
1401     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
1402     // notify client
1403     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
1404 
1405     // discard channel
1406     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1407     l2cap_free_channel_entry(channel);
1408 }
1409 
1410 static uint8_t l2cap_classic_packet_boundary_flag(void){
1411     return (hci_non_flushable_packet_boundary_flag_supported() && (hci_automatic_flush_timeout() == 0)) ? 0x00 : 0x02;
1412 }
1413 #endif
1414 
1415 #ifdef L2CAP_USES_CHANNELS
1416 static void l2cap_stop_rtx(l2cap_channel_t * channel){
1417     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
1418     btstack_run_loop_remove_timer(&channel->rtx);
1419 }
1420 #endif
1421 
1422 static uint8_t l2cap_send_signaling_packet(hci_con_handle_t handle, uint8_t pb_flags, uint16_t cid, L2CAP_SIGNALING_COMMANDS cmd, int identifier, va_list argptr){
1423     if (!hci_can_send_acl_packet_now(handle)){
1424         log_info("l2cap_send_classic_signaling_packet, cannot send");
1425         return BTSTACK_ACL_BUFFERS_FULL;
1426     }
1427     hci_reserve_packet_buffer();
1428     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1429     uint16_t len = l2cap_create_signaling_packet(acl_buffer, handle, pb_flags, cid, cmd, identifier, argptr);
1430     va_end(argptr);
1431     return hci_send_acl_packet_buffer(len);
1432 }
1433 
1434 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
1435 static int l2cap_send_general_signaling_packet(hci_con_handle_t handle, uint16_t signaling_cid, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1436     va_list argptr;
1437     va_start(argptr, identifier);
1438     uint8_t pb_flags = 0x00;
1439 #ifdef ENABLE_CLASSIC
1440     if (signaling_cid == L2CAP_CID_SIGNALING){
1441         pb_flags = l2cap_classic_packet_boundary_flag();
1442     }
1443 #endif
1444 uint8_t result = l2cap_send_signaling_packet(handle, pb_flags, signaling_cid, cmd, identifier, argptr);
1445     va_end(argptr);
1446     return result;
1447 }
1448 #endif
1449 
1450 #ifdef ENABLE_CLASSIC
1451 
1452 static void l2cap_start_rtx(l2cap_channel_t * channel){
1453     l2cap_stop_rtx(channel);
1454     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
1455     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1456     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
1457     btstack_run_loop_add_timer(&channel->rtx);
1458 }
1459 
1460 static void l2cap_start_ertx(l2cap_channel_t * channel){
1461     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
1462     l2cap_stop_rtx(channel);
1463     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1464     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
1465     btstack_run_loop_add_timer(&channel->rtx);
1466 }
1467 
1468 void l2cap_require_security_level_2_for_outgoing_sdp(void){
1469     l2cap_require_security_level2_for_outgoing_sdp = 1;
1470 }
1471 
1472 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
1473     return (psm == BLUETOOTH_PSM_SDP) && (!l2cap_require_security_level2_for_outgoing_sdp);
1474 }
1475 
1476 static int l2cap_send_classic_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1477     va_list argptr;
1478     va_start(argptr, identifier);
1479     uint8_t pb_flag = l2cap_classic_packet_boundary_flag();
1480     uint8_t result = l2cap_send_signaling_packet(handle, pb_flag, L2CAP_CID_SIGNALING, cmd, identifier, argptr);
1481     va_end(argptr);
1482     return result;
1483 }
1484 
1485 // assumption - only on Classic connections
1486 // cannot be used for L2CAP ERTM
1487 uint8_t l2cap_send_prepared(uint16_t local_cid, uint16_t len){
1488 
1489     if (!hci_is_packet_buffer_reserved()){
1490         log_error("l2cap_send_prepared called without reserving packet first");
1491         return BTSTACK_ACL_BUFFERS_FULL;
1492     }
1493 
1494     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1495     if (!channel) {
1496         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
1497         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
1498     }
1499 
1500     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
1501         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
1502         return BTSTACK_ACL_BUFFERS_FULL;
1503     }
1504 
1505     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
1506 
1507     int fcs_size = 0;
1508 
1509 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1510     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->fcs_option){
1511         fcs_size = 2;
1512     }
1513 #endif
1514 
1515     // set non-flushable packet boundary flag if supported on Controller
1516     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1517     uint8_t packet_boundary_flag = l2cap_classic_packet_boundary_flag();
1518     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
1519 
1520 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1521     if (fcs_size){
1522         // calculate FCS over l2cap data
1523         uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
1524         log_info("I-Frame: fcs 0x%04x", fcs);
1525         little_endian_store_16(acl_buffer, 8 + len, fcs);
1526     }
1527 #endif
1528 
1529     // send
1530     return hci_send_acl_packet_buffer(len+8+fcs_size);
1531 }
1532 
1533 // assumption - only on Classic connections
1534 static uint8_t l2cap_classic_send(l2cap_channel_t * channel, const uint8_t *data, uint16_t len){
1535 
1536 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1537     // send in ERTM
1538     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1539         return l2cap_ertm_send(channel, data, len);
1540     }
1541 #endif
1542 
1543     if (len > channel->remote_mtu){
1544         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
1545         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
1546     }
1547 
1548     if (!hci_can_send_acl_packet_now(channel->con_handle)){
1549         log_info("l2cap_send cid 0x%02x, cannot send", channel->local_cid);
1550         return BTSTACK_ACL_BUFFERS_FULL;
1551     }
1552 
1553     hci_reserve_packet_buffer();
1554     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1555     (void)memcpy(&acl_buffer[8], data, len);
1556     return l2cap_send_prepared(channel->local_cid, len);
1557 }
1558 
1559 int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
1560     return l2cap_send_classic_signaling_packet(con_handle, ECHO_REQUEST, l2cap_next_sig_id(), len, data);
1561 }
1562 
1563 static inline void channelStateVarSetFlag(l2cap_channel_t *channel, uint16_t flag){
1564     channel->state_var = channel->state_var | flag;
1565 }
1566 
1567 static inline void channelStateVarClearFlag(l2cap_channel_t *channel, uint16_t flag){
1568     channel->state_var = channel->state_var & ~flag;
1569 }
1570 #endif
1571 
1572 
1573 #ifdef ENABLE_BLE
1574 static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1575     va_list argptr;
1576     va_start(argptr, identifier);
1577     uint8_t pb_flags = 0x00;  // First non-automatically-flushable packet of a higher layer message
1578     uint8_t result = l2cap_send_signaling_packet(handle, pb_flags, L2CAP_CID_SIGNALING_LE, cmd, identifier, argptr);
1579     va_end(argptr);
1580     return result;
1581 }
1582 #endif
1583 
1584 uint16_t l2cap_max_mtu(void){
1585     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
1586 }
1587 
1588 #ifdef ENABLE_BLE
1589 uint16_t l2cap_max_le_mtu(void){
1590     if (l2cap_le_custom_max_mtu != 0u) return l2cap_le_custom_max_mtu;
1591     return l2cap_max_mtu();
1592 }
1593 
1594 void l2cap_set_max_le_mtu(uint16_t max_mtu){
1595     if (max_mtu < l2cap_max_mtu()){
1596         l2cap_le_custom_max_mtu = max_mtu;
1597     }
1598 }
1599 #endif
1600 
1601 #ifdef ENABLE_CLASSIC
1602 
1603 static uint16_t l2cap_setup_options_mtu(uint8_t * config_options, uint16_t mtu){
1604     config_options[0] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
1605     config_options[1] = 2; // len param
1606     little_endian_store_16(config_options, 2, mtu);
1607     return 4;
1608 }
1609 
1610 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1611 static int l2cap_ertm_mode(l2cap_channel_t * channel){
1612     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
1613     return ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE)
1614         &&  (connection->l2cap_state.extended_feature_mask & 0x08));
1615 }
1616 #endif
1617 
1618 static uint16_t l2cap_setup_options_request(l2cap_channel_t * channel, uint8_t * config_options){
1619 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1620     // use ERTM options if supported by remote and channel ready to use it
1621     if (l2cap_ertm_mode(channel) && channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1622         return l2cap_setup_options_ertm_request(channel, config_options);
1623     }
1624 #endif
1625     uint16_t mtu = channel->local_mtu;
1626     return l2cap_setup_options_mtu(config_options, mtu);
1627 }
1628 
1629 static uint16_t l2cap_setup_options_mtu_response(l2cap_channel_t * channel, uint8_t * config_options){
1630     uint16_t mtu = btstack_min(channel->local_mtu, channel->remote_mtu);
1631     return l2cap_setup_options_mtu(config_options, mtu);
1632 }
1633 
1634 static uint32_t l2cap_extended_features_mask(void){
1635     // extended features request supported, features: fixed channels, unicast connectionless data reception
1636     uint32_t features = 0x280;
1637 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1638     features |= 0x0028;
1639 #endif
1640     return features;
1641 }
1642 #endif
1643 
1644 //
1645 #ifdef ENABLE_CLASSIC
1646 
1647 // returns true if channel was finalized
1648 static bool l2cap_run_for_classic_channel(l2cap_channel_t * channel){
1649 
1650 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1651     uint8_t  config_options[18];
1652 #else
1653     uint8_t  config_options[10];
1654 #endif
1655 
1656     switch (channel->state){
1657 
1658         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1659         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
1660             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1661             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
1662                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
1663                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONN_RESP_PEND);
1664                 l2cap_send_classic_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id,
1665                                                     channel->local_cid, channel->remote_cid, 1, 0);
1666             }
1667             break;
1668 
1669         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1670             if (!hci_can_send_command_packet_now()) break;
1671             // send connection request - set state first
1672             channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
1673             // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
1674             (void)memcpy(l2cap_outgoing_classic_addr, channel->address, 6);
1675             hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_get_allow_role_switch());
1676             break;
1677 
1678         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
1679             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1680             channel->state = L2CAP_STATE_INVALID;
1681             l2cap_send_classic_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id,
1682                                                 channel->local_cid, channel->remote_cid, channel->reason, 0);
1683             // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1684             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1685             l2cap_free_channel_entry(channel);
1686             channel = NULL;
1687             break;
1688 
1689         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
1690             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1691             channel->state = L2CAP_STATE_CONFIG;
1692             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1693             l2cap_send_classic_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id,
1694                                                 channel->local_cid, channel->remote_cid, 0, 0);
1695             break;
1696 
1697         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
1698             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1699             // success, start l2cap handshake
1700             channel->local_sig_id = l2cap_next_sig_id();
1701             channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
1702             l2cap_send_classic_signaling_packet(channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id,
1703                                                 channel->psm, channel->local_cid);
1704             l2cap_start_rtx(channel);
1705             break;
1706 
1707         case L2CAP_STATE_CONFIG:
1708             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1709 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1710             // fallback to basic mode if ERTM requested but not not supported by remote
1711             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1712                 if (!l2cap_ertm_mode(channel)){
1713                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1714                     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
1715                 }
1716             }
1717 #endif
1718             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
1719                 uint16_t flags = 0;
1720                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1721                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
1722                     flags = 1;
1723                 } else {
1724                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1725                 }
1726                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
1727                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1728                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1729                                                         channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS,
1730                                                         1, &channel->unknown_option);
1731 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1732                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
1733                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1734                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1735                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1736                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1737                                                         channel->remote_cid, flags,
1738                                                         L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS, options_size,
1739                                                         &config_options);
1740                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM){
1741                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
1742                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1743                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1744                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1745                                                         channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS,
1746                                                         options_size, &config_options);
1747 #endif
1748                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
1749                     channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1750                     uint16_t options_size = l2cap_setup_options_mtu_response(channel, config_options);
1751                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1752                                                         channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS,
1753                                                         options_size, &config_options);
1754                 } else {
1755                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1756                                                         channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
1757                 }
1758                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1759             }
1760             else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
1761                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1762                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
1763                 channel->local_sig_id = l2cap_next_sig_id();
1764                 uint16_t options_size = l2cap_setup_options_request(channel, config_options);
1765                 l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id,
1766                                                     channel->remote_cid, 0, options_size, &config_options);
1767                 l2cap_start_rtx(channel);
1768             }
1769             if (l2cap_channel_ready_for_open(channel)){
1770                 channel->state = L2CAP_STATE_OPEN;
1771                 l2cap_emit_channel_opened(channel, 0);  // success
1772             }
1773             break;
1774 
1775         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1776             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1777             channel->state = L2CAP_STATE_INVALID;
1778             l2cap_send_classic_signaling_packet(channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id,
1779                                                 channel->local_cid, channel->remote_cid);
1780             // 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 :)
1781             l2cap_finalize_channel_close(channel);  // -- remove from list
1782             channel = NULL;
1783             break;
1784 
1785         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1786             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1787             channel->local_sig_id = l2cap_next_sig_id();
1788             channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1789             l2cap_send_classic_signaling_packet(channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id,
1790                                                 channel->remote_cid, channel->local_cid);
1791             break;
1792         default:
1793             break;
1794     }
1795 
1796     // handle channel finalize on L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE and L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE
1797     return channel == NULL;
1798 }
1799 
1800 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1801 static void l2cap_run_for_classic_channel_ertm(l2cap_channel_t * channel){
1802 
1803     // ERTM mode
1804     if (channel->mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) return;
1805 
1806     // check if we can still send
1807     if (channel->con_handle == HCI_CON_HANDLE_INVALID) return;
1808     if (!hci_can_send_acl_packet_now(channel->con_handle)) return;
1809 
1810     if (channel->send_supervisor_frame_receiver_ready){
1811         channel->send_supervisor_frame_receiver_ready = 0;
1812         log_info("Send S-Frame: RR %u, final %u", channel->req_seq, channel->set_final_bit_after_packet_with_poll_bit_set);
1813         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);
1814         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1815         l2cap_ertm_send_supervisor_frame(channel, control);
1816         return;
1817     }
1818     if (channel->send_supervisor_frame_receiver_ready_poll){
1819         channel->send_supervisor_frame_receiver_ready_poll = 0;
1820         log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
1821         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
1822         l2cap_ertm_send_supervisor_frame(channel, control);
1823         return;
1824     }
1825     if (channel->send_supervisor_frame_receiver_not_ready){
1826         channel->send_supervisor_frame_receiver_not_ready = 0;
1827         log_info("Send S-Frame: RNR %u", channel->req_seq);
1828         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
1829         l2cap_ertm_send_supervisor_frame(channel, control);
1830         return;
1831     }
1832     if (channel->send_supervisor_frame_reject){
1833         channel->send_supervisor_frame_reject = 0;
1834         log_info("Send S-Frame: REJ %u", channel->req_seq);
1835         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 0, 0, channel->req_seq);
1836         l2cap_ertm_send_supervisor_frame(channel, control);
1837         return;
1838     }
1839     if (channel->send_supervisor_frame_selective_reject){
1840         channel->send_supervisor_frame_selective_reject = 0;
1841         log_info("Send S-Frame: SREJ %u", channel->expected_tx_seq);
1842         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);
1843         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1844         l2cap_ertm_send_supervisor_frame(channel, control);
1845         return;
1846     }
1847 
1848     if (channel->srej_active){
1849         int i;
1850         for (i=0;i<channel->num_tx_buffers;i++){
1851             l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
1852             if (tx_state->retransmission_requested) {
1853                 tx_state->retransmission_requested = 0;
1854                 uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set;
1855                 channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1856                 l2cap_ertm_send_information_frame(channel, i, final);
1857                 break;
1858             }
1859         }
1860         if (i == channel->num_tx_buffers){
1861             // no retransmission request found
1862             channel->srej_active = 0;
1863         } else {
1864             // packet was sent
1865             return;
1866         }
1867     }
1868 }
1869 #endif /* ERTM */
1870 #endif /* Classic */
1871 
1872 static void l2cap_run_signaling_response(void) {
1873 
1874     // check pending signaling responses
1875     while (l2cap_signaling_responses_pending){
1876 
1877         hci_con_handle_t handle = l2cap_signaling_responses[0].handle;
1878 
1879         if (!hci_can_send_acl_packet_now(handle)) break;
1880 
1881         uint8_t  sig_id        = l2cap_signaling_responses[0].sig_id;
1882         uint8_t  response_code = l2cap_signaling_responses[0].code;
1883         uint16_t result        = l2cap_signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT, REJECT_SM_PAIRING, L2CAP_CREDIT_BASED_CONNECTION_REQUEST
1884         uint8_t  buffer[4];                                          // REJECT_SM_PAIRING
1885         uint16_t source_cid    = l2cap_signaling_responses[0].cid;   // CONNECTION_REQUEST, REJECT_SM_PAIRING, DISCONNECT_REQUEST
1886 #ifdef ENABLE_CLASSIC
1887         uint16_t info_type     = l2cap_signaling_responses[0].data;  // INFORMATION_REQUEST
1888 #endif
1889 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1890         uint8_t num_channels = l2cap_signaling_responses[0].cid >> 8;                 // L2CAP_CREDIT_BASED_CONNECTION_REQUEST
1891         uint16_t signaling_cid = (uint16_t) l2cap_signaling_responses[0].cid & 0xff;  // L2CAP_CREDIT_BASED_CONNECTION_REQUEST, L2CAP_CREDIT_BASED_CONNECTION_REQUEST
1892 #endif
1893 
1894         // remove first item before sending (to avoid sending response mutliple times)
1895         l2cap_signaling_responses_pending--;
1896         int i;
1897         for (i=0; i < l2cap_signaling_responses_pending; i++){
1898             (void)memcpy(&l2cap_signaling_responses[i],
1899                          &l2cap_signaling_responses[i + 1],
1900                          sizeof(l2cap_signaling_response_t));
1901         }
1902 
1903         switch (response_code){
1904 #ifdef ENABLE_CLASSIC
1905             case CONNECTION_REQUEST:
1906                 l2cap_send_classic_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
1907                 break;
1908             case ECHO_REQUEST:
1909                 l2cap_send_classic_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
1910                 break;
1911             case INFORMATION_REQUEST:
1912                 switch (info_type){
1913                     case L2CAP_INFO_TYPE_CONNECTIONLESS_MTU: {
1914                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
1915                         l2cap_send_classic_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0,
1916                                                             sizeof(connectionless_mtu), &connectionless_mtu);
1917                         }
1918                         break;
1919                     case L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED: {
1920                             uint32_t features = l2cap_extended_features_mask();
1921                         l2cap_send_classic_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0,
1922                                                             sizeof(features), &features);
1923                         }
1924                         break;
1925                     case L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED: {
1926                             uint8_t map[8];
1927                             memset(map, 0, 8);
1928                             // L2CAP Signaling Channel + Connectionless reception
1929                             map[0] = (1 << L2CAP_CID_SIGNALING) | (1 << L2CAP_CID_CONNECTIONLESS_CHANNEL);
1930 #if defined (ENABLE_EXPLICIT_BR_EDR_SECURITY_MANAGER) || (defined(ENABLE_BLE) && defined(ENABLE_CROSS_TRANSPORT_KEY_DERIVATION))
1931                             // BR/EDR Security Manager (bit 7) if BR/EDR Secure Connections possible
1932                             if (gap_secure_connections_active()){
1933                                 map[0] |= (1 << L2CAP_CID_BR_EDR_SECURITY_MANAGER);
1934                             }
1935 #endif
1936                             l2cap_send_classic_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0,
1937                                                             sizeof(map), &map);
1938                         }
1939                         break;
1940                     default:
1941                         // all other types are not supported
1942                         l2cap_send_classic_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 1, 0, NULL);
1943                         break;
1944                 }
1945                 break;
1946             case COMMAND_REJECT:
1947                 l2cap_send_classic_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
1948                 break;
1949 #endif
1950 #ifdef ENABLE_BLE
1951             case LE_CREDIT_BASED_CONNECTION_REQUEST:
1952                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
1953                 break;
1954             case DISCONNECTION_REQUEST:
1955                 // Invalid CID, local cid, remote cid
1956                 little_endian_store_16(buffer, 0, result);
1957                 little_endian_store_16(buffer, 2, source_cid);
1958                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, 0x0002, 4, buffer);
1959                 break;
1960             case COMMAND_REJECT_LE:
1961                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
1962                 break;
1963 #endif
1964 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1965             case L2CAP_CREDIT_BASED_CONNECTION_REQUEST: {
1966                 // send variable size array or cids with each cid being zero
1967                 uint16_t cids[6];
1968                 (void) memset(cids, 0xff, sizeof(cids));
1969                 (void) memset(cids, 0x00, num_channels * sizeof(uint16_t));
1970                 l2cap_send_general_signaling_packet(handle, signaling_cid, L2CAP_CREDIT_BASED_CONNECTION_RESPONSE,
1971                                                     sig_id, 0, 0, 0, result, cids);
1972                 break;
1973             }
1974 
1975             case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
1976                 l2cap_send_general_signaling_packet(handle, signaling_cid, L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE,
1977                                                     sig_id, result);
1978                 break;
1979 #endif
1980             case SM_PAIRING_FAILED:
1981                 buffer[0] = SM_CODE_PAIRING_FAILED;
1982                 buffer[1] = (uint8_t) result;
1983                 l2cap_send_connectionless(handle, source_cid, buffer, 2);
1984                 break;
1985             default:
1986                 // should not happen
1987                 break;
1988         }
1989     }
1990 }
1991 
1992 #ifdef ENABLE_CLASSIC
1993 static bool l2ap_run_information_requests(void){
1994     // send l2cap information request if requested
1995     btstack_linked_list_iterator_t it;
1996     hci_connections_get_iterator(&it);
1997     uint8_t info_type;
1998     l2cap_information_state_t new_state;
1999     while(btstack_linked_list_iterator_has_next(&it)){
2000         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
2001         switch (connection->l2cap_state.information_state){
2002             case L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST:
2003                 info_type = L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED;
2004                 new_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
2005                 break;
2006             case L2CAP_INFORMATION_STATE_W2_SEND_FIXED_CHANNELS_REQUEST:
2007                 info_type = L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED;
2008                 new_state = L2CAP_INFORMATION_STATE_W4_FIXED_CHANNELS_RESPONSE;
2009                 break;
2010             default:
2011                 continue;
2012         }
2013         if (!hci_can_send_acl_packet_now(connection->con_handle)) break;
2014 
2015         connection->l2cap_state.information_state = new_state;
2016         uint8_t sig_id = l2cap_next_sig_id();
2017         l2cap_send_classic_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
2018     }
2019     return false;
2020 }
2021 #endif
2022 
2023 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2024 static void l2cap_cbm_run_channels(void){
2025     btstack_linked_list_iterator_t it;
2026     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2027     while (btstack_linked_list_iterator_has_next(&it)){
2028         uint16_t mps;
2029         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2030 
2031         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CHANNEL_CBM) continue;
2032         if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2033 
2034         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
2035         switch (channel->state){
2036             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
2037                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
2038                 // le psm, source cid, mtu, mps, initial credits
2039                 channel->local_sig_id = l2cap_next_sig_id();
2040                 channel->credits_incoming =  channel->new_credits_incoming;
2041                 channel->new_credits_incoming = 0;
2042                 channel->local_mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
2043                 l2cap_send_le_signaling_packet( channel->con_handle, LE_CREDIT_BASED_CONNECTION_REQUEST,
2044                                                 channel->local_sig_id, channel->psm, channel->local_cid, channel->local_mtu,
2045                                                 channel->local_mps, channel->credits_incoming);
2046                 break;
2047             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
2048                 // TODO: support larger MPS
2049                 channel->state = L2CAP_STATE_OPEN;
2050                 channel->credits_incoming =  channel->new_credits_incoming;
2051                 channel->new_credits_incoming = 0;
2052                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
2053                 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);
2054                 // notify client
2055                 l2cap_cbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
2056                 break;
2057             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
2058                 channel->state = L2CAP_STATE_INVALID;
2059                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
2060                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
2061                 btstack_linked_list_iterator_remove(&it);
2062                 l2cap_free_channel_entry(channel);
2063                 break;
2064             case L2CAP_STATE_OPEN:
2065                 if (channel->new_credits_incoming){
2066                     l2cap_credit_based_send_credits(channel);
2067                 }
2068                 break;
2069             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2070                 channel->local_sig_id = l2cap_next_sig_id();
2071                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
2072                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
2073                 break;
2074             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
2075                 channel->state = L2CAP_STATE_INVALID;
2076                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
2077                 l2cap_cbm_finialize_channel_close(channel);  // -- remove from list
2078                 break;
2079             default:
2080                 break;
2081         }
2082     }
2083 }
2084 
2085 static inline uint8_t l2cap_cbm_status_for_result(uint16_t result) {
2086     switch (result) {
2087         case L2CAP_CBM_CONNECTION_RESULT_SUCCESS:
2088             return ERROR_CODE_SUCCESS;
2089         case L2CAP_CBM_CONNECTION_RESULT_SPSM_NOT_SUPPORTED:
2090             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_PSM;
2091         case L2CAP_CBM_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE:
2092             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_RESOURCES;
2093         case L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHENTICATION:
2094         case L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHORIZATION:
2095         case L2CAP_CBM_CONNECTION_RESULT_ENCYRPTION_KEY_SIZE_TOO_SHORT:
2096         case L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_ENCRYPTION:
2097             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY;
2098         default:
2099             // invalid Source CID, Source CID already allocated, unacceptable parameters
2100             return L2CAP_CONNECTION_RESPONSE_UNKNOWN_ERROR;
2101     }
2102 }
2103 
2104 #endif
2105 
2106 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2107 
2108 static void l2cap_run_trigger_callback(void * context){
2109     UNUSED(context);
2110     l2cap_run();
2111 }
2112 
2113 static void l2cap_run_trigger(void){
2114     btstack_run_loop_execute_on_main_thread(&l2cap_trigger_run_registration);
2115 }
2116 
2117 // 11BH22222
2118 static void l2cap_ecbm_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
2119     log_info("opened ecbm channel 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",
2120             status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
2121             channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
2122     uint8_t event[23];
2123     event[0] = L2CAP_EVENT_ECBM_CHANNEL_OPENED;
2124     event[1] = sizeof(event) - 2u;
2125     event[2] = status;
2126     event[3] = channel->address_type;
2127     reverse_bd_addr(channel->address, &event[4]);
2128     little_endian_store_16(event, 10, channel->con_handle);
2129     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
2130     little_endian_store_16(event, 13, channel->psm);
2131     little_endian_store_16(event, 15, channel->local_cid);
2132     little_endian_store_16(event, 17, channel->remote_cid);
2133     little_endian_store_16(event, 19, channel->local_mtu);
2134     little_endian_store_16(event, 21, channel->remote_mtu);
2135     hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
2136     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
2137 }
2138 
2139 static void l2cap_ecbm_emit_reconfigure_complete(l2cap_channel_t *channel, uint16_t result) {
2140     // emit event
2141     uint8_t event[6];
2142     event[0] = L2CAP_EVENT_ECBM_RECONFIGURATION_COMPLETE;
2143     event[1] = sizeof(event) - 2;
2144     little_endian_store_16(event, 2, channel->local_cid);
2145     little_endian_store_16(event, 4, result);
2146     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
2147 }
2148 
2149 static void l2cap_ecbm_run_channels(void) {
2150     hci_con_handle_t con_handle = HCI_CON_HANDLE_INVALID;
2151     // num max channels + 1 for signaling pdu generator
2152     uint16_t cids[L2CAP_ECBM_MAX_CID_ARRAY_SIZE + 1];
2153     uint8_t num_cids = 0;
2154     uint8_t sig_id;
2155     uint16_t spsm;
2156     L2CAP_STATE matching_state;
2157     bool match_remote_sig_cid;
2158     uint8_t result = 0;
2159     uint16_t local_mtu;
2160     uint16_t initial_credits;
2161     uint16_t signaling_cid;
2162     L2CAP_STATE new_state;
2163     uint16_t local_mps;
2164 
2165     // pick first channel that needs to send a combined signaling pdu and setup collection via break
2166     // then collect all others that belong to the same pdu
2167     btstack_linked_list_iterator_t it;
2168     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2169     while (btstack_linked_list_iterator_has_next(&it)) {
2170         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2171         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CHANNEL_ECBM) continue;
2172         if (con_handle == HCI_CON_HANDLE_INVALID) {
2173             switch (channel->state) {
2174                 case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST:
2175                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2176                     local_mtu = channel->local_mtu;
2177                     local_mps = channel->local_mps;
2178                     spsm = channel->psm;
2179                     result = channel->reason;
2180                     initial_credits = channel->credits_incoming;
2181                     sig_id = channel->local_sig_id;
2182                     new_state = L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE;
2183                     match_remote_sig_cid = false;
2184                     break;
2185                 case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE:
2186                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2187                     local_mtu = channel->local_mtu;
2188                     local_mps = channel->local_mps;
2189                     initial_credits = channel->credits_incoming;
2190                     sig_id = channel->remote_sig_id;
2191                     new_state = L2CAP_STATE_OPEN;
2192                     match_remote_sig_cid = true;
2193                     break;
2194                 case L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST:
2195                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2196                     sig_id = channel->local_sig_id;
2197                     local_mtu = channel->renegotiate_mtu;
2198                     local_mps = channel->local_mps;
2199                     new_state = L2CAP_STATE_WAIT_ENHANCED_RENEGOTIATION_RESPONSE;
2200                     match_remote_sig_cid = false;
2201                     break;
2202                 case L2CAP_STATE_OPEN:
2203                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2204                     if (channel->new_credits_incoming) {
2205                         l2cap_credit_based_send_credits(channel);
2206                     }
2207                     continue;
2208                 case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2209                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2210                     channel->local_sig_id = l2cap_next_sig_id();
2211                     channel->state = L2CAP_STATE_WAIT_DISCONNECT;
2212                     signaling_cid = channel->address_type == BD_ADDR_TYPE_ACL ? L2CAP_CID_SIGNALING : L2CAP_CID_SIGNALING_LE;
2213                     l2cap_send_general_signaling_packet(channel->con_handle, signaling_cid, DISCONNECTION_REQUEST,
2214                                                         channel->local_sig_id, channel->remote_cid, channel->local_cid);
2215                     continue;
2216                 case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
2217                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2218                     channel->state = L2CAP_STATE_INVALID;
2219                     signaling_cid = channel->address_type == BD_ADDR_TYPE_ACL ? L2CAP_CID_SIGNALING : L2CAP_CID_SIGNALING_LE;
2220                     l2cap_send_general_signaling_packet(channel->con_handle, signaling_cid, DISCONNECTION_RESPONSE,
2221                                                         channel->remote_sig_id, channel->local_cid,
2222                                                         channel->remote_cid);
2223                     l2cap_cbm_finialize_channel_close(channel);  // -- remove from list
2224                     continue;
2225                 default:
2226                     continue;
2227             }
2228 
2229             // channel picked - setup cid array and collect info
2230             (void) memset(cids, 0xff, sizeof(cids));
2231             (void) memset(cids, 0, channel->num_cids * sizeof(uint16_t));
2232             matching_state = channel->state;
2233             con_handle = channel->con_handle;
2234             signaling_cid = channel->address_type == BD_ADDR_TYPE_ACL ? L2CAP_CID_SIGNALING : L2CAP_CID_SIGNALING_LE;
2235             num_cids = channel->num_cids;
2236 
2237         } else {
2238             // check if it matches first channel by state, con_handle, and signaling id
2239             if (matching_state != channel->state) continue;
2240             if (channel->con_handle != con_handle) continue;
2241             if (match_remote_sig_cid) {
2242                 if (channel->remote_sig_id != sig_id) continue;
2243             } else {
2244                 if (channel->local_sig_id != sig_id) continue;
2245             }
2246         }
2247 
2248         // add this cid
2249         cids[channel->cid_index] = channel->local_cid;
2250 
2251         // set new state
2252         channel->state = new_state;
2253 
2254         // handle open for L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE
2255         if (matching_state == L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE) {
2256             if (channel->reason == L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS) {
2257                 l2cap_ecbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
2258             } else {
2259                 result = channel->reason;
2260                 btstack_linked_list_iterator_remove(&it);
2261                 btstack_memory_l2cap_channel_free(channel);
2262             }
2263         }
2264     }
2265 
2266     if (con_handle != HCI_CON_HANDLE_INVALID) {
2267         switch (matching_state) {
2268             case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST:
2269                 log_info("send combined connection request for %u cids", num_cids);
2270                 l2cap_send_general_signaling_packet(con_handle, signaling_cid, L2CAP_CREDIT_BASED_CONNECTION_REQUEST,
2271                                                     sig_id, spsm, local_mtu, local_mps, initial_credits, cids);
2272                 break;
2273             case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE:
2274                 log_info("send combined connection response for %u cids", num_cids);
2275                 l2cap_send_general_signaling_packet(con_handle, signaling_cid, L2CAP_CREDIT_BASED_CONNECTION_RESPONSE,
2276                                                     sig_id, local_mtu, local_mps, initial_credits, result, cids);
2277                 break;
2278             case L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST:
2279                 log_info("send combined renegotiation request for %u cids", num_cids);
2280                 l2cap_send_general_signaling_packet(con_handle, signaling_cid, L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST,
2281                                                     sig_id, local_mtu, local_mps, cids);
2282                 break;
2283             default:
2284                 break;
2285         }
2286     }
2287 }
2288 #endif
2289 
2290 // MARK: L2CAP_RUN
2291 // process outstanding signaling tasks
2292 static void l2cap_run(void){
2293 
2294     // log_info("l2cap_run: entered");
2295     l2cap_run_signaling_response();
2296 
2297 #ifdef ENABLE_CLASSIC
2298     bool done = l2ap_run_information_requests();
2299     if (done) return;
2300 #endif
2301 
2302 #if defined(ENABLE_CLASSIC) || defined(ENABLE_BLE)
2303     btstack_linked_list_iterator_t it;
2304 #endif
2305 
2306 #ifdef ENABLE_CLASSIC
2307     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2308     while (btstack_linked_list_iterator_has_next(&it)){
2309 
2310         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2311 
2312         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CLASSIC) continue;
2313 
2314         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
2315         bool finalized = l2cap_run_for_classic_channel(channel);
2316 
2317         if (!finalized) {
2318 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2319             l2cap_run_for_classic_channel_ertm(channel);
2320 #endif
2321         }
2322     }
2323 #endif
2324 
2325 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2326     l2cap_cbm_run_channels();
2327 #endif
2328 
2329 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2330     l2cap_ecbm_run_channels();
2331 #endif
2332 
2333 #ifdef ENABLE_BLE
2334     // send l2cap con paramter update if necessary
2335     hci_connections_get_iterator(&it);
2336     while(btstack_linked_list_iterator_has_next(&it)){
2337         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
2338         if ((connection->address_type != BD_ADDR_TYPE_LE_PUBLIC) && (connection->address_type != BD_ADDR_TYPE_LE_RANDOM)) continue;
2339         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
2340         switch (connection->le_con_parameter_update_state){
2341             case CON_PARAMETER_UPDATE_SEND_REQUEST:
2342                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2343                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, l2cap_next_sig_id(),
2344                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
2345                 break;
2346             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
2347                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
2348                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
2349                 break;
2350             case CON_PARAMETER_UPDATE_DENY:
2351                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2352                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
2353                 break;
2354             default:
2355                 break;
2356         }
2357     }
2358 #endif
2359 
2360     if (l2cap_call_notify_channel_in_run){
2361         l2cap_call_notify_channel_in_run = false;
2362         l2cap_notify_channel_can_send();
2363     }
2364 
2365     // log_info("l2cap_run: exit");
2366 }
2367 
2368 #ifdef ENABLE_CLASSIC
2369 static void l2cap_ready_to_connect(l2cap_channel_t * channel){
2370 
2371 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2372     // assumption: outgoing connection
2373     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
2374         // ERTM requested: trigger information request if not already started then wait for response
2375         hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
2376         switch (connection->l2cap_state.information_state){
2377             case L2CAP_INFORMATION_STATE_DONE:
2378                 break;
2379             case L2CAP_INFORMATION_STATE_IDLE:
2380                 connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2381                 /* fall through */
2382             default:
2383                 channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
2384                 return;
2385         }
2386     }
2387 #endif
2388 
2389     // fine, go ahead
2390     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
2391 }
2392 
2393 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
2394     if ((channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE) || (channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION)) {
2395         log_info("connection complete con_handle %04x - for channel %p cid 0x%04x", (int) con_handle, channel, channel->local_cid);
2396         channel->con_handle = con_handle;
2397         // query remote features if pairing is required
2398         if (channel->required_security_level > LEVEL_0){
2399             channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
2400             hci_remote_features_query(con_handle);
2401         } else {
2402             l2cap_ready_to_connect(channel);
2403         }
2404     }
2405 }
2406 
2407 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
2408     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
2409 
2410     bool security_required = channel->required_security_level > LEVEL_0;
2411 
2412     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) != 0){
2413 
2414         // Core V5.2, Vol 3, Part C, 5.2.2.2 - Security Mode 4
2415         //   When a remote device attempts to access a service offered by a Bluetooth device that is in security mode 4
2416         //   and a sufficient link key exists and authentication has not been performed the local device shall authenticate
2417         //   the remote device and enable encryption after the channel establishment request is received but before a channel
2418         //   establishment confirmation (L2CAP_ConnectRsp with result code of 0x0000 or a higher-level channel establishment
2419         //   confirmation such as that of RFCOMM) is sent.
2420 
2421         //   If the remote device has indicated support for Secure Simple Pairing, a channel establishment request is
2422         //   received for a service other than SDP, and encryption has not yet been enabled, then the local device shall
2423         //   disconnect the ACL link with error code 0x05 - Authentication Failure.
2424 
2425         // => Disconnect if l2cap request received in mode 4 and ssp supported, non-sdp psm, not encrypted, no link key available
2426         if ((gap_get_security_mode() == GAP_SECURITY_MODE_4)
2427         && gap_ssp_supported_on_both_sides(channel->con_handle)
2428         && (channel->psm != PSM_SDP)
2429         && (gap_encryption_key_size(channel->con_handle) == 0)){
2430             hci_disconnect_security_block(channel->con_handle);
2431             return;
2432         }
2433 
2434         // incoming: assert security requirements
2435         channel->state = L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
2436         if (channel->required_security_level <= gap_security_level(channel->con_handle)){
2437             l2cap_handle_security_level_incoming_sufficient(channel);
2438         } else {
2439             // send connection pending if not already done
2440             if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONN_RESP_PEND) == 0){
2441                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND;
2442             }
2443             gap_request_security_level(channel->con_handle, channel->required_security_level);
2444         }
2445     } else {
2446         // outgoing: we have been waiting for remote supported features
2447         if (security_required){
2448             // request security level
2449             channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
2450             gap_request_security_level(channel->con_handle, channel->required_security_level);
2451         } else {
2452             l2cap_ready_to_connect(channel);
2453         }
2454     }
2455 }
2456 #endif
2457 
2458 #ifdef L2CAP_USES_CHANNELS
2459 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,
2460     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
2461 
2462     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
2463     if (!channel) {
2464         return NULL;
2465     }
2466 
2467     // fill in
2468     channel->packet_handler = packet_handler;
2469     channel->channel_type   = channel_type;
2470     bd_addr_copy(channel->address, address);
2471     channel->address_type = address_type;
2472     channel->psm = psm;
2473     channel->local_mtu  = local_mtu;
2474     channel->remote_mtu = L2CAP_DEFAULT_MTU;
2475     channel->required_security_level = security_level;
2476 
2477     //
2478     channel->local_cid = l2cap_next_local_cid();
2479     channel->con_handle = HCI_CON_HANDLE_INVALID;
2480 
2481     // set initial state
2482     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
2483     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
2484     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
2485     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
2486 
2487     log_info("create channel %p, local_cid 0x%04x", channel, channel->local_cid);
2488 
2489     return channel;
2490 }
2491 
2492 static void l2cap_free_channel_entry(l2cap_channel_t * channel){
2493     log_info("free channel %p, local_cid 0x%04x", channel, channel->local_cid);
2494     // assert all timers are stopped
2495     l2cap_stop_rtx(channel);
2496 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2497     l2cap_ertm_stop_retransmission_timer(channel);
2498     l2cap_ertm_stop_monitor_timer(channel);
2499 #endif
2500     // free  memory
2501     btstack_memory_l2cap_channel_free(channel);
2502 }
2503 #endif
2504 
2505 #ifdef ENABLE_CLASSIC
2506 
2507 /**
2508  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
2509  * @param packet_handler
2510  * @param address
2511  * @param psm
2512  * @param mtu
2513  * @param local_cid
2514  */
2515 
2516 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){
2517     // limit MTU to the size of our outgoing HCI buffer
2518     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
2519 
2520 	// determine security level based on psm
2521 	const gap_security_level_t security_level = l2cap_security_level_0_allowed_for_PSM(psm) ? LEVEL_0 : gap_get_security_level();
2522 	log_info("create channel addr %s psm 0x%x mtu %u -> local mtu %u, sec level %u", bd_addr_to_str(address), psm, mtu, local_mtu, (int) security_level);
2523 
2524     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, address, BD_ADDR_TYPE_ACL, psm, local_mtu, security_level);
2525     if (!channel) {
2526         return BTSTACK_MEMORY_ALLOC_FAILED;
2527     }
2528 
2529 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2530     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2531 #endif
2532 
2533     // add to connections list
2534     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2535 
2536     // store local_cid
2537     if (out_local_cid){
2538        *out_local_cid = channel->local_cid;
2539     }
2540 
2541 	// state: L2CAP_STATE_WILL_SEND_CREATE_CONNECTION
2542 
2543     // check if hci connection is already usable,
2544     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
2545     if (conn && conn->state == OPEN){
2546     	// simulate connection complete
2547 	    l2cap_handle_connection_complete(conn->con_handle, channel);
2548 
2549 	    // state: L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES or L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST
2550 
2551         // simulate if remote supported features if requested and already received
2552         if ((channel->state == L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) && hci_remote_features_available(conn->con_handle)) {
2553         	// simulate remote features received
2554             l2cap_handle_remote_supported_features_received(channel);
2555         }
2556     }
2557 
2558     l2cap_run();
2559 
2560     return ERROR_CODE_SUCCESS;
2561 }
2562 
2563 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
2564     // mark all channels before emitting open events as these could trigger new connetion requests to the same device
2565     btstack_linked_list_iterator_t it;
2566     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2567     while (btstack_linked_list_iterator_has_next(&it)){
2568         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2569         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2570         if (bd_addr_cmp( channel->address, address) != 0) continue;
2571         // channel for this address found
2572         switch (channel->state){
2573             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2574             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2575                 channel->state = L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD;
2576                 break;
2577             default:
2578                 break;
2579         }
2580     }
2581     // emit and free marked entries. restart loop to deal with list changes
2582     int done = 0;
2583     while (!done) {
2584         done = 1;
2585         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2586         while (btstack_linked_list_iterator_has_next(&it)){
2587             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2588             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2589             if (channel->state == L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD){
2590                 done = 0;
2591                 // failure, forward error code
2592                 l2cap_handle_channel_open_failed(channel, status);
2593                 // discard channel
2594                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2595                 l2cap_free_channel_entry(channel);
2596                 break;
2597             }
2598         }
2599     }
2600 
2601 }
2602 
2603 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
2604     btstack_linked_list_iterator_t it;
2605     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2606     while (btstack_linked_list_iterator_has_next(&it)){
2607         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2608         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2609         if ( ! bd_addr_cmp( channel->address, address) ){
2610             l2cap_handle_connection_complete(handle, channel);
2611         }
2612     }
2613 
2614 #ifdef ENABLE_L2CAP_INFORMATION_REQUESTS_ON_CONNECT
2615     // trigger query of extended features and fixed channels right away (instead of later)
2616     hci_connection_t * hci_connection = hci_connection_for_handle(handle);
2617     btstack_assert(hci_connection != NULL);
2618     hci_connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2619 #endif
2620 
2621     // process
2622     l2cap_run();
2623 }
2624 #endif
2625 
2626 static bool l2cap_channel_ready_to_send(l2cap_channel_t * channel){
2627     switch (channel->channel_type){
2628 #ifdef ENABLE_CLASSIC
2629         case L2CAP_CHANNEL_TYPE_CLASSIC:
2630             if (channel->state != L2CAP_STATE_OPEN) return false;
2631 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2632             // send if we have more data and remote windows isn't full yet
2633             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2634                 if (channel->unacked_frames >= btstack_min(channel->num_stored_tx_frames, channel->remote_tx_window_size)) return false;
2635                 return hci_can_send_acl_packet_now(channel->con_handle);
2636             }
2637 #endif
2638             if (!channel->waiting_for_can_send_now) return false;
2639             return hci_can_send_acl_packet_now(channel->con_handle);
2640         case L2CAP_CHANNEL_TYPE_FIXED_CLASSIC:
2641         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2642             if (!channel->waiting_for_can_send_now) return false;
2643             return hci_can_send_acl_classic_packet_now();
2644 #endif
2645 #ifdef ENABLE_BLE
2646         case L2CAP_CHANNEL_TYPE_FIXED_LE:
2647             if (!channel->waiting_for_can_send_now) return false;
2648             return hci_can_send_acl_le_packet_now();
2649 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2650         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
2651             if (channel->state != L2CAP_STATE_OPEN) return false;
2652             if (channel->send_sdu_buffer == NULL) return false;
2653             if (channel->credits_outgoing == 0u) return false;
2654             return hci_can_send_acl_packet_now(channel->con_handle);
2655 #endif
2656 #endif
2657 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2658         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
2659             if (channel->state != L2CAP_STATE_OPEN) return false;
2660             if (channel->send_sdu_buffer == NULL) return false;
2661             if (channel->credits_outgoing == 0u) return false;
2662             return hci_can_send_acl_packet_now(channel->con_handle);
2663 #endif
2664         default:
2665             return false;
2666     }
2667 }
2668 
2669 static void l2cap_channel_trigger_send(l2cap_channel_t * channel){
2670     switch (channel->channel_type){
2671 #ifdef ENABLE_CLASSIC
2672         case L2CAP_CHANNEL_TYPE_CLASSIC:
2673 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2674             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2675                 l2cap_ertm_channel_send_information_frame(channel);
2676                 return;
2677             }
2678 #endif
2679             channel->waiting_for_can_send_now = 0;
2680             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2681             break;
2682         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2683         case L2CAP_CHANNEL_TYPE_FIXED_CLASSIC:
2684             channel->waiting_for_can_send_now = 0;
2685             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2686             break;
2687 #endif
2688 #ifdef ENABLE_BLE
2689         case L2CAP_CHANNEL_TYPE_FIXED_LE:
2690             channel->waiting_for_can_send_now = 0;
2691             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2692             break;
2693 #endif
2694 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2695         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
2696             l2cap_credit_based_send_pdu(channel);
2697             break;
2698 #endif
2699 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2700         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
2701             l2cap_credit_based_send_pdu(channel);
2702             break;
2703 #endif
2704         default:
2705             btstack_unreachable();
2706             break;
2707     }
2708 }
2709 
2710 static void l2cap_notify_channel_can_send(void){
2711     bool done = false;
2712     while (!done){
2713         done = true;
2714         btstack_linked_list_iterator_t it;
2715         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2716         while (btstack_linked_list_iterator_has_next(&it)){
2717             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2718             bool ready = l2cap_channel_ready_to_send(channel);
2719             if (!ready) continue;
2720 
2721             // requeue channel for fairness
2722             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2723             btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2724 
2725             // trigger sending
2726             l2cap_channel_trigger_send(channel);
2727 
2728             // exit inner loop as we just broke the iterator, but try again
2729             done = false;
2730             break;
2731         }
2732     }
2733 }
2734 
2735 #ifdef L2CAP_USES_CHANNELS
2736 
2737 uint8_t l2cap_disconnect(uint16_t local_cid){
2738     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2739     if (!channel) {
2740         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2741     }
2742     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2743     l2cap_run();
2744     return ERROR_CODE_SUCCESS;
2745 }
2746 
2747 static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){
2748     // open cannot fail for for incoming connections
2749     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0;
2750 
2751     // check state
2752     switch (channel->state){
2753         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2754         case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2755         case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES:
2756         case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2757         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
2758         case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES:
2759         case L2CAP_STATE_WAIT_CONNECT_RSP:
2760         case L2CAP_STATE_CONFIG:
2761         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
2762         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
2763         case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE:
2764         case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD:
2765             return 1;
2766 
2767         case L2CAP_STATE_OPEN:
2768         case L2CAP_STATE_CLOSED:
2769         case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES:
2770         case L2CAP_STATE_WAIT_DISCONNECT:
2771         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY:
2772         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
2773         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
2774         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2775         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
2776         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
2777         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
2778         case L2CAP_STATE_INVALID:
2779         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2780             return 0;
2781 
2782         default:
2783             // get a "warning" about new states
2784             btstack_assert(false);
2785             return 0;
2786     }
2787 }
2788 #endif
2789 
2790 #ifdef ENABLE_CLASSIC
2791 static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){
2792     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2793         l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2794     } else {
2795         l2cap_handle_channel_closed(channel);
2796     }
2797     l2cap_free_channel_entry(channel);
2798 }
2799 #endif
2800 
2801 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2802 static void l2cap_handle_hci_le_disconnect_event(l2cap_channel_t * channel){
2803     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2804         l2cap_cbm_emit_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2805     } else {
2806         l2cap_emit_channel_closed(channel);
2807     }
2808     l2cap_free_channel_entry(channel);
2809 }
2810 #endif
2811 
2812 #ifdef ENABLE_CLASSIC
2813 static void l2cap_check_classic_timeout(hci_con_handle_t handle){
2814     if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) {
2815         return;
2816     }
2817     if (hci_authentication_active_for_handle(handle)) {
2818         return;
2819     }
2820     bool hci_con_used = false;
2821     btstack_linked_list_iterator_t it;
2822     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2823     while (btstack_linked_list_iterator_has_next(&it)){
2824         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2825         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2826         if (channel->con_handle != handle) continue;
2827         hci_con_used = true;
2828         break;
2829     }
2830     if (hci_con_used) {
2831         return;
2832     }
2833     if (!hci_can_send_command_packet_now()) {
2834         return;
2835     }
2836     hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
2837 }
2838 
2839 static void l2cap_handle_features_complete(hci_con_handle_t handle){
2840     if (hci_remote_features_available(handle) == false){
2841         return;
2842     }
2843     btstack_linked_list_iterator_t it;
2844     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2845     while (btstack_linked_list_iterator_has_next(&it)){
2846         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2847         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2848         if (channel->con_handle != handle) continue;
2849         log_info("remote supported features, channel %p, cid %04x - state %u", channel, channel->local_cid, channel->state);
2850         l2cap_handle_remote_supported_features_received(channel);
2851     }
2852 }
2853 
2854 static void l2cap_handle_security_level_incoming_sufficient(l2cap_channel_t * channel){
2855     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2856     l2cap_emit_incoming_connection(channel);
2857 }
2858 
2859 static void l2cap_handle_security_level(hci_con_handle_t handle, gap_security_level_t actual_level){
2860     log_info("security level update for handle 0x%04x", handle);
2861 
2862     // trigger l2cap information requests
2863     if (actual_level > LEVEL_0){
2864         hci_connection_t * hci_connection = hci_connection_for_handle(handle);
2865         btstack_assert(hci_connection != NULL);
2866         if (hci_connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
2867             hci_connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2868         }
2869     }
2870 
2871     bool done = false;
2872     while (!done){
2873         done = true;
2874         btstack_linked_list_iterator_t it;
2875         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2876         while (btstack_linked_list_iterator_has_next(&it)){
2877             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2878             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2879             if (channel->con_handle != handle) continue;
2880 
2881             gap_security_level_t required_level = channel->required_security_level;
2882 
2883             log_info("channel %p, cid %04x - state %u: actual %u >= required %u?", channel, channel->local_cid, channel->state, actual_level, required_level);
2884 
2885             switch (channel->state){
2886                 case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2887                     if (actual_level >= required_level){
2888                         l2cap_handle_security_level_incoming_sufficient(channel);
2889                     } else {
2890                         channel->reason = L2CAP_CONNECTION_RESULT_SECURITY_BLOCK;
2891                         channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2892                     }
2893                     break;
2894 
2895                 case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2896                     if (actual_level >= required_level){
2897                         l2cap_ready_to_connect(channel);
2898                     } else {
2899                         // security level insufficient, report error and free channel
2900                         l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY);
2901                         btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t  *) channel);
2902                         l2cap_free_channel_entry(channel);
2903                     }
2904                     break;
2905 
2906                 default:
2907                     break;
2908             }
2909         }
2910     }
2911 }
2912 #endif
2913 
2914 #ifdef L2CAP_USES_CHANNELS
2915 static void l2cap_handle_disconnection_complete(hci_con_handle_t handle){
2916     // collect channels to close
2917     btstack_linked_list_t channels_to_close = NULL;
2918     btstack_linked_list_iterator_t it;
2919     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2920     while (btstack_linked_list_iterator_has_next(&it)) {
2921         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2922         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2923         if (channel->con_handle != handle) continue;
2924         btstack_linked_list_iterator_remove(&it);
2925         btstack_linked_list_add(&channels_to_close, (btstack_linked_item_t *) channel);
2926     }
2927     // send l2cap open failed or closed events for all channels on this handle and free them
2928     btstack_linked_list_iterator_init(&it, &channels_to_close);
2929     while (btstack_linked_list_iterator_has_next(&it)) {
2930         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2931         btstack_linked_list_iterator_remove(&it);
2932         switch(channel->channel_type){
2933 #ifdef ENABLE_CLASSIC
2934             case L2CAP_CHANNEL_TYPE_CLASSIC:
2935                 l2cap_handle_hci_disconnect_event(channel);
2936                 break;
2937 #endif
2938 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2939             case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
2940                 l2cap_handle_hci_le_disconnect_event(channel);
2941                 break;
2942 #endif
2943 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2944             case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
2945                 switch (channel->state) {
2946                     case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST:
2947                     case L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE:
2948                         // emit open failed if disconnected before connection complete
2949                         l2cap_ecbm_emit_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2950                         break;
2951                     case L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST:
2952                     case L2CAP_STATE_WAIT_ENHANCED_RENEGOTIATION_RESPONSE:
2953                         // emit reconfigure failure - result = 0xffff
2954                         l2cap_ecbm_emit_reconfigure_complete(channel, 0xffff);
2955                         break;
2956                     default:
2957                         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
2958                         break;
2959                 }
2960                 l2cap_free_channel_entry(channel);
2961                 break;
2962 #endif
2963             default:
2964                 break;
2965         }
2966     }
2967 }
2968 #endif
2969 
2970 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
2971 
2972     UNUSED(packet_type); // ok: registered with hci_event_callback_registration
2973     UNUSED(cid);         // ok: there is no channel
2974     UNUSED(size);        // ok: fixed format events read from HCI buffer
2975 
2976 #ifdef ENABLE_CLASSIC
2977     bd_addr_t address;
2978     gap_security_level_t security_level;
2979 #endif
2980 #ifdef L2CAP_USES_CHANNELS
2981     hci_con_handle_t handle;
2982 #endif
2983 
2984     switch(hci_event_packet_get_type(packet)){
2985 
2986         // Notify channel packet handler if they can send now
2987         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2988         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
2989         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
2990 #ifdef ENABLE_TESTING_SUPPORT
2991         case HCI_EVENT_NOP:
2992 #endif
2993             l2cap_call_notify_channel_in_run = true;
2994             break;
2995 
2996         case HCI_EVENT_COMMAND_STATUS:
2997 #ifdef ENABLE_CLASSIC
2998             // check command status for create connection for errors
2999             if (hci_event_command_status_get_command_opcode(packet) == HCI_OPCODE_HCI_CREATE_CONNECTION){
3000                 // cache outgoing address and reset
3001                 (void)memcpy(address, l2cap_outgoing_classic_addr, 6);
3002                 memset(l2cap_outgoing_classic_addr, 0, 6);
3003                 // error => outgoing connection failed
3004                 uint8_t status = hci_event_command_status_get_status(packet);
3005                 if (status){
3006                     l2cap_handle_connection_failed_for_addr(address, status);
3007                 }
3008             }
3009 #endif
3010             l2cap_run();    // try sending signaling packets first
3011             break;
3012 
3013 #ifdef ENABLE_CLASSIC
3014         // handle connection complete events
3015         case HCI_EVENT_CONNECTION_COMPLETE:
3016             reverse_bd_addr(&packet[5], address);
3017             if (packet[2] == 0){
3018                 handle = little_endian_read_16(packet, 3);
3019                 l2cap_handle_connection_success_for_addr(address, handle);
3020             } else {
3021                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
3022             }
3023             break;
3024 
3025         // handle successful create connection cancel command
3026         case HCI_EVENT_COMMAND_COMPLETE:
3027             if (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_CREATE_CONNECTION_CANCEL) {
3028                 if (packet[5] == 0){
3029                     reverse_bd_addr(&packet[6], address);
3030                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
3031                     l2cap_handle_connection_failed_for_addr(address, 0x16);
3032                 }
3033             }
3034             l2cap_run();    // try sending signaling packets first
3035             break;
3036 #endif
3037 
3038 #ifdef L2CAP_USES_CHANNELS
3039         // handle disconnection complete events
3040         case HCI_EVENT_DISCONNECTION_COMPLETE:
3041             handle = little_endian_read_16(packet, 3);
3042             l2cap_handle_disconnection_complete(handle);
3043             break;
3044 #endif
3045 
3046         // HCI Connection Timeouts
3047 #ifdef ENABLE_CLASSIC
3048         case L2CAP_EVENT_TIMEOUT_CHECK:
3049             handle = little_endian_read_16(packet, 2);
3050             l2cap_check_classic_timeout(handle);
3051             break;
3052 
3053         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
3054         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
3055             handle = little_endian_read_16(packet, 3);
3056             l2cap_handle_features_complete(handle);
3057             break;
3058 
3059         case GAP_EVENT_SECURITY_LEVEL:
3060             handle = little_endian_read_16(packet, 2);
3061             security_level = (gap_security_level_t) packet[4];
3062             l2cap_handle_security_level(handle, security_level);
3063             break;
3064 #endif
3065         default:
3066             break;
3067     }
3068 
3069     l2cap_run();
3070 }
3071 
3072 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t cid, uint16_t data){
3073     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indicates the connection was refused."
3074     if (l2cap_signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
3075         l2cap_signaling_responses[l2cap_signaling_responses_pending].handle = handle;
3076         l2cap_signaling_responses[l2cap_signaling_responses_pending].code = code;
3077         l2cap_signaling_responses[l2cap_signaling_responses_pending].sig_id = sig_id;
3078         l2cap_signaling_responses[l2cap_signaling_responses_pending].cid = cid;
3079         l2cap_signaling_responses[l2cap_signaling_responses_pending].data = data;
3080         l2cap_signaling_responses_pending++;
3081         l2cap_run();
3082     }
3083 }
3084 
3085 #ifdef ENABLE_CLASSIC
3086 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint8_t identifier){
3087     switch (channel->state){
3088         case L2CAP_STATE_CONFIG:
3089         case L2CAP_STATE_OPEN:
3090         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
3091         case L2CAP_STATE_WAIT_DISCONNECT:
3092             break;
3093         default:
3094             // ignore in other states
3095             return;
3096     }
3097 
3098     channel->remote_sig_id = identifier;
3099     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
3100     l2cap_run();
3101 }
3102 
3103 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
3104 
3105     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
3106     l2cap_service_t *service = l2cap_get_service(psm);
3107     if (!service) {
3108         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CONNECTION_RESULT_PSM_NOT_SUPPORTED);
3109         return;
3110     }
3111 
3112     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
3113     if (!hci_connection) {
3114         //
3115         log_error("no hci_connection for handle %u", handle);
3116         return;
3117     }
3118 
3119     // if SC only mode is active and service requires encryption, reject connection if SC not active or use security level
3120     gap_security_level_t required_level = service->required_security_level;
3121     if (gap_get_secure_connections_only_mode() && (required_level != LEVEL_0)){
3122         if (gap_secure_connection(handle)){
3123             required_level = LEVEL_4;
3124         } else {
3125             l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CONNECTION_RESULT_SECURITY_BLOCK);
3126             return;
3127         }
3128     }
3129 
3130     // alloc structure
3131     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, hci_connection->address, BD_ADDR_TYPE_ACL,
3132     psm, service->mtu, required_level);
3133     if (!channel){
3134         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE);
3135         return;
3136     }
3137 
3138     channel->con_handle = handle;
3139     channel->remote_cid = source_cid;
3140     channel->remote_sig_id = sig_id;
3141 
3142     // limit local mtu to max acl packet length - l2cap header
3143     if (channel->local_mtu > l2cap_max_mtu()) {
3144         channel->local_mtu = l2cap_max_mtu();
3145     }
3146 
3147     // set initial state
3148     channel->state =     L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
3149     channel->state_var = L2CAP_CHANNEL_STATE_VAR_INCOMING;
3150 
3151     // add to connections list
3152     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
3153 
3154     //
3155     if (required_level > LEVEL_0){
3156         // send conn resp pending if remote supported features have not been received yet
3157         if (hci_remote_features_available(handle)) {
3158             l2cap_handle_remote_supported_features_received(channel);
3159         } else {
3160             channel->state_var |= L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND;
3161             hci_remote_features_query(handle);
3162         }
3163     } else {
3164         l2cap_handle_security_level_incoming_sufficient(channel);
3165     }
3166 }
3167 
3168 void l2cap_accept_connection(uint16_t local_cid){
3169     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
3170     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3171     if (!channel) {
3172         log_error("accept called but local_cid 0x%x not found", local_cid);
3173         return;
3174     }
3175 
3176 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3177     // configure L2CAP Basic mode
3178     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
3179 #endif
3180 
3181     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
3182 
3183     // process
3184     l2cap_run();
3185 }
3186 
3187 void l2cap_decline_connection(uint16_t local_cid){
3188     log_info("decline local_cid 0x%x", local_cid);
3189     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
3190     if (!channel) {
3191         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
3192         return;
3193     }
3194     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
3195     channel->reason = L2CAP_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE;
3196     l2cap_run();
3197 }
3198 
3199 // @pre command len is valid, see check in l2cap_signaling_handler_channel
3200 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
3201 
3202 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3203     uint8_t use_fcs = 1;
3204 #endif
3205 
3206     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
3207 
3208     uint16_t flags = little_endian_read_16(command, 6);
3209     if (flags & 1) {
3210         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
3211     }
3212 
3213     // accept the other's configuration options
3214     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3215     uint16_t pos     = 8;
3216     while (pos < end_pos){
3217         uint8_t option_hint = command[pos] >> 7;
3218         uint8_t option_type = command[pos] & 0x7f;
3219         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
3220         pos++;
3221         uint8_t length = command[pos++];
3222         // MTU { type(8): 1, len(8):2, MTU(16) }
3223         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) && (length == 2)){
3224             channel->remote_mtu = little_endian_read_16(command, pos);
3225             log_info("Remote MTU %u", channel->remote_mtu);
3226             if (channel->remote_mtu > l2cap_max_mtu()){
3227                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
3228                 channel->remote_mtu = l2cap_max_mtu();
3229             }
3230             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
3231         }
3232         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
3233         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT) && (length == 2)){
3234             channel->flush_timeout = little_endian_read_16(command, pos);
3235             log_info("Flush timeout: %u ms", channel->flush_timeout);
3236         }
3237 
3238 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3239         // Retransmission and Flow Control Option
3240         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
3241             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
3242             switch(channel->mode){
3243                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
3244                     // Store remote config
3245                     channel->remote_tx_window_size = command[pos+1];
3246                     channel->remote_max_transmit   = command[pos+2];
3247                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
3248                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
3249                     {
3250                         uint16_t remote_mps = little_endian_read_16(command, pos + 7);
3251                         // optimize our tx buffer configuration based on actual remote mps if remote mps is smaller than planned
3252                         if (remote_mps < channel->remote_mps){
3253                             // get current tx storage
3254                             uint16_t num_bytes_per_tx_buffer_before = sizeof(l2cap_ertm_tx_packet_state_t) + channel->remote_mps;
3255                             uint16_t tx_storage = channel->num_tx_buffers * num_bytes_per_tx_buffer_before;
3256 
3257                             channel->remote_mps = remote_mps;
3258                             uint16_t num_bytes_per_tx_buffer_now = sizeof(l2cap_ertm_tx_packet_state_t) + channel->remote_mps;
3259                             channel->num_tx_buffers = tx_storage / num_bytes_per_tx_buffer_now;
3260                             uint32_t total_storage = (sizeof(l2cap_ertm_rx_packet_state_t) + channel->local_mps) * channel->num_rx_buffers + tx_storage + channel->local_mtu;
3261                             l2cap_ertm_setup_buffers(channel, (uint8_t *) channel->rx_packets_state, total_storage);
3262                         }
3263                         // limit remote mtu by our tx buffers. Include 2 bytes SDU Length
3264                         uint16_t effective_mtu = channel->remote_mps * channel->num_tx_buffers - 2;
3265                         channel->remote_mtu    = btstack_min( effective_mtu, channel->remote_mtu);
3266                     }
3267                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
3268                         channel->remote_tx_window_size,
3269                         channel->remote_max_transmit,
3270                         channel->remote_retransmission_timeout_ms,
3271                         channel->remote_monitor_timeout_ms,
3272                         channel->remote_mps);
3273                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
3274                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3275                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3276                     } else {
3277                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
3278                     }
3279                     break;
3280                 case L2CAP_CHANNEL_MODE_BASIC:
3281                     switch (mode){
3282                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
3283                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
3284                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
3285                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3286                             }
3287                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
3288                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
3289                             break;
3290                         default: // case L2CAP_CHANNEL_MODE_BASIC:
3291                             // TODO store and evaluate configuration
3292                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
3293                             break;
3294                     }
3295                     break;
3296                 default:
3297                     break;
3298             }
3299         }
3300         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
3301             use_fcs = command[pos];
3302         }
3303 #endif
3304         // check for unknown options
3305         if ((option_hint == 0) && ((option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) || (option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE))){
3306             log_info("l2cap cid %u, unknown option 0x%02x", channel->local_cid, option_type);
3307             channel->unknown_option = option_type;
3308             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
3309         }
3310         pos += length;
3311     }
3312 
3313 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3314         // "FCS" has precedence over "No FCS"
3315         uint8_t update = channel->fcs_option || use_fcs;
3316         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
3317         channel->fcs_option = update;
3318         // If ERTM mandatory, but remote didn't send Retransmission and Flowcontrol options -> disconnect
3319         if (((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM) == 0) & (channel->ertm_mandatory)){
3320             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3321         }
3322 #endif
3323 }
3324 
3325 // @pre command len is valid, see check in l2cap_signaling_handler_channel
3326 static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint16_t result, uint8_t *command){
3327     log_info("l2cap_signaling_handle_configure_response");
3328 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3329     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3330     uint16_t pos     = 10;
3331     while (pos < end_pos){
3332         uint8_t option_hint = command[pos] >> 7;
3333         uint8_t option_type = command[pos] & 0x7f;
3334         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
3335         pos++;
3336         uint8_t length = command[pos++];
3337 
3338         // Retransmission and Flow Control Option
3339         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
3340             switch (channel->mode){
3341                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
3342                     if (channel->ertm_mandatory){
3343                         // ??
3344                     } else {
3345                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
3346                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
3347                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3348                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3349                         }
3350                     }
3351                     break;
3352                 case L2CAP_CHANNEL_MODE_BASIC:
3353                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
3354                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
3355                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3356                     }
3357                     break;
3358                 default:
3359                     break;
3360             }
3361         }
3362 
3363         // check for unknown options
3364         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
3365             log_info("l2cap cid %u, unknown option 0x%02x", channel->local_cid, option_type);
3366             channel->unknown_option = option_type;
3367             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
3368         }
3369 
3370         pos += length;
3371     }
3372 #else
3373     UNUSED(channel);  // ok: no code
3374     UNUSED(result);   // ok: no code
3375     UNUSED(command);  // ok: no code
3376 #endif
3377 }
3378 
3379 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
3380     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
3381     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
3382     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
3383     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
3384     if (channel->state == L2CAP_STATE_OPEN) return 0;
3385     return 1;
3386 }
3387 
3388 
3389 // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
3390 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
3391 
3392     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3393     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
3394     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3395     uint16_t result = 0;
3396 
3397     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
3398 
3399     // handle DISCONNECT REQUESTS seperately
3400     if (code == DISCONNECTION_REQUEST){
3401         l2cap_handle_disconnect_request(channel, identifier);
3402         return;
3403     }
3404 
3405     // @STATEMACHINE(l2cap)
3406     switch (channel->state) {
3407 
3408         case L2CAP_STATE_WAIT_CONNECT_RSP:
3409             switch (code){
3410                 case CONNECTION_RESPONSE:
3411                     if (cmd_len < 8){
3412                         // command imcomplete
3413                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3414                         break;
3415                     }
3416                     l2cap_stop_rtx(channel);
3417                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3418                     switch (result) {
3419                         case 0:
3420                             // successful connection
3421                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3422                             channel->state = L2CAP_STATE_CONFIG;
3423                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
3424                             break;
3425                         case 1:
3426                             // connection pending. get some coffee, but start the ERTX
3427                             l2cap_start_ertx(channel);
3428                             break;
3429                         default:
3430                             // channel closed
3431                             channel->state = L2CAP_STATE_CLOSED;
3432                             // map l2cap connection response result to BTstack status enumeration
3433                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
3434 
3435                             // drop link key if security block
3436                             if ((L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result) == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
3437                                 gap_drop_link_key_for_bd_addr(channel->address);
3438                             }
3439 
3440                             // discard channel
3441                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3442                             l2cap_free_channel_entry(channel);
3443                             break;
3444                     }
3445                     break;
3446 
3447                 default:
3448                     //@TODO: implement other signaling packets
3449                     break;
3450             }
3451             break;
3452 
3453         case L2CAP_STATE_CONFIG:
3454             switch (code) {
3455                 case CONFIGURE_REQUEST:
3456                     if (cmd_len < 4){
3457                         // command incomplete
3458                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3459                         break;
3460                     }
3461                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
3462                     l2cap_signaling_handle_configure_request(channel, command);
3463                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
3464                         // only done if continuation not set
3465                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
3466                     }
3467                     break;
3468                 case CONFIGURE_RESPONSE:
3469                     if (cmd_len < 6){
3470                         // command incomplete
3471                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3472                         break;
3473                     }
3474                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3475                     l2cap_stop_rtx(channel);
3476                     l2cap_signaling_handle_configure_response(channel, result, command);
3477                     switch (result){
3478                         case 0: // success
3479                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
3480                             break;
3481                         case 4: // pending
3482                             l2cap_start_ertx(channel);
3483                             break;
3484                         default:
3485 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3486                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
3487                                 // remote does not offer ertm but it's required
3488                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3489                                 break;
3490                             }
3491 #endif
3492                             // retry on negative result
3493                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
3494                             break;
3495                     }
3496                     break;
3497                 default:
3498                     break;
3499             }
3500             if (l2cap_channel_ready_for_open(channel)){
3501 
3502 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3503                 // assert that packet can be stored in fragment buffers in ertm
3504                 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3505                     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
3506                     uint16_t usable_mtu = channel->num_tx_buffers == 1 ? effective_mps : channel->num_tx_buffers * effective_mps - 2;
3507                     if (usable_mtu < channel->remote_mtu){
3508                         log_info("Remote MTU %u > max storable ERTM packet, only using MTU = %u", channel->remote_mtu, usable_mtu);
3509                         channel->remote_mtu = usable_mtu;
3510                     }
3511                 }
3512 #endif
3513                 // for open:
3514                 channel->state = L2CAP_STATE_OPEN;
3515                 l2cap_emit_channel_opened(channel, 0);
3516             }
3517             break;
3518 
3519         case L2CAP_STATE_WAIT_DISCONNECT:
3520             switch (code) {
3521                 case DISCONNECTION_RESPONSE:
3522                     l2cap_finalize_channel_close(channel);
3523                     break;
3524                 default:
3525                     //@TODO: implement other signaling packets
3526                     break;
3527             }
3528             break;
3529 
3530         case L2CAP_STATE_CLOSED:
3531             // @TODO handle incoming requests
3532             break;
3533 
3534         case L2CAP_STATE_OPEN:
3535             //@TODO: implement other signaling packets, e.g. re-configure
3536             break;
3537         default:
3538             break;
3539     }
3540     // log_info("new state %u", channel->state);
3541 }
3542 
3543 #ifdef ENABLE_CLASSIC
3544 static void l2cap_handle_information_request_complete(hci_connection_t * connection){
3545 
3546     connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
3547 
3548     // emit event
3549     uint8_t event[8];
3550     event[0] = L2CAP_EVENT_INFORMATION_RESPONSE;
3551     event[1] = sizeof(event) - 2;
3552     little_endian_store_16(event, 2, connection->con_handle);
3553     little_endian_store_16(event, 4, connection->l2cap_state.extended_feature_mask);
3554     little_endian_store_16(event, 6, connection->l2cap_state.fixed_channels_supported);
3555     l2cap_emit_event(event, sizeof(event));
3556 
3557     // trigger connection request
3558     btstack_linked_list_iterator_t it;
3559     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3560     while (btstack_linked_list_iterator_has_next(&it)){
3561         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3562         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3563         if (channel->con_handle != connection->con_handle) continue;
3564 
3565         // incoming connection: information request was triggered after user has accepted connection,
3566         // now: verify channel configuration, esp. if ertm will be mandatory
3567         if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
3568             // default: continue
3569             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
3570 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3571             if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
3572                 // ERTM not possible, select basic mode and release buffer
3573                 channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3574                 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3575 
3576                 // bail if ERTM is mandatory
3577                 if (channel->ertm_mandatory){
3578                     // We chose 'no resources available' for "ERTM mandatory but you don't even know ERTM exists"
3579                     log_info("ERTM mandatory -> reject connection");
3580                     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
3581                     channel->reason = L2CAP_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE;
3582                 }  else {
3583                     log_info("ERTM not supported by remote -> use Basic mode");
3584                 }
3585             }
3586 #endif
3587             continue;
3588         }
3589 
3590         // outgoing connection: information request is triggered before connection request
3591         if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
3592 
3593 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3594             // if ERTM was requested, but is not listed in extended feature mask:
3595             if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
3596 
3597                 if (channel->ertm_mandatory){
3598                     // bail if ERTM is mandatory
3599                     channel->state = L2CAP_STATE_CLOSED;
3600                     // map l2cap connection response result to BTstack status enumeration
3601                     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
3602                     // discard channel
3603                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3604                     l2cap_free_channel_entry(channel);
3605                     continue;
3606 
3607                 } else {
3608                     // fallback to Basic mode
3609                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3610                     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3611                 }
3612             }
3613 #endif
3614 
3615             // respond to connection request
3616             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
3617             continue;
3618         }
3619     }
3620 }
3621 #endif
3622 
3623 // @pre command len is valid, see check in l2cap_acl_classic_handler
3624 static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
3625 
3626     hci_connection_t * connection;
3627     btstack_linked_list_iterator_t it;
3628 
3629     // get code, signal identifier and command len
3630     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3631     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
3632     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3633 
3634     // general commands without an assigned channel
3635     switch(code) {
3636 
3637         case CONNECTION_REQUEST:
3638             if (cmd_len == 4){
3639                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3640                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3641                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
3642             } else {
3643                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3644             }
3645             return;
3646 
3647         case ECHO_REQUEST:
3648             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
3649             return;
3650 
3651         case INFORMATION_REQUEST:
3652             if (cmd_len == 2) {
3653                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3654                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
3655                 return;
3656             }
3657             break;
3658 
3659         case INFORMATION_RESPONSE:
3660             connection = hci_connection_for_handle(handle);
3661             if (!connection) return;
3662             switch (connection->l2cap_state.information_state){
3663                 case L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE:
3664                     // get extended features from response if valid
3665                     if (cmd_len >= 6) {
3666                         uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3667                         uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3668                         if (result == 0 && info_type == L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) {
3669                             connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3670                         }
3671                         log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
3672                         if ((connection->l2cap_state.extended_feature_mask & 0x80) != 0){
3673                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_FIXED_CHANNELS_REQUEST;
3674                         } else {
3675                             // information request complete
3676                             l2cap_handle_information_request_complete(connection);
3677                         }
3678                     }
3679                     break;
3680                 case L2CAP_INFORMATION_STATE_W4_FIXED_CHANNELS_RESPONSE:
3681                     if (cmd_len >= 12) {
3682                         uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3683                         uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3684                         if (result == 0 && info_type == L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED) {
3685                             connection->l2cap_state.fixed_channels_supported = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3686                         }
3687                         log_info("fixed channels mask 0x%02x", connection->l2cap_state.fixed_channels_supported);
3688                         // information request complete
3689                         l2cap_handle_information_request_complete(connection);
3690                     }
3691                     break;
3692                 default:
3693                     break;
3694             }
3695             return;
3696 
3697 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
3698         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
3699         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
3700         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
3701         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
3702             l2cap_ecbm_signaling_handler_dispatch(handle, L2CAP_CID_SIGNALING, command, sig_id);
3703             return;
3704         case L2CAP_FLOW_CONTROL_CREDIT_INDICATION:
3705             // return if valid
3706             if (l2cap_credit_based_handle_credit_indication(handle, command, cmd_len)) return;
3707             break;
3708 
3709         case COMMAND_REJECT:
3710             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3711             while (btstack_linked_list_iterator_has_next(&it)) {
3712                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3713                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3714                 if (channel->con_handle != handle) continue;
3715                 if (channel->local_sig_id != sig_id) continue;
3716                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE) continue;
3717 
3718                 // open failed
3719                 channel->state = L2CAP_STATE_CLOSED;
3720                 l2cap_ecbm_emit_channel_opened(channel,
3721                                                ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES);
3722                 // drop failed channel
3723                 btstack_linked_list_iterator_remove(&it);
3724                 l2cap_free_channel_entry(channel);
3725             }
3726             break;
3727 #endif
3728 
3729         default:
3730             break;
3731     }
3732 
3733     // Get potential destination CID
3734     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3735 
3736     // Find channel for this sig_id and connection handle
3737     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3738     while (btstack_linked_list_iterator_has_next(&it)){
3739         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3740         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3741         if (channel->con_handle != handle) continue;
3742         if (code & 1) {
3743             // match odd commands (responses) by previous signaling identifier
3744             if (channel->local_sig_id == sig_id) {
3745                 l2cap_signaling_handler_channel(channel, command);
3746                 return;
3747             }
3748         } else {
3749             // match even commands (requests) by local channel id
3750             if (channel->local_cid == dest_cid) {
3751                 l2cap_signaling_handler_channel(channel, command);
3752                 return;
3753             }
3754         }
3755     }
3756 
3757     // send command reject
3758     l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3759 }
3760 #endif
3761 
3762 #ifdef L2CAP_USES_CHANNELS
3763 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3764     btstack_linked_list_iterator_t it;
3765     btstack_linked_list_iterator_init(&it, services);
3766     while (btstack_linked_list_iterator_has_next(&it)){
3767         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
3768         if ( service->psm == psm){
3769             return service;
3770         };
3771     }
3772     return NULL;
3773 }
3774 #endif
3775 
3776 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
3777 
3778 static uint8_t l2cap_ecbm_setup_channels(btstack_linked_list_t * channels,
3779                                          btstack_packet_handler_t packet_handler, uint8_t num_channels,
3780                                          hci_connection_t * connection, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
3781     uint8_t i;
3782     uint8_t status = ERROR_CODE_SUCCESS;
3783     for (i=0;i<num_channels;i++){
3784         l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_ECBM, connection->address, connection->address_type, psm, mtu, security_level);
3785         if (!channel) {
3786             status = BTSTACK_MEMORY_ALLOC_FAILED;
3787             break;
3788         }
3789         channel->con_handle = connection->con_handle;
3790         btstack_linked_list_add_tail(channels, (btstack_linked_item_t *) channel);
3791     }
3792 
3793     // free channels if not all allocated
3794     if (status != ERROR_CODE_SUCCESS){
3795         while (true) {
3796             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_pop(channels);
3797             if (channel == NULL) break;
3798             l2cap_free_channel_entry(channel);
3799         }
3800     }
3801 
3802     return status;
3803 }
3804 
3805 static inline l2cap_service_t * l2cap_ecbm_get_service(uint16_t spsm){
3806     return l2cap_get_service_internal(&l2cap_enhanced_services, spsm);
3807 }
3808 
3809 static inline uint8_t l2cap_ecbm_status_for_result(uint16_t result) {
3810     switch (result) {
3811         case L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS:
3812             return ERROR_CODE_SUCCESS;
3813         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_SPSM_NOT_SUPPORTED:
3814             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_PSM;
3815         case L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INSUFFICIENT_RESOURCES_AVAILABLE:
3816             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_RESOURCES;
3817         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHENTICATION:
3818         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHORIZATION:
3819         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_ENCYRPTION_KEY_SIZE_TOO_SHORT:
3820         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_ENCRYPTION:
3821             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY;
3822         default:
3823             // invalid Source CID, Source CID already allocated, unacceptable parameters
3824             return L2CAP_CONNECTION_RESPONSE_UNKNOWN_ERROR;
3825     }
3826 }
3827 
3828 static void
3829 l2cap_ecbm_emit_incoming_connection(l2cap_channel_t *channel, uint8_t num_channels) {
3830     uint8_t event[16];
3831     event[0] = L2CAP_EVENT_ECBM_INCOMING_CONNECTION;
3832     event[1] = sizeof(event) - 2;
3833     event[2] = channel->address_type;
3834     reverse_bd_addr(channel->address, &event[3]);
3835     little_endian_store_16(event, 9, channel->con_handle);
3836     little_endian_store_16(event, 11, channel->psm);
3837     event[13] = num_channels;
3838     little_endian_store_16(event, 14, channel->local_cid);
3839     hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
3840     (*channel->packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
3841 }
3842 
3843 static uint8_t
3844 l2cap_ecbm_security_status_for_connection_request(hci_con_handle_t handle, gap_security_level_t required_security_level,
3845                                                   bool requires_authorization) {
3846     // check security in increasing error priority
3847     uint8_t security_status = L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS;
3848 
3849     // security: check encryption
3850     if (required_security_level >= LEVEL_2) {
3851         if (gap_encryption_key_size(handle) < 16) {
3852             security_status = L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_ENCYRPTION_KEY_SIZE_TOO_SHORT;
3853         }
3854         if (gap_encryption_key_size(handle) == 0){
3855             security_status = L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_ENCRYPTION;
3856         }
3857     }
3858 
3859     // security: check authentication
3860     if (required_security_level >= LEVEL_3) {
3861         if (!gap_authenticated(handle)) {
3862             security_status = requires_authorization ?
3863                     L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHORIZATION :
3864                     L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHENTICATION;
3865         }
3866     }
3867     return security_status;
3868 }
3869 
3870 static void l2cap_ecbm_handle_security_level_incoming(l2cap_channel_t * channel){
3871     // count number of l2cap_channels in state L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE with same remote_sig_id
3872     uint8_t sig_id = channel->remote_sig_id;
3873     hci_con_handle_t con_handle = channel->con_handle;
3874 
3875     uint8_t security_status = l2cap_ecbm_security_status_for_connection_request(channel->con_handle,
3876                                                                                 channel->required_security_level,
3877                                                                                 false);
3878     bool security_sufficient = security_status == L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS;
3879 
3880     uint8_t num_channels = 0;
3881     btstack_linked_list_iterator_t it;
3882     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3883     while (btstack_linked_list_iterator_has_next(&it)) {
3884         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3885         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3886         if (channel->con_handle != con_handle) continue;
3887         if (channel->remote_sig_id != sig_id) continue;
3888         if (channel->state != L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE) continue;
3889         num_channels++;
3890 
3891         if (security_sufficient){
3892             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
3893         } else {
3894             btstack_linked_list_iterator_remove(&it);
3895             btstack_memory_l2cap_channel_free(channel);
3896         }
3897     }
3898 
3899     if (security_sufficient){
3900         l2cap_ecbm_emit_incoming_connection(channel, num_channels);
3901     } else {
3902         // combine signaling cid and number channels for l2cap_register_signaling_response
3903         uint16_t signaling_cid = L2CAP_CID_SIGNALING;
3904         uint16_t num_channels_and_signaling_cid = (num_channels << 8) | signaling_cid;
3905         l2cap_register_signaling_response(con_handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3906                                           num_channels_and_signaling_cid, security_status);
3907     }
3908 }
3909 
3910 void l2cap_ecbm_trigger_pending_connection_responses(hci_con_handle_t con_handle){
3911     bool done = false;
3912     while (!done) {
3913         done = true;
3914         btstack_linked_list_iterator_t it;
3915         btstack_linked_list_iterator_init(&it, &l2cap_channels);
3916         while (btstack_linked_list_iterator_has_next(&it)) {
3917             l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3918             if (channel->channel_type != L2CAP_CHANNEL_TYPE_CHANNEL_ECBM) continue;
3919             if (channel->con_handle != con_handle) continue;
3920             if  (channel->state == L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE) {
3921                 l2cap_ecbm_handle_security_level_incoming(channel);
3922                 done = false;
3923             };
3924         }
3925     }
3926 }
3927 
3928 static int l2cap_ecbm_signaling_handler_dispatch(hci_con_handle_t handle, uint16_t signaling_cid, uint8_t *command,
3929                                                  uint8_t sig_id) {
3930 
3931     hci_connection_t *connection;
3932     btstack_linked_list_iterator_t it;
3933     l2cap_service_t *service;
3934     uint16_t spsm;
3935     uint8_t num_channels;
3936     uint16_t num_channels_and_signaling_cid;
3937     uint8_t i;
3938     uint16_t new_mtu;
3939     uint16_t new_mps;
3940     uint16_t initial_credits;
3941     uint16_t result;
3942     uint8_t status;
3943 
3944     uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3945     uint16_t len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3946     log_info("enhanced dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
3947 
3948     switch (code) {
3949         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
3950             // check size
3951             if (len < 10u) return 0u;
3952 
3953             // get hci connection, bail if not found (must not happen)
3954             connection = hci_connection_for_handle(handle);
3955             btstack_assert(connection != NULL);
3956 
3957             // get num channels to establish
3958             num_channels = (len - 8) / sizeof(uint16_t);
3959 
3960             // combine signaling cid and number channels for l2cap_register_signaling_response
3961             num_channels_and_signaling_cid = (num_channels << 8) | signaling_cid;
3962 
3963             // check if service registered
3964             spsm = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3965             service = l2cap_ecbm_get_service(spsm);
3966 
3967             if (service) {
3968 
3969                 uint16_t remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3970                 uint16_t remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3971                 uint16_t credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
3972 
3973                 // param: check remote mtu
3974                 if (service->mtu > remote_mtu) {
3975                     l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3976                                                       num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INVALID_PARAMETERS);
3977                     return 1;
3978                 }
3979 
3980                 // check if authentication is required and possible
3981                 bool send_pending = false;
3982                 uint8_t security_status = l2cap_ecbm_security_status_for_connection_request(handle,
3983                                                                                             service->required_security_level,
3984                                                                                             service->requires_authorization);
3985                 if (security_status != L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS) {
3986                     if (gap_get_bondable_mode() != 0) {
3987                         // if possible, send pending and continue
3988                         send_pending = true;
3989                     } else {
3990                         // otherwise, send refused and abort
3991                         l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3992                                                           num_channels_and_signaling_cid, security_status);
3993                         return 1;
3994                     }
3995                 }
3996 
3997                 // report the last result code != 0
3998                 result = 0;
3999                 // store one of the local channels for the event
4000                 l2cap_channel_t * a_channel = NULL;
4001                 for (i = 0; i < num_channels; i++) {
4002 
4003                     // check source cids
4004                     uint16_t source_cid = little_endian_read_16(command, 12 + (i * 2));
4005                     if (source_cid < 0x40u) {
4006                         result = L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INVALID_SOURCE_CID;
4007                         continue;
4008                     }
4009 
4010                     // go through list of channels for this ACL connection and check if we get a match
4011                     btstack_linked_list_iterator_init(&it, &l2cap_channels);
4012                     bool source_cid_allocated = false;
4013                     while (btstack_linked_list_iterator_has_next(&it)) {
4014                         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4015                         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4016                         if (channel->con_handle != handle) continue;
4017                         if (channel->remote_cid != source_cid) continue;
4018                         source_cid_allocated = true;
4019                         break;
4020                     }
4021                     if (source_cid_allocated) {
4022                         result = 0x00a;
4023                         continue;
4024                     }
4025 
4026                     // setup channel
4027                     l2cap_channel_t *channel = l2cap_create_channel_entry(service->packet_handler,
4028                                                                           L2CAP_CHANNEL_TYPE_CHANNEL_ECBM,
4029                                                                           connection->address,
4030                                                                           connection->address_type, spsm,
4031                                                                           service->mtu,
4032                                                                           service->required_security_level);
4033 
4034                     if (channel == NULL) {
4035                         // Some connections refused – insufficient resources available
4036                         result = 0x004;
4037                         continue;
4038                     }
4039 
4040                     // setup state
4041                     channel->state = L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
4042                     channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
4043                     channel->con_handle = connection->con_handle;
4044                     channel->remote_sig_id = sig_id;
4045                     channel->remote_cid = source_cid;
4046                     channel->remote_mtu = remote_mtu;
4047                     channel->remote_mps = remote_mps;
4048                     channel->credits_outgoing = credits_outgoing;
4049                     channel->cid_index = i;
4050                     channel->num_cids = num_channels;
4051 
4052                     // if more than one error, we can report any of them
4053                     channel->reason = result;
4054 
4055                     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
4056 
4057                     a_channel = channel;
4058                 }
4059 
4060                 // if no channels have been created, all have been refused, and we can respond right away
4061                 if (a_channel == NULL) {
4062                     l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
4063                                                       num_channels_and_signaling_cid, result);
4064                     return 1;
4065                 }
4066 
4067                 // if security is pending, send intermediate response, otherwise, ask user
4068                 if (send_pending){
4069                     l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
4070                                                       num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_PENDING_AUTHENTICATION);
4071                 } else {
4072                     // if security is ok but authorization is required, send intermediate response and ask user
4073                     if (service->requires_authorization){
4074                         l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
4075                                                           num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_PENDING_AUTHORIZATION);
4076                     }
4077                     l2cap_ecbm_handle_security_level_incoming(a_channel);
4078                 }
4079 
4080             } else {
4081                 l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
4082                                                   num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_SPSM_NOT_SUPPORTED);
4083             }
4084             return 1;
4085 
4086         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
4087             // check size
4088             if (len < 10u) return 0u;
4089 
4090             // get hci connection, ignore if not found
4091             connection = hci_connection_for_handle(handle);
4092             if (connection == NULL) return 0;
4093 
4094             // get channel config: mtu, mps, initial credits, result
4095             new_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4096             new_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
4097             initial_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
4098             result = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
4099             status = l2cap_ecbm_status_for_result(result);
4100 
4101             // get num channels to modify
4102             num_channels = (len - 8) / sizeof(uint16_t);
4103             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4104             while (btstack_linked_list_iterator_has_next(&it)) {
4105                 uint8_t channel_status = status;
4106                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4107                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4108                 if (channel->con_handle != handle) continue;
4109                 if (channel->local_sig_id != sig_id) continue;
4110                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE) continue;
4111                 if (channel->cid_index < num_channels) {
4112                     uint16_t remote_cid = little_endian_read_16(command, 12 + channel->cid_index * sizeof(uint16_t));
4113                     if (remote_cid != 0) {
4114                         // check for duplicate remote CIDs
4115                         l2cap_channel_t * original_channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
4116                         if (original_channel == NULL){
4117                             channel->state = L2CAP_STATE_OPEN;
4118                             channel->remote_cid = remote_cid;
4119                             channel->remote_mtu = new_mtu;
4120                             channel->remote_mps = new_mps;
4121                             channel->credits_outgoing = initial_credits;
4122                             l2cap_ecbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
4123                             continue;
4124                         }
4125                         // close original channel
4126                         original_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4127                         channel_status = ERROR_CODE_ACL_CONNECTION_ALREADY_EXISTS;
4128                     }
4129                 }
4130                 // open failed
4131                 l2cap_ecbm_emit_channel_opened(channel, channel_status);
4132                 // drop failed channel
4133                 btstack_linked_list_iterator_remove(&it);
4134                 btstack_memory_l2cap_channel_free(channel);
4135             }
4136             return 1;
4137 
4138         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
4139             // check minimal size
4140             if (len < 6) return 0u;
4141 
4142             // get hci connection, bail if not found (must not happen)
4143             connection = hci_connection_for_handle(handle);
4144             btstack_assert(connection != NULL);
4145 
4146             // get num channels to modify
4147             num_channels = (len - 4) / sizeof(uint16_t);
4148 
4149             // get new mtu and mps
4150             new_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4151             new_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
4152 
4153             // validate request
4154             result = 0;
4155             for (i = 0; i < num_channels; i++) {
4156                 // check cid
4157                 uint16_t remote_cid = little_endian_read_16(command, 8 + (i * sizeof(uint16_t)));
4158                 l2cap_channel_t *channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
4159                 if (channel == NULL) {
4160                     result = L2CAP_ECBM_RECONFIGURE_FAILED_DESTINATION_CID_INVALID;
4161                     break;
4162                 }
4163                 // check MTU is not reduced
4164                 if (channel->remote_mtu > new_mtu) {
4165                     result = L2CAP_ECBM_RECONFIGURE_FAILED_MTU_REDUCTION_NOT_ALLOWED;
4166                     break;
4167                 }
4168                 // check MPS reduction
4169                 if ((num_channels > 1) && (channel->remote_mps > new_mps)) {
4170                     result = L2CAP_ECBM_RECONFIGURE_FAILED_MPS_REDUCTION_MULTIPLE_CHANNELS;
4171                     break;
4172                 }
4173                 // check MPS valid
4174                 if (new_mps < l2cap_enhanced_mps_min) {
4175                     result = L2CAP_ECBM_RECONFIGURE_FAILED_UNACCEPTABLE_PARAMETERS;
4176                     break;
4177                 }
4178             }
4179 
4180             // send reject
4181             if (result != 0) {
4182                 l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST, sig_id, signaling_cid,
4183                                                   result);
4184                 return 1;
4185             }
4186 
4187             // update channels
4188             for (i = 0; i < num_channels; i++) {
4189                 uint16_t remote_cid = little_endian_read_16(command, 8 + (i * sizeof(uint16_t)));
4190                 l2cap_channel_t *channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
4191                 channel->remote_mps = new_mps;
4192                 channel->remote_mtu = new_mtu;
4193                 // emit event
4194                 uint8_t event[8];
4195                 event[0] = L2CAP_EVENT_ECBM_RECONFIGURED;
4196                 event[1] = sizeof(event) - 2;
4197                 little_endian_store_16(event, 2, channel->local_cid);
4198                 little_endian_store_16(event, 4, new_mtu);
4199                 little_endian_store_16(event, 6, new_mps);
4200                 l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
4201             }
4202 
4203             // send accept
4204             l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST, sig_id, signaling_cid, 0);
4205             return 1;
4206 
4207         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
4208             // check size
4209             if (len < 2u) return 0u;
4210 
4211             result = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4212             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4213             while (btstack_linked_list_iterator_has_next(&it)) {
4214                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4215                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4216                 if (channel->con_handle != handle) continue;
4217                 if (channel->local_sig_id != sig_id) continue;
4218                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_RENEGOTIATION_RESPONSE) continue;
4219                 // complete request
4220                 if (result == 0) {
4221                     channel->receive_sdu_buffer = channel->renegotiate_sdu_buffer;
4222                     channel->local_mtu = channel->renegotiate_mtu;
4223                 }
4224                 channel->state = L2CAP_STATE_OPEN;
4225                 // emit event
4226                 l2cap_ecbm_emit_reconfigure_complete(channel, result);
4227             }
4228             break;
4229 
4230         default:
4231             btstack_unreachable();
4232             break;
4233     }
4234     return 0;
4235 }
4236 
4237 #endif
4238 
4239 #ifdef ENABLE_BLE
4240 
4241 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
4242     uint8_t event[6];
4243     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
4244     event[1] = 4;
4245     little_endian_store_16(event, 2, con_handle);
4246     little_endian_store_16(event, 4, result);
4247     l2cap_emit_event(event, sizeof(event));
4248 }
4249 
4250 // @return valid
4251 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
4252     hci_connection_t * connection;
4253     uint16_t result;
4254     uint8_t  event[12];
4255 
4256 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4257     l2cap_channel_t * channel;
4258     btstack_linked_list_iterator_t it;
4259 #endif
4260 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4261     uint16_t local_cid;
4262     uint16_t le_psm;
4263     l2cap_service_t * service;
4264     uint16_t source_cid;
4265 #endif
4266 
4267     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
4268     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
4269     log_info("le dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
4270 
4271     switch (code){
4272 
4273         case CONNECTION_PARAMETER_UPDATE_REQUEST:
4274             // check size
4275             if (len < 8u) return 0u;
4276             connection = hci_connection_for_handle(handle);
4277             if (connection != NULL){
4278                 if (connection->role != HCI_ROLE_MASTER){
4279                     // reject command without notifying upper layer when not in master role
4280                     return 0;
4281                 }
4282                 le_connection_parameter_range_t existing_range;
4283                 gap_get_connection_parameter_range(&existing_range);
4284                 uint16_t le_conn_interval_min   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
4285                 uint16_t le_conn_interval_max   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
4286                 uint16_t le_conn_latency        = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
4287                 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
4288 
4289                 int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
4290                 if (update_parameter){
4291                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
4292                     connection->le_conn_interval_min = le_conn_interval_min;
4293                     connection->le_conn_interval_max = le_conn_interval_max;
4294                     connection->le_conn_latency = le_conn_latency;
4295                     connection->le_supervision_timeout = le_supervision_timeout;
4296                 } else {
4297                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
4298                 }
4299                 connection->le_con_param_update_identifier = sig_id;
4300             }
4301 
4302             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
4303             event[1] = 10;
4304             little_endian_store_16(event, 2, handle);
4305             (void)memcpy(&event[4], &command[4], 8);
4306             l2cap_emit_event(event, sizeof(event));
4307             break;
4308 
4309         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
4310             // check size
4311             if (len < 2u) return 0u;
4312             result = little_endian_read_16(command, 4);
4313             l2cap_emit_connection_parameter_update_response(handle, result);
4314             break;
4315 
4316 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
4317         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
4318         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
4319         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
4320         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
4321             return l2cap_ecbm_signaling_handler_dispatch(handle, L2CAP_CID_SIGNALING_LE, command, sig_id);
4322 #endif
4323 
4324 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4325         case COMMAND_REJECT:
4326             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4327             while (btstack_linked_list_iterator_has_next(&it)){
4328                 channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4329                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4330                 if (channel->con_handle   != handle) continue;
4331                 if (channel->local_sig_id != sig_id) continue;
4332 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4333                 // if received while waiting for le connection response, assume legacy device
4334                 if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
4335                     channel->state = L2CAP_STATE_CLOSED;
4336                     // no official value for this, use: Connection refused – LE_PSM not supported
4337                     l2cap_cbm_emit_channel_opened(channel, L2CAP_CBM_CONNECTION_RESULT_SPSM_NOT_SUPPORTED);
4338 
4339                     // discard channel
4340                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4341                     l2cap_free_channel_entry(channel);
4342                     continue;
4343                 }
4344 #endif
4345 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
4346                 // if received while waiting for le connection response, assume legacy device
4347                 if (channel->state == L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE){
4348                     channel->state = L2CAP_STATE_CLOSED;
4349                     // treat as SPSM not supported
4350                     l2cap_ecbm_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_PSM);
4351 
4352                     // discard channel
4353                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4354                     l2cap_free_channel_entry(channel);
4355                     continue;
4356                 }
4357 #endif
4358             }
4359             break;
4360 #endif
4361 
4362 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4363         case LE_CREDIT_BASED_CONNECTION_REQUEST:
4364             // check size
4365             if (len < 10u) return 0u;
4366 
4367             // get hci connection, bail if not found (must not happen)
4368             connection = hci_connection_for_handle(handle);
4369             if (!connection) return 0;
4370 
4371             // check if service registered
4372             le_psm  = little_endian_read_16(command, 4);
4373             service = l2cap_cbm_get_service(le_psm);
4374             source_cid = little_endian_read_16(command, 6);
4375 
4376             if (service){
4377                 if (source_cid < 0x40u){
4378                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INVALID_SOURCE_CID);
4379                     return 1;
4380                 }
4381 
4382                 // go through list of channels for this ACL connection and check if we get a match
4383                 btstack_linked_list_iterator_init(&it, &l2cap_channels);
4384                 while (btstack_linked_list_iterator_has_next(&it)){
4385                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4386                     if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
4387                     if (a_channel->con_handle != handle) continue;
4388                     if (a_channel->remote_cid != source_cid) continue;
4389                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_SOURCE_CID_ALREADY_ALLOCATED);
4390                     return 1;
4391                 }
4392 
4393                 // security: check encryption
4394                 if (service->required_security_level >= LEVEL_2){
4395                     if (gap_encryption_key_size(handle) == 0){
4396                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_ENCRYPTION);
4397                         return 1;
4398                     }
4399                     // anything less than 16 byte key size is insufficient
4400                     if (gap_encryption_key_size(handle) < 16){
4401                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_ENCYRPTION_KEY_SIZE_TOO_SHORT);
4402                         return 1;
4403                     }
4404                 }
4405 
4406                 // security: check authentication
4407                 if (service->required_security_level >= LEVEL_3){
4408                     if (!gap_authenticated(handle)){
4409                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHENTICATION);
4410                         return 1;
4411                     }
4412                 }
4413 
4414                 // security: check authorization
4415                 if (service->required_security_level >= LEVEL_4){
4416                     if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
4417                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHORIZATION);
4418                         return 1;
4419                     }
4420                 }
4421 
4422                 // allocate channel
4423                 channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_CBM, connection->address,
4424                                                      BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
4425                 if (!channel){
4426                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE);
4427                     return 1;
4428                 }
4429 
4430                 channel->con_handle = handle;
4431                 channel->remote_cid = source_cid;
4432                 channel->remote_sig_id = sig_id;
4433                 channel->remote_mtu = little_endian_read_16(command, 8);
4434                 channel->remote_mps = little_endian_read_16(command, 10);
4435                 channel->credits_outgoing = little_endian_read_16(command, 12);
4436 
4437                 // set initial state
4438                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
4439                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
4440 
4441                 // add to connections list
4442                 btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
4443 
4444                 // post connection request event
4445                 l2cap_cbm_emit_incoming_connection(channel);
4446 
4447             } else {
4448                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_SPSM_NOT_SUPPORTED);
4449             }
4450             break;
4451 
4452         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
4453             // check size
4454             if (len < 10u) return 0u;
4455 
4456             // Find channel for this sig_id and connection handle
4457             channel = NULL;
4458             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4459             while (btstack_linked_list_iterator_has_next(&it)){
4460                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4461                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
4462                 if (a_channel->con_handle   != handle) continue;
4463                 if (a_channel->local_sig_id != sig_id) continue;
4464                 channel = a_channel;
4465                 break;
4466             }
4467             if (!channel) break;
4468 
4469             // cid + 0
4470             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
4471             if (result){
4472                 channel->state = L2CAP_STATE_CLOSED;
4473                 uint8_t status = l2cap_cbm_status_for_result(result);
4474                 l2cap_cbm_emit_channel_opened(channel, status);
4475 
4476                 // discard channel
4477                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4478                 l2cap_free_channel_entry(channel);
4479                 break;
4480             }
4481 
4482             // success
4483             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4484             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
4485             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
4486             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
4487             channel->state = L2CAP_STATE_OPEN;
4488             l2cap_cbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
4489             break;
4490 #endif
4491 
4492 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4493         case L2CAP_FLOW_CONTROL_CREDIT_INDICATION:
4494             return l2cap_credit_based_handle_credit_indication(handle, command, len) ? 1 : 0;
4495 
4496         case DISCONNECTION_REQUEST:
4497             // check size
4498             if (len < 4u) return 0u;
4499 
4500             // find channel
4501             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4502             channel = l2cap_get_channel_for_local_cid_and_handle(local_cid, handle);
4503             if (!channel) {
4504                 l2cap_register_signaling_response(handle, DISCONNECTION_REQUEST, sig_id,
4505                                                   little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2), local_cid);
4506                 break;
4507             }
4508             channel->remote_sig_id = sig_id;
4509             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
4510             break;
4511 
4512         case DISCONNECTION_RESPONSE:
4513             // check size
4514             if (len < 4u) return 0u;
4515 
4516             // find channel
4517             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4518             channel = l2cap_get_channel_for_local_cid_and_handle(local_cid, handle);
4519             if (!channel) break;
4520             if (channel->local_sig_id == sig_id) {
4521                 if (channel->state == L2CAP_STATE_WAIT_DISCONNECT){
4522                     l2cap_finalize_channel_close(channel);
4523                 }
4524             }
4525             break;
4526 #endif
4527 
4528         default:
4529             // command unknown -> reject command
4530             return 0;
4531     }
4532     return 1;
4533 }
4534 #endif
4535 
4536 #ifdef ENABLE_CLASSIC
4537 static void l2cap_acl_classic_handler_for_channel(l2cap_channel_t * l2cap_channel, uint8_t * packet, uint16_t size){
4538 
4539     // forward data only in OPEN state
4540     if (l2cap_channel->state != L2CAP_STATE_OPEN) return;
4541 
4542 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4543     if (l2cap_channel->channel_type == L2CAP_CHANNEL_TYPE_CHANNEL_ECBM){
4544         l2cap_credit_based_handle_pdu(l2cap_channel, packet, size);
4545         return;
4546     }
4547 #endif
4548 
4549 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
4550     if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
4551 
4552         int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
4553 
4554         // assert control + FCS fields are inside
4555         if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) return;
4556 
4557         if (l2cap_channel->fcs_option){
4558             // verify FCS (required if one side requested it)
4559             uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
4560             uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
4561 
4562 #ifdef L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL
4563             // simulate fcs error
4564             static int counter = 0;
4565             if (++counter == L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL) {
4566                 log_info("Simulate fcs error");
4567                 fcs_calculated++;
4568                 counter = 0;
4569             }
4570 #endif
4571 
4572             if (fcs_calculated == fcs_packet){
4573                 log_info("Packet FCS 0x%04x verified", fcs_packet);
4574             } else {
4575                 log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
4576                 // ERTM State Machine in Bluetooth Spec does not handle 'I-Frame with invalid FCS'
4577                 return;
4578             }
4579         }
4580 
4581         // switch on packet type
4582         uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
4583         uint8_t  req_seq = (control >> 8) & 0x3f;
4584         int final = (control >> 7) & 0x01;
4585         if (control & 1){
4586             // S-Frame
4587             int poll  = (control >> 4) & 0x01;
4588             l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
4589             log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
4590             l2cap_ertm_tx_packet_state_t * tx_state;
4591             switch (s){
4592                 case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
4593                     log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
4594                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4595                     if (poll && final){
4596                         // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
4597                         log_error("P=F=1 in S-Frame");
4598                         break;
4599                     }
4600                     if (poll){
4601                         // check if we did request selective retransmission before <==> we have stored SDU segments
4602                         int i;
4603                         int num_stored_out_of_order_packets = 0;
4604                         for (i=0;i<l2cap_channel->num_rx_buffers;i++){
4605                             int index = l2cap_channel->rx_store_index + i;
4606                             if (index >= l2cap_channel->num_rx_buffers){
4607                                 index -= l2cap_channel->num_rx_buffers;
4608                             }
4609                             l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
4610                             if (!rx_state->valid) continue;
4611                             num_stored_out_of_order_packets++;
4612                         }
4613                         if (num_stored_out_of_order_packets){
4614                             l2cap_channel->send_supervisor_frame_selective_reject = 1;
4615                         } else {
4616                             l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
4617                         }
4618                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
4619                     }
4620                     if (final){
4621                         // Stop-MonitorTimer
4622                         l2cap_ertm_stop_monitor_timer(l2cap_channel);
4623                         // If UnackedFrames > 0 then Start-RetransTimer
4624                         if (l2cap_channel->unacked_frames){
4625                             l2cap_ertm_start_retransmission_timer(l2cap_channel);
4626                         }
4627                         // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
4628                         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4629                     }
4630                     break;
4631                 case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
4632                     log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
4633                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4634                     // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
4635                     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4636                     break;
4637                 case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
4638                     log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
4639                     break;
4640                 case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
4641                     log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
4642                     if (poll){
4643                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4644                     }
4645                     // find requested i-frame
4646                     tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
4647                     if (tx_state){
4648                         log_info("Retransmission for tx_seq %u requested", req_seq);
4649                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
4650                         tx_state->retransmission_requested = 1;
4651                         l2cap_channel->srej_active = 1;
4652                     }
4653                     break;
4654                 default:
4655                     break;
4656             }
4657         } else {
4658             // I-Frame
4659             // get control
4660             l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
4661             uint8_t tx_seq = (control >> 1) & 0x3f;
4662             log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
4663             log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
4664             log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
4665             l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4666             if (final){
4667                 // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
4668                 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4669             }
4670 
4671             // get SDU
4672             const uint8_t * payload_data = &packet[COMPLETE_L2CAP_HEADER+2];
4673             uint16_t        payload_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
4674 
4675             // assert SDU size is smaller or equal to our buffers
4676             uint16_t max_payload_size = 0;
4677             switch (sar){
4678                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
4679                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
4680                     // SDU Length + MPS
4681                     max_payload_size = l2cap_channel->local_mps + 2;
4682                     break;
4683                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
4684                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
4685                     max_payload_size = l2cap_channel->local_mps;
4686                     break;
4687                 default:
4688                     btstack_assert(false);
4689                     break;
4690             }
4691             if (payload_len > max_payload_size){
4692                 log_info("payload len %u > max payload %u -> drop packet", payload_len, max_payload_size);
4693                 return;
4694             }
4695 
4696             // check ordering
4697             if (l2cap_channel->expected_tx_seq == tx_seq){
4698                 log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
4699                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
4700                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
4701 
4702                 // process SDU
4703                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, payload_data, payload_len);
4704 
4705                 // process stored segments
4706                 while (true){
4707                     int index = l2cap_channel->rx_store_index;
4708                     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
4709                     if (!rx_state->valid) break;
4710 
4711                     log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
4712                     l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
4713                     l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
4714 
4715                     rx_state->valid = 0;
4716                     l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
4717 
4718                     // update rx store index
4719                     index++;
4720                     if (index >= l2cap_channel->num_rx_buffers){
4721                         index = 0;
4722                     }
4723                     l2cap_channel->rx_store_index = index;
4724                 }
4725 
4726                 //
4727                 l2cap_channel->send_supervisor_frame_receiver_ready = 1;
4728 
4729             } else {
4730                 int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
4731                 if (delta < 2){
4732                     // store segment
4733                     l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, payload_data, payload_len);
4734 
4735                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
4736                     l2cap_channel->send_supervisor_frame_selective_reject = 1;
4737                 } else {
4738                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
4739                     l2cap_channel->send_supervisor_frame_reject = 1;
4740                 }
4741             }
4742         }
4743         return;
4744     }
4745 #endif
4746 
4747     // check size
4748     uint16_t payload_size = size - COMPLETE_L2CAP_HEADER;
4749     if (l2cap_channel->local_mtu < payload_size) return;
4750 
4751     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], payload_size);
4752 }
4753 #endif
4754 
4755 static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
4756 #ifdef ENABLE_CLASSIC
4757     l2cap_channel_t * l2cap_channel;
4758     l2cap_fixed_channel_t * l2cap_fixed_channel;
4759 
4760     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
4761     uint8_t  broadcast_flag = READ_ACL_FLAGS(packet) >> 2;
4762     switch (channel_id) {
4763 
4764         case L2CAP_CID_SIGNALING: {
4765             if (broadcast_flag != 0) break;
4766             uint32_t command_offset = 8;
4767             while ((command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET) < size) {
4768                 // assert signaling command is fully inside packet
4769                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
4770                 uint32_t next_command_offset = command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
4771                 if (next_command_offset > size){
4772                     log_error("l2cap signaling command len invalid -> drop");
4773                     break;
4774                 }
4775                 // handle signaling command
4776                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
4777                 // go to next command
4778                 command_offset = next_command_offset;
4779             }
4780             break;
4781         }
4782 
4783         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
4784             if (broadcast_flag == 0) break;
4785             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL);
4786             if (!l2cap_fixed_channel) break;
4787             if (!l2cap_fixed_channel->packet_handler) break;
4788             (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4789             break;
4790 
4791 #ifdef ENABLE_BLE
4792         case L2CAP_CID_BR_EDR_SECURITY_MANAGER:
4793             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_BR_EDR_SECURITY_MANAGER);
4794             if ((l2cap_fixed_channel == NULL) || (l2cap_fixed_channel->packet_handler == NULL)){
4795                 // Pairing Failed
4796                 l2cap_register_signaling_response(handle, (uint8_t) SM_PAIRING_FAILED, 0, L2CAP_CID_BR_EDR_SECURITY_MANAGER, SM_REASON_PAIRING_NOT_SUPPORTED);
4797             } else {
4798                 (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4799             }
4800             break;
4801 #endif
4802 
4803         default:
4804             if (broadcast_flag != 0) break;
4805             // Find channel for this channel_id and connection handle
4806             l2cap_channel = l2cap_get_channel_for_local_cid_and_handle(channel_id, handle);
4807             if (l2cap_channel != NULL){
4808                 l2cap_acl_classic_handler_for_channel(l2cap_channel, packet, size);
4809             }
4810             break;
4811     }
4812 #else
4813     UNUSED(handle); // ok: no code
4814     UNUSED(packet); // ok: no code
4815     UNUSED(size);   // ok: no code
4816 #endif
4817 }
4818 
4819 static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
4820 #ifdef ENABLE_BLE
4821 
4822     l2cap_fixed_channel_t * l2cap_fixed_channel;
4823 
4824 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4825     l2cap_channel_t * l2cap_channel;
4826 #endif
4827     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
4828     switch (channel_id) {
4829 
4830         case L2CAP_CID_SIGNALING_LE: {
4831             uint8_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
4832             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
4833             if ((COMPLETE_L2CAP_HEADER + 4u + len) > size) break;
4834             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
4835             if (!valid){
4836                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
4837             }
4838             break;
4839         }
4840 
4841         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
4842             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL);
4843             if (!l2cap_fixed_channel) break;
4844             if (!l2cap_fixed_channel->packet_handler) break;
4845             (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4846             break;
4847 
4848         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
4849             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
4850             if ((l2cap_fixed_channel == NULL) || (l2cap_fixed_channel->packet_handler == NULL)){
4851                 // Pairing Failed
4852                 l2cap_register_signaling_response(handle, (uint8_t) SM_PAIRING_FAILED, 0, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, SM_REASON_PAIRING_NOT_SUPPORTED);
4853             } else {
4854                 (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4855             }
4856             break;
4857 
4858         default:
4859 
4860 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4861             l2cap_channel = l2cap_get_channel_for_local_cid_and_handle(channel_id, handle);
4862             if (l2cap_channel != NULL) {
4863                 l2cap_credit_based_handle_pdu(l2cap_channel, packet, size);
4864             }
4865 #endif
4866             break;
4867     }
4868 #else
4869     UNUSED(handle); // ok: no code
4870     UNUSED(packet); // ok: no code
4871     UNUSED(size);   // ok: no code
4872 #endif
4873 }
4874 
4875 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
4876     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
4877     UNUSED(channel);        // ok: there is no channel
4878 
4879     // Assert full L2CAP header present
4880     if (size < COMPLETE_L2CAP_HEADER) return;
4881 
4882     // Dispatch to Classic or LE handler (SCO packets are not dispatched to L2CAP)
4883     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
4884     hci_connection_t *conn = hci_connection_for_handle(handle);
4885     if (!conn) return;
4886     if (conn->address_type == BD_ADDR_TYPE_ACL){
4887         l2cap_acl_classic_handler(handle, packet, size);
4888     } else {
4889         l2cap_acl_le_handler(handle, packet, size);
4890     }
4891 
4892     l2cap_run();
4893 }
4894 
4895 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
4896 void l2cap_register_fixed_channel(btstack_packet_handler_t packet_handler, uint16_t channel_id) {
4897     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
4898     if (!channel) return;
4899     channel->packet_handler = packet_handler;
4900 }
4901 
4902 #ifdef L2CAP_USES_CHANNELS
4903 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
4904 void l2cap_finalize_channel_close(l2cap_channel_t * channel){
4905     channel->state = L2CAP_STATE_CLOSED;
4906     l2cap_handle_channel_closed(channel);
4907     // discard channel
4908     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4909     l2cap_free_channel_entry(channel);
4910 }
4911 #endif
4912 
4913 #ifdef ENABLE_CLASSIC
4914 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
4915     return l2cap_get_service_internal(&l2cap_services, psm);
4916 }
4917 
4918 static void l2cap_update_minimal_security_level(void){
4919     // update minimal service security level
4920     gap_security_level_t minimal_level = LEVEL_1;
4921     btstack_linked_list_iterator_t it;
4922     btstack_linked_list_iterator_init(&it, &l2cap_services);
4923     while (btstack_linked_list_iterator_has_next(&it)){
4924         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
4925         if (service->required_security_level > minimal_level){
4926             minimal_level = service->required_security_level;
4927         };
4928     }
4929     gap_set_minimal_service_security_level(minimal_level);
4930 }
4931 
4932 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
4933 
4934     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
4935 
4936     // check for alread registered psm
4937     l2cap_service_t *service = l2cap_get_service(psm);
4938     if (service) {
4939         log_error("register: PSM %u already registered", psm);
4940         return L2CAP_SERVICE_ALREADY_REGISTERED;
4941     }
4942 
4943     // alloc structure
4944     service = btstack_memory_l2cap_service_get();
4945     if (!service) {
4946         log_error("register: no memory for l2cap_service_t");
4947         return BTSTACK_MEMORY_ALLOC_FAILED;
4948     }
4949 
4950     // fill in
4951     service->psm = psm;
4952     service->mtu = mtu;
4953     service->packet_handler = service_packet_handler;
4954     service->required_security_level = security_level;
4955 
4956     // add to services list
4957     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
4958 
4959     l2cap_update_minimal_security_level();
4960 
4961 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
4962     // enable page scan
4963     gap_connectable_control(1);
4964 #endif
4965 
4966 
4967     return ERROR_CODE_SUCCESS;
4968 }
4969 
4970 uint8_t l2cap_unregister_service(uint16_t psm){
4971 
4972     log_info("unregister psm 0x%x", psm);
4973 
4974     l2cap_service_t *service = l2cap_get_service(psm);
4975     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
4976     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
4977     btstack_memory_l2cap_service_free(service);
4978 
4979     l2cap_update_minimal_security_level();
4980 
4981 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
4982     // disable page scan when no services registered
4983     if (btstack_linked_list_empty(&l2cap_services)) {
4984         gap_connectable_control(0);
4985     }
4986 #endif
4987 
4988     return ERROR_CODE_SUCCESS;
4989 }
4990 #endif
4991 
4992 
4993 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4994 
4995 static void l2cap_credit_based_send_pdu(l2cap_channel_t *channel) {
4996     btstack_assert(channel != NULL);
4997     btstack_assert(channel->send_sdu_buffer != NULL);
4998     btstack_assert(channel->credits_outgoing > 0);
4999 
5000     // send part of SDU
5001     hci_reserve_packet_buffer();
5002     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
5003     uint8_t *l2cap_payload = acl_buffer + 8;
5004     uint16_t pos = 0;
5005     if (!channel->send_sdu_pos) {
5006         // store SDU len
5007         channel->send_sdu_pos += 2u;
5008         little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
5009         pos += 2u;
5010     }
5011     uint16_t payload_size = btstack_min(channel->send_sdu_len + 2u - channel->send_sdu_pos, channel->remote_mps - pos);
5012     log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size,
5013              channel->credits_outgoing);
5014     (void) memcpy(&l2cap_payload[pos],
5015                   &channel->send_sdu_buffer[channel->send_sdu_pos - 2u],
5016                   payload_size); // -2 for virtual SDU len
5017     pos += payload_size;
5018     channel->send_sdu_pos += payload_size;
5019     l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
5020 
5021     channel->credits_outgoing--;
5022 
5023     // update state (mark SDU as done) before calling hci_send_acl_packet_buffer (trigger l2cap_le_send_pdu again)
5024     bool done = channel->send_sdu_pos >= (channel->send_sdu_len + 2u);
5025     if (done) {
5026         channel->send_sdu_buffer = NULL;
5027     }
5028 
5029     hci_send_acl_packet_buffer(8u + pos);
5030 
5031     if (done) {
5032         // send done event
5033         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_PACKET_SENT);
5034         // inform about can send now
5035         l2cap_credit_based_notify_channel_can_send(channel);
5036     }
5037 }
5038 
5039 static uint8_t l2cap_credit_based_send_data(l2cap_channel_t * channel, const uint8_t * data, uint16_t size){
5040 
5041     if (size > channel->remote_mtu){
5042         log_error("l2cap send, cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
5043         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
5044     }
5045 
5046     if (channel->send_sdu_buffer){
5047         log_info("l2cap send, cid 0x%02x, cannot send", channel->local_cid);
5048         return BTSTACK_ACL_BUFFERS_FULL;
5049     }
5050 
5051     channel->send_sdu_buffer = data;
5052     channel->send_sdu_len    = size;
5053     channel->send_sdu_pos    = 0;
5054 
5055     l2cap_notify_channel_can_send();
5056     return ERROR_CODE_SUCCESS;
5057 }
5058 
5059 static uint8_t l2cap_credit_based_provide_credits(uint16_t local_cid, uint16_t credits){
5060     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5061     if (!channel) {
5062         log_error("le credits no channel for cid 0x%02x", local_cid);
5063         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5064     }
5065 
5066     // check state
5067     if (channel->state != L2CAP_STATE_OPEN){
5068         log_error("le credits but channel 0x%02x not open yet", local_cid);
5069     }
5070 
5071     // ignore if set to automatic credits
5072     if (channel->automatic_credits) return ERROR_CODE_SUCCESS;
5073 
5074     // assert incoming credits + credits <= 0xffff
5075     uint32_t total_credits = channel->credits_incoming;
5076     total_credits += channel->new_credits_incoming;
5077     total_credits += credits;
5078     if (total_credits > 0xffffu){
5079         log_error("le credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
5080                   channel->new_credits_incoming, credits);
5081     }
5082 
5083     // set credits_granted
5084     channel->new_credits_incoming += credits;
5085 
5086     // go
5087     l2cap_run();
5088     return ERROR_CODE_SUCCESS;
5089 }
5090 
5091 static void l2cap_credit_based_send_credits(l2cap_channel_t *channel) {
5092     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
5093     channel->local_sig_id = l2cap_next_sig_id();
5094     uint16_t new_credits = channel->new_credits_incoming;
5095     channel->new_credits_incoming = 0;
5096     channel->credits_incoming += new_credits;
5097     uint16_t signaling_cid = channel->address_type == BD_ADDR_TYPE_ACL ? L2CAP_CID_SIGNALING : L2CAP_CID_SIGNALING_LE;
5098     l2cap_send_general_signaling_packet(channel->con_handle, signaling_cid, L2CAP_FLOW_CONTROL_CREDIT_INDICATION, channel->local_sig_id, channel->local_cid, new_credits);
5099 }
5100 
5101 // @return valid
5102 static bool l2cap_credit_based_handle_credit_indication(hci_con_handle_t handle, const uint8_t * command, uint16_t len){
5103     // check size
5104     if (len < 4u) return false;
5105 
5106     // find channel
5107     uint16_t remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
5108     l2cap_channel_t * channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
5109     if (!channel) {
5110         log_error("credit: no channel for handle 0x%04x/cid 0x%02x", handle, remote_cid);
5111         return true;
5112     }
5113     uint16_t new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
5114     uint16_t credits_before = channel->credits_outgoing;
5115     channel->credits_outgoing += new_credits;
5116     // check for credit overrun
5117     if (credits_before > channel->credits_outgoing) {
5118         log_error("credit: new credits caused overrrun for cid 0x%02x, disconnecting", channel->local_cid);
5119         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
5120         return true;
5121     }
5122     log_info("credit: %u credits for 0x%02x, now %u", new_credits, channel->local_cid, channel->credits_outgoing);
5123     l2cap_call_notify_channel_in_run = true;
5124     return true;
5125 }
5126 
5127 static void l2cap_credit_based_handle_pdu(l2cap_channel_t * l2cap_channel, const uint8_t * packet, uint16_t size){
5128     // ignore empty packets
5129     if (size == COMPLETE_L2CAP_HEADER) return;
5130 
5131     // credit counting
5132     if (l2cap_channel->credits_incoming == 0u){
5133         log_info("(e)CBM: packet received but no incoming credits");
5134         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
5135         return;
5136     }
5137     l2cap_channel->credits_incoming--;
5138 
5139     // automatic credits
5140     if ((l2cap_channel->credits_incoming < L2CAP_CREDIT_BASED_FLOW_CONTROL_MODE_AUTOMATIC_CREDITS_WATERMARK) && l2cap_channel->automatic_credits){
5141         l2cap_channel->new_credits_incoming = L2CAP_CREDIT_BASED_FLOW_CONTROL_MODE_AUTOMATIC_CREDITS_INCREMENT;
5142     }
5143 
5144     // first fragment
5145     uint16_t pos = 0;
5146     if (!l2cap_channel->receive_sdu_len){
5147         if (size < (COMPLETE_L2CAP_HEADER + 2)) return;
5148         uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
5149         if (sdu_len > l2cap_channel->local_mtu) {
5150             log_info("(e)CBM: packet received larger than MTU");
5151             l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
5152             return;
5153         }
5154         l2cap_channel->receive_sdu_len = sdu_len;
5155         l2cap_channel->receive_sdu_pos = 0;
5156         pos  += 2u;
5157         size -= 2u;
5158     }
5159 
5160     uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
5161 
5162     // check fragment_size
5163     if (fragment_size > l2cap_channel->local_mps) {
5164         log_info("(e)CBM: fragment larger than local MPS");
5165         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
5166         return;
5167     }
5168 
5169     // check sdu overrun
5170     if ((l2cap_channel->receive_sdu_pos + fragment_size) > l2cap_channel->receive_sdu_len){
5171         log_info("(e)CBM: fragments larger than SDU");
5172         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
5173         return;
5174     }
5175 
5176     (void)memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos],
5177                  &packet[COMPLETE_L2CAP_HEADER + pos],
5178                  fragment_size);
5179     l2cap_channel->receive_sdu_pos += fragment_size;
5180 
5181     // done?
5182     log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
5183     if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
5184         l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
5185         l2cap_channel->receive_sdu_len = 0;
5186     }
5187 }
5188 
5189 static void l2cap_credit_based_notify_channel_can_send(l2cap_channel_t *channel){
5190     if (!channel->waiting_for_can_send_now) return;
5191     if (channel->send_sdu_buffer) return;
5192     channel->waiting_for_can_send_now = 0;
5193     log_debug("le can send now, local_cid 0x%x", channel->local_cid);
5194     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CAN_SEND_NOW);
5195 }
5196 #endif
5197 
5198 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
5199 // 1BH2222
5200 static void l2cap_cbm_emit_incoming_connection(l2cap_channel_t *channel) {
5201     log_info("le incoming addr_type %u, addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x, remote_mtu %u",
5202              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
5203     uint8_t event[19];
5204     event[0] = L2CAP_EVENT_CBM_INCOMING_CONNECTION;
5205     event[1] = sizeof(event) - 2u;
5206     event[2] = channel->address_type;
5207     reverse_bd_addr(channel->address, &event[3]);
5208     little_endian_store_16(event,  9, channel->con_handle);
5209     little_endian_store_16(event, 11, channel->psm);
5210     little_endian_store_16(event, 13, channel->local_cid);
5211     little_endian_store_16(event, 15, channel->remote_cid);
5212     little_endian_store_16(event, 17, channel->remote_mtu);
5213     hci_dump_packet( HCI_EVENT_PACKET, 1, event, sizeof(event));
5214     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
5215 }
5216 // 11BH22222
5217 static void l2cap_cbm_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
5218     log_info("opened le channel 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",
5219              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
5220              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
5221     uint8_t event[23];
5222     event[0] = L2CAP_EVENT_CBM_CHANNEL_OPENED;
5223     event[1] = sizeof(event) - 2u;
5224     event[2] = status;
5225     event[3] = channel->address_type;
5226     reverse_bd_addr(channel->address, &event[4]);
5227     little_endian_store_16(event, 10, channel->con_handle);
5228     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
5229     little_endian_store_16(event, 13, channel->psm);
5230     little_endian_store_16(event, 15, channel->local_cid);
5231     little_endian_store_16(event, 17, channel->remote_cid);
5232     little_endian_store_16(event, 19, channel->local_mtu);
5233     little_endian_store_16(event, 21, channel->remote_mtu);
5234     hci_dump_packet( HCI_EVENT_PACKET, 1, event, sizeof(event));
5235     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
5236 }
5237 
5238 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
5239 void l2cap_cbm_finialize_channel_close(l2cap_channel_t * channel){
5240     channel->state = L2CAP_STATE_CLOSED;
5241     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
5242     // discard channel
5243     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
5244     l2cap_free_channel_entry(channel);
5245 }
5246 
5247 static inline l2cap_service_t * l2cap_cbm_get_service(uint16_t le_psm){
5248     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
5249 }
5250 
5251 uint8_t l2cap_cbm_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
5252 
5253     log_info("l2cap_cbm_register_service psm 0x%x", psm);
5254 
5255     // check for alread registered psm
5256     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5257     if (service) {
5258         return L2CAP_SERVICE_ALREADY_REGISTERED;
5259     }
5260 
5261     // alloc structure
5262     service = btstack_memory_l2cap_service_get();
5263     if (!service) {
5264         log_error("register: no memory for l2cap_service_t");
5265         return BTSTACK_MEMORY_ALLOC_FAILED;
5266     }
5267 
5268     // fill in
5269     service->psm = psm;
5270     service->mtu = 0;
5271     service->packet_handler = packet_handler;
5272     service->required_security_level = security_level;
5273     service->requires_authorization = false;
5274 
5275     // add to services list
5276     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
5277 
5278     // done
5279     return ERROR_CODE_SUCCESS;
5280 }
5281 
5282 uint8_t l2cap_cbm_unregister_service(uint16_t psm) {
5283     log_info("l2cap_cbm_unregister_service psm 0x%x", psm);
5284     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5285     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
5286 
5287     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
5288     btstack_memory_l2cap_service_free(service);
5289     return ERROR_CODE_SUCCESS;
5290 }
5291 
5292 uint8_t l2cap_cbm_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
5293     // get channel
5294     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5295     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5296 
5297     // validate state
5298     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
5299         return ERROR_CODE_COMMAND_DISALLOWED;
5300     }
5301 
5302     // set state accept connection
5303     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
5304     channel->receive_sdu_buffer = receive_sdu_buffer;
5305     channel->local_mtu = mtu;
5306     channel->new_credits_incoming = initial_credits;
5307     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5308 
5309     // go
5310     l2cap_run();
5311     return ERROR_CODE_SUCCESS;
5312 }
5313 
5314 uint8_t l2cap_cbm_decline_connection(uint16_t local_cid, uint16_t result) {
5315     // get channel
5316     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5317     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5318 
5319     // validate state
5320     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
5321         return ERROR_CODE_COMMAND_DISALLOWED;
5322     }
5323 
5324     // set state decline connection
5325     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
5326     channel->reason = result;
5327     l2cap_run();
5328     return ERROR_CODE_SUCCESS;
5329 }
5330 
5331 static gap_security_level_t l2cap_cbm_security_level_for_connection(hci_con_handle_t con_handle){
5332     uint8_t encryption_key_size = gap_encryption_key_size(con_handle);
5333     if (encryption_key_size == 0) return LEVEL_0;
5334 
5335     bool authenticated = gap_authenticated(con_handle);
5336     if (!authenticated) return LEVEL_2;
5337 
5338     return encryption_key_size == 16 ? LEVEL_4 : LEVEL_3;
5339 }
5340 
5341 // used to handle pairing complete after triggering to increase
5342 static void l2cap_cbm_sm_packet_handler(uint8_t packet_type, uint16_t channel_nr, uint8_t *packet, uint16_t size) {
5343     UNUSED(channel_nr);
5344     UNUSED(size);
5345     UNUSED(packet_type);
5346     btstack_assert(packet_type == HCI_EVENT_PACKET);
5347     if (hci_event_packet_get_type(packet) != SM_EVENT_PAIRING_COMPLETE) return;
5348     hci_con_handle_t con_handle = sm_event_pairing_complete_get_handle(packet);
5349     btstack_linked_list_iterator_t it;
5350     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5351     while (btstack_linked_list_iterator_has_next(&it)) {
5352         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5353         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5354         if (channel->con_handle != con_handle) continue;
5355         if (channel->state != L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE) continue;
5356 
5357         // found channel, check security level
5358         if (l2cap_cbm_security_level_for_connection(con_handle) < channel->required_security_level){
5359             // pairing failed or wasn't good enough, inform user
5360             l2cap_cbm_emit_channel_opened(channel, ERROR_CODE_INSUFFICIENT_SECURITY);
5361             // discard channel
5362             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
5363             l2cap_free_channel_entry(channel);
5364         } else {
5365             // send conn request now
5366             channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5367             l2cap_run();
5368         }
5369     }
5370 }
5371 
5372 uint8_t l2cap_cbm_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5373     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
5374     uint16_t * out_local_cid) {
5375 
5376     static btstack_packet_callback_registration_t sm_event_callback_registration;
5377     static bool sm_callback_registered = false;
5378 
5379     log_info("create, handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
5380 
5381     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5382     if (!connection) {
5383         log_error("no hci_connection for handle 0x%04x", con_handle);
5384         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5385     }
5386 
5387     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_CBM, connection->address, connection->address_type, psm, mtu, security_level);
5388     if (!channel) {
5389         return BTSTACK_MEMORY_ALLOC_FAILED;
5390     }
5391     log_info("created %p", channel);
5392 
5393     // store local_cid
5394     if (out_local_cid){
5395        *out_local_cid = channel->local_cid;
5396     }
5397 
5398     // setup channel entry
5399     channel->con_handle = con_handle;
5400     channel->receive_sdu_buffer = receive_sdu_buffer;
5401     channel->new_credits_incoming = initial_credits;
5402     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5403 
5404     // add to connections list
5405     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
5406 
5407     // check security level
5408     if (l2cap_cbm_security_level_for_connection(con_handle) < channel->required_security_level){
5409         if (!sm_callback_registered){
5410             sm_callback_registered = true;
5411             // lazy registration for SM events
5412             sm_event_callback_registration.callback = &l2cap_cbm_sm_packet_handler;
5413             sm_add_event_handler(&sm_event_callback_registration);
5414         }
5415 
5416         // start pairing
5417         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
5418         sm_request_pairing(con_handle);
5419     } else {
5420         // send conn request right away
5421         channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5422         l2cap_run();
5423     }
5424 
5425     return ERROR_CODE_SUCCESS;
5426 }
5427 
5428 uint8_t l2cap_cbm_provide_credits(uint16_t local_cid, uint16_t credits){
5429     return l2cap_credit_based_provide_credits(local_cid, credits);
5430 }
5431 #endif
5432 
5433 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
5434 
5435 uint8_t l2cap_ecbm_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, uint16_t min_remote_mtu,
5436                                     gap_security_level_t security_level, bool authorization_required) {
5437 
5438     // check for already registered psm
5439     l2cap_service_t *service = l2cap_ecbm_get_service(psm);
5440     if (service) {
5441         return L2CAP_SERVICE_ALREADY_REGISTERED;
5442     }
5443 
5444     // alloc structure
5445     service = btstack_memory_l2cap_service_get();
5446     if (!service) {
5447         log_error("register: no memory for l2cap_service_t");
5448         return BTSTACK_MEMORY_ALLOC_FAILED;
5449     }
5450 
5451     // fill in
5452     service->psm = psm;
5453     service->mtu = min_remote_mtu;
5454     service->packet_handler = packet_handler;
5455     service->required_security_level = security_level;
5456     service->requires_authorization = authorization_required;
5457 
5458     // add to services list
5459     btstack_linked_list_add(&l2cap_enhanced_services, (btstack_linked_item_t *) service);
5460 
5461     // done
5462     return ERROR_CODE_SUCCESS;
5463 }
5464 
5465 uint8_t l2cap_ecbm_unregister_service(uint16_t psm) {
5466     l2cap_service_t *service = l2cap_ecbm_get_service(psm);
5467     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
5468 
5469     btstack_linked_list_remove(&l2cap_enhanced_services, (btstack_linked_item_t *) service);
5470     btstack_memory_l2cap_service_free(service);
5471     return ERROR_CODE_SUCCESS;
5472 }
5473 
5474 void l2cap_ecbm_mps_set_min(uint16_t mps_min){
5475     l2cap_enhanced_mps_min = mps_min;
5476 }
5477 
5478 void l2cap_ecbm_mps_set_max(uint16_t mps_max){
5479     l2cap_enhanced_mps_max = mps_max;
5480 }
5481 
5482 uint8_t l2cap_ecbm_create_channels(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5483                                        gap_security_level_t security_level,
5484                                        uint16_t psm, uint8_t num_channels, uint16_t initial_credits, uint16_t mtu,
5485                                        uint8_t ** receive_sdu_buffers, uint16_t * out_local_cid){
5486 
5487     log_info("create enhanced, handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
5488 
5489     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5490     if (!connection) {
5491         log_error("no hci_connection for handle 0x%04x", con_handle);
5492         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5493     }
5494 
5495     // setup all channels
5496     btstack_linked_list_t channels = NULL;
5497     uint8_t status = l2cap_ecbm_setup_channels(&channels, packet_handler, num_channels, connection, psm, mtu,
5498                                                security_level);
5499     uint16_t local_mps = btstack_min(l2cap_enhanced_mps_max, btstack_min(l2cap_max_le_mtu(), mtu));
5500 
5501     // add to connections list and set state + local_sig_id
5502     l2cap_channel_t * channel;
5503     uint8_t i = 0;
5504     uint8_t local_sig_id = l2cap_next_sig_id();
5505     while (true) {
5506         channel = (l2cap_channel_t *) btstack_linked_list_pop(&channels);
5507         if (channel == NULL) break;
5508         channel->state              = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST;
5509         channel->local_sig_id       = local_sig_id;
5510         channel->local_mps = local_mps;
5511         channel->cid_index = i;
5512         channel->num_cids = num_channels;
5513         channel->credits_incoming   = initial_credits;
5514         channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5515         channel->receive_sdu_buffer = receive_sdu_buffers[i];
5516         // store local_cid
5517         if (out_local_cid){
5518             out_local_cid[i] = channel->local_cid;
5519         }
5520         btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
5521         i++;
5522     }
5523 
5524 #if 0
5525     // check security level
5526     if (l2cap_le_security_level_for_connection(con_handle) < channel->required_security_level){
5527         if (!sm_callback_registered){
5528             sm_callback_registered = true;
5529             // lazy registration for SM events
5530             sm_event_callback_registration.callback = &l2cap_sm_packet_handler;
5531             sm_add_event_handler(&sm_event_callback_registration);
5532         }
5533 
5534         // start pairing
5535         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
5536         sm_request_pairing(con_handle);
5537     } else {
5538         // send conn request right away
5539         channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5540         l2cap_run();
5541     }
5542 #endif
5543 
5544     l2cap_run();
5545 
5546     return status;
5547 }
5548 
5549 uint8_t l2cap_ecbm_accept_channels(uint16_t local_cid, uint8_t num_channels, uint16_t initial_credits,
5550                                             uint16_t receive_buffer_size, uint8_t ** receive_buffers, uint16_t * out_local_cids){
5551 
5552     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5553     if (!channel) {
5554 
5555         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5556     }
5557 
5558     uint16_t local_mps = btstack_min(l2cap_enhanced_mps_max, btstack_min(l2cap_max_le_mtu(), receive_buffer_size));
5559 
5560     //
5561     hci_con_handle_t  con_handle    = channel->con_handle;
5562     uint8_t           local_sig_id  = channel->local_sig_id;
5563     uint8_t           channel_index = 0;
5564     btstack_linked_list_iterator_t it;
5565     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5566     while (btstack_linked_list_iterator_has_next(&it)) {
5567         channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5568         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5569         if (channel->con_handle != con_handle) continue;
5570         if (channel->local_sig_id != local_sig_id) continue;
5571         if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT) continue;
5572 
5573         if (channel_index < num_channels){
5574             // assign buffer and cid
5575             out_local_cids[channel_index] = channel->local_cid;
5576             channel->receive_sdu_buffer = receive_buffers[channel_index];
5577             channel->local_mtu = receive_buffer_size;
5578             channel->local_mps = local_mps;
5579             channel->credits_incoming   = initial_credits;
5580             channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5581             channel_index++;
5582         } else {
5583             // clear local cid for response packet
5584             channel->local_cid = 0;
5585             channel->reason = L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INSUFFICIENT_RESOURCES_AVAILABLE;
5586         }
5587         // update state
5588         channel->state = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE;
5589     }
5590     l2cap_run_trigger();
5591     return ERROR_CODE_SUCCESS;
5592 }
5593 
5594 uint8_t l2cap_ecbm_decline_channels(uint16_t local_cid, uint16_t result){
5595     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5596     if (!channel) {
5597         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5598     }
5599     //
5600     hci_con_handle_t  con_handle    = channel->con_handle;
5601     uint8_t           local_sig_id  = channel->local_sig_id;
5602     btstack_linked_list_iterator_t it;
5603     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5604     while (btstack_linked_list_iterator_has_next(&it)) {
5605         channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5606         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5607         if (channel->con_handle != con_handle) continue;
5608         if (channel->local_sig_id != local_sig_id) continue;
5609         if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT) continue;
5610 
5611         // prepare response
5612         channel->local_cid = 0;
5613         channel->reason = result;
5614         channel->state = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE;
5615     }
5616     l2cap_run_trigger();
5617     return ERROR_CODE_SUCCESS;
5618 }
5619 
5620 uint8_t l2cap_ecbm_reconfigure_channels(uint8_t num_cids, uint16_t * local_cids, int16_t receive_buffer_size, uint8_t ** receive_buffers){
5621     btstack_assert(receive_buffers != NULL);
5622     btstack_assert(local_cids != NULL);
5623 
5624     if (num_cids > L2CAP_ECBM_MAX_CID_ARRAY_SIZE){
5625         return ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS;
5626     }
5627 
5628     // check if all cids exist and have the same con handle
5629     uint8_t i;
5630     hci_con_handle_t con_handle = HCI_CON_HANDLE_INVALID;
5631     for (i = 0 ; i < num_cids ; i++){
5632         l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cids[i]);
5633         if (!channel) {
5634             return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5635         }
5636         if (channel->state != L2CAP_STATE_OPEN){
5637             return ERROR_CODE_COMMAND_DISALLOWED;
5638         }
5639         if (con_handle == HCI_CON_HANDLE_INVALID){
5640             con_handle = channel->con_handle;
5641         } else if (con_handle != channel->con_handle){
5642             return ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS;
5643         }
5644     }
5645     // set renegotiation data and state
5646     uint8_t sig_id = l2cap_next_sig_id();
5647     for (i = 0 ; i < num_cids ; i++){
5648         l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cids[i]);
5649         channel->cid_index = i;
5650         channel->num_cids = num_cids;
5651         channel->local_sig_id = sig_id;
5652         channel->renegotiate_mtu = receive_buffer_size;
5653         channel->renegotiate_sdu_buffer = receive_buffers[i];
5654         channel->state = L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST;
5655     }
5656 
5657 
5658     l2cap_run();
5659     return ERROR_CODE_SUCCESS;
5660 }
5661 
5662 uint8_t l2cap_ecbm_provide_credits(uint16_t local_cid, uint16_t credits){
5663     return l2cap_credit_based_provide_credits(local_cid, credits);
5664 }
5665 #endif
5666 
5667 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
5668 // @deprecated - please use l2cap_ertm_create_channel
5669 uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
5670                                   l2cap_ertm_config_t * ertm_contig, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
5671     log_error("deprecated - please use l2cap_ertm_create_channel");
5672     return l2cap_ertm_create_channel(packet_handler, address, psm, ertm_contig, buffer, size, out_local_cid);
5673 };
5674 
5675 // @deprecated - please use l2cap_ertm_accept_connection
5676 uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, l2cap_ertm_config_t * ertm_contig, uint8_t * buffer, uint32_t size){
5677     log_error("deprecated - please use l2cap_ertm_accept_connection");
5678     return l2cap_ertm_accept_connection(local_cid, ertm_contig, buffer, size);
5679 }
5680 #endif
5681 
5682 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
5683 // @deprecated - please use l2cap_cbm_register_service
5684 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
5685     log_error("deprecated - please use l2cap_cbm_register_service");
5686     return l2cap_cbm_register_service(packet_handler, psm, security_level);
5687 }
5688 
5689 // @deprecated - please use l2cap_cbm_unregister_service
5690 uint8_t l2cap_le_unregister_service(uint16_t psm){
5691     log_error("deprecated - please use l2cap_cbm_unregister_service");
5692     return l2cap_cbm_unregister_service(psm);
5693 }
5694 
5695 // @deprecated - please use l2cap_cbm_accept_connection
5696 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
5697     log_error("deprecated - please use l2cap_cbm_accept_connection");
5698     return l2cap_cbm_accept_connection(local_cid, receive_sdu_buffer, mtu, initial_credits);
5699 }
5700 
5701 // @deprecated - please use l2cap_cbm_decline_connection
5702 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
5703     log_error("deprecated - please use l2cap_cbm_decline_connection");
5704     return l2cap_cbm_decline_connection(local_cid, L2CAP_CBM_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE);
5705 }
5706 
5707 // @deprecated - please use l2cap_cbm_create_channel
5708 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5709                                 uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
5710                                 uint16_t * out_local_cid){
5711     log_error("deprecated - please use l2cap_cbm_create_channel");
5712     return l2cap_cbm_create_channel(packet_handler, con_handle, psm, receive_sdu_buffer, mtu, initial_credits, security_level, out_local_cid);
5713 }
5714 
5715 // @deprecated - please use l2cap_cbm_provide_credits
5716 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
5717     log_error("deprecated - please use l2cap_cbm_provide_credits");
5718     return l2cap_cbm_provide_credits(local_cid, credits);
5719 }
5720 
5721 // @deprecated - please use l2cap_can_send_packet_now
5722 bool l2cap_le_can_send_now(uint16_t local_cid){
5723     log_error("deprecated - please use l2cap_can_send_packet_now");
5724     return l2cap_can_send_packet_now(local_cid);
5725 }
5726 
5727 // @deprecated - please use l2cap_request_can_send_now_event
5728 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
5729     log_error("deprecated - please use l2cap_request_can_send_now_event");
5730     return l2cap_request_can_send_now_event(local_cid);
5731 }
5732 
5733 // @deprecated - please use l2cap_cbm_send_data
5734 uint8_t l2cap_le_send_data(uint16_t local_cid, const uint8_t * data, uint16_t size){
5735     log_error("deprecated - please use l2cap_cbm_send_data");
5736     return l2cap_send(local_cid, data, size);
5737 }
5738 
5739 // @deprecated - please use l2cap_disconnect
5740 uint8_t l2cap_le_disconnect(uint16_t local_cid){
5741     log_error("deprecated - please use l2cap_disconnect");
5742     return l2cap_disconnect(local_cid);
5743 }
5744 #endif
5745