xref: /btstack/src/l2cap.c (revision 2046b1ba63390fdf64250bbe845c218ca396814f)
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 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
1368     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1369     if (channel) {
1370         return channel->remote_mtu;
1371     }
1372     return 0;
1373 }
1374 #endif
1375 
1376 #ifdef ENABLE_CLASSIC
1377 // RTX Timer only exist for dynamic channels
1378 static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
1379     btstack_linked_list_iterator_t it;
1380     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1381     while (btstack_linked_list_iterator_has_next(&it)){
1382         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1383         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
1384         if (&channel->rtx == ts) {
1385             return channel;
1386         }
1387     }
1388     return NULL;
1389 }
1390 
1391 static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
1392     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
1393     if (!channel) return;
1394 
1395     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
1396 
1397     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
1398     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
1399     // notify client
1400     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
1401 
1402     // discard channel
1403     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1404     l2cap_free_channel_entry(channel);
1405 }
1406 
1407 static uint8_t l2cap_classic_packet_boundary_flag(void){
1408     return (hci_non_flushable_packet_boundary_flag_supported() && (hci_automatic_flush_timeout() == 0)) ? 0x00 : 0x02;
1409 }
1410 #endif
1411 
1412 #ifdef L2CAP_USES_CHANNELS
1413 static void l2cap_stop_rtx(l2cap_channel_t * channel){
1414     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
1415     btstack_run_loop_remove_timer(&channel->rtx);
1416 }
1417 #endif
1418 
1419 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){
1420     if (!hci_can_send_acl_packet_now(handle)){
1421         log_info("l2cap_send_classic_signaling_packet, cannot send");
1422         return BTSTACK_ACL_BUFFERS_FULL;
1423     }
1424     hci_reserve_packet_buffer();
1425     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1426     uint16_t len = l2cap_create_signaling_packet(acl_buffer, handle, pb_flags, cid, cmd, identifier, argptr);
1427     va_end(argptr);
1428     return hci_send_acl_packet_buffer(len);
1429 }
1430 
1431 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
1432 static int l2cap_send_general_signaling_packet(hci_con_handle_t handle, uint16_t signaling_cid, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1433     va_list argptr;
1434     va_start(argptr, identifier);
1435     uint8_t pb_flags = 0x00;
1436 #ifdef ENABLE_CLASSIC
1437     if (signaling_cid == L2CAP_CID_SIGNALING){
1438         pb_flags = l2cap_classic_packet_boundary_flag();
1439     }
1440 #endif
1441 uint8_t result = l2cap_send_signaling_packet(handle, pb_flags, signaling_cid, cmd, identifier, argptr);
1442     va_end(argptr);
1443     return result;
1444 }
1445 #endif
1446 
1447 #ifdef ENABLE_CLASSIC
1448 
1449 static void l2cap_start_rtx(l2cap_channel_t * channel){
1450     l2cap_stop_rtx(channel);
1451     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
1452     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1453     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
1454     btstack_run_loop_add_timer(&channel->rtx);
1455 }
1456 
1457 static void l2cap_start_ertx(l2cap_channel_t * channel){
1458     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
1459     l2cap_stop_rtx(channel);
1460     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1461     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
1462     btstack_run_loop_add_timer(&channel->rtx);
1463 }
1464 
1465 void l2cap_require_security_level_2_for_outgoing_sdp(void){
1466     l2cap_require_security_level2_for_outgoing_sdp = 1;
1467 }
1468 
1469 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
1470     return (psm == BLUETOOTH_PSM_SDP) && (!l2cap_require_security_level2_for_outgoing_sdp);
1471 }
1472 
1473 static int l2cap_send_classic_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1474     va_list argptr;
1475     va_start(argptr, identifier);
1476     uint8_t pb_flag = l2cap_classic_packet_boundary_flag();
1477     uint8_t result = l2cap_send_signaling_packet(handle, pb_flag, L2CAP_CID_SIGNALING, cmd, identifier, argptr);
1478     va_end(argptr);
1479     return result;
1480 }
1481 
1482 // assumption - only on Classic connections
1483 // cannot be used for L2CAP ERTM
1484 uint8_t l2cap_send_prepared(uint16_t local_cid, uint16_t len){
1485 
1486     if (!hci_is_packet_buffer_reserved()){
1487         log_error("l2cap_send_prepared called without reserving packet first");
1488         return BTSTACK_ACL_BUFFERS_FULL;
1489     }
1490 
1491     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1492     if (!channel) {
1493         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
1494         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
1495     }
1496 
1497     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
1498         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
1499         return BTSTACK_ACL_BUFFERS_FULL;
1500     }
1501 
1502     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
1503 
1504     int fcs_size = 0;
1505 
1506 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1507     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->fcs_option){
1508         fcs_size = 2;
1509     }
1510 #endif
1511 
1512     // set non-flushable packet boundary flag if supported on Controller
1513     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1514     uint8_t packet_boundary_flag = l2cap_classic_packet_boundary_flag();
1515     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
1516 
1517 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1518     if (fcs_size){
1519         // calculate FCS over l2cap data
1520         uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
1521         log_info("I-Frame: fcs 0x%04x", fcs);
1522         little_endian_store_16(acl_buffer, 8 + len, fcs);
1523     }
1524 #endif
1525 
1526     // send
1527     return hci_send_acl_packet_buffer(len+8+fcs_size);
1528 }
1529 
1530 // assumption - only on Classic connections
1531 static uint8_t l2cap_classic_send(l2cap_channel_t * channel, const uint8_t *data, uint16_t len){
1532 
1533 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1534     // send in ERTM
1535     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1536         return l2cap_ertm_send(channel, data, len);
1537     }
1538 #endif
1539 
1540     if (len > channel->remote_mtu){
1541         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
1542         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
1543     }
1544 
1545     if (!hci_can_send_acl_packet_now(channel->con_handle)){
1546         log_info("l2cap_send cid 0x%02x, cannot send", channel->local_cid);
1547         return BTSTACK_ACL_BUFFERS_FULL;
1548     }
1549 
1550     hci_reserve_packet_buffer();
1551     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1552     (void)memcpy(&acl_buffer[8], data, len);
1553     return l2cap_send_prepared(channel->local_cid, len);
1554 }
1555 
1556 int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
1557     return l2cap_send_classic_signaling_packet(con_handle, ECHO_REQUEST, l2cap_next_sig_id(), len, data);
1558 }
1559 
1560 static inline void channelStateVarSetFlag(l2cap_channel_t *channel, uint16_t flag){
1561     channel->state_var = channel->state_var | flag;
1562 }
1563 
1564 static inline void channelStateVarClearFlag(l2cap_channel_t *channel, uint16_t flag){
1565     channel->state_var = channel->state_var & ~flag;
1566 }
1567 #endif
1568 
1569 
1570 #ifdef ENABLE_BLE
1571 static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1572     va_list argptr;
1573     va_start(argptr, identifier);
1574     uint8_t pb_flags = 0x00;  // First non-automatically-flushable packet of a higher layer message
1575     uint8_t result = l2cap_send_signaling_packet(handle, pb_flags, L2CAP_CID_SIGNALING_LE, cmd, identifier, argptr);
1576     va_end(argptr);
1577     return result;
1578 }
1579 #endif
1580 
1581 uint16_t l2cap_max_mtu(void){
1582     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
1583 }
1584 
1585 #ifdef ENABLE_BLE
1586 uint16_t l2cap_max_le_mtu(void){
1587     if (l2cap_le_custom_max_mtu != 0u) return l2cap_le_custom_max_mtu;
1588     return l2cap_max_mtu();
1589 }
1590 
1591 void l2cap_set_max_le_mtu(uint16_t max_mtu){
1592     if (max_mtu < l2cap_max_mtu()){
1593         l2cap_le_custom_max_mtu = max_mtu;
1594     }
1595 }
1596 #endif
1597 
1598 #ifdef ENABLE_CLASSIC
1599 
1600 static uint16_t l2cap_setup_options_mtu(uint8_t * config_options, uint16_t mtu){
1601     config_options[0] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
1602     config_options[1] = 2; // len param
1603     little_endian_store_16(config_options, 2, mtu);
1604     return 4;
1605 }
1606 
1607 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1608 static int l2cap_ertm_mode(l2cap_channel_t * channel){
1609     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
1610     return ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE)
1611         &&  (connection->l2cap_state.extended_feature_mask & 0x08));
1612 }
1613 #endif
1614 
1615 static uint16_t l2cap_setup_options_request(l2cap_channel_t * channel, uint8_t * config_options){
1616 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1617     // use ERTM options if supported by remote and channel ready to use it
1618     if (l2cap_ertm_mode(channel) && channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1619         return l2cap_setup_options_ertm_request(channel, config_options);
1620     }
1621 #endif
1622     uint16_t mtu = channel->local_mtu;
1623     return l2cap_setup_options_mtu(config_options, mtu);
1624 }
1625 
1626 static uint16_t l2cap_setup_options_mtu_response(l2cap_channel_t * channel, uint8_t * config_options){
1627     uint16_t mtu = btstack_min(channel->local_mtu, channel->remote_mtu);
1628     return l2cap_setup_options_mtu(config_options, mtu);
1629 }
1630 
1631 static uint32_t l2cap_extended_features_mask(void){
1632     // extended features request supported, features: fixed channels, unicast connectionless data reception
1633     uint32_t features = 0x280;
1634 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1635     features |= 0x0028;
1636 #endif
1637     return features;
1638 }
1639 #endif
1640 
1641 //
1642 #ifdef ENABLE_CLASSIC
1643 
1644 // returns true if channel was finalized
1645 static bool l2cap_run_for_classic_channel(l2cap_channel_t * channel){
1646 
1647 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1648     uint8_t  config_options[18];
1649 #else
1650     uint8_t  config_options[10];
1651 #endif
1652 
1653     switch (channel->state){
1654 
1655         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1656         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
1657             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1658             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
1659                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
1660                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONN_RESP_PEND);
1661                 l2cap_send_classic_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id,
1662                                                     channel->local_cid, channel->remote_cid, 1, 0);
1663             }
1664             break;
1665 
1666         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1667             if (!hci_can_send_command_packet_now()) break;
1668             // send connection request - set state first
1669             channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
1670             // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
1671             (void)memcpy(l2cap_outgoing_classic_addr, channel->address, 6);
1672             hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, hci_get_allow_role_switch());
1673             break;
1674 
1675         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
1676             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1677             channel->state = L2CAP_STATE_INVALID;
1678             l2cap_send_classic_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id,
1679                                                 channel->local_cid, channel->remote_cid, channel->reason, 0);
1680             // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1681             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1682             l2cap_free_channel_entry(channel);
1683             channel = NULL;
1684             break;
1685 
1686         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
1687             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1688             channel->state = L2CAP_STATE_CONFIG;
1689             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1690             l2cap_send_classic_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id,
1691                                                 channel->local_cid, channel->remote_cid, 0, 0);
1692             break;
1693 
1694         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
1695             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1696             // success, start l2cap handshake
1697             channel->local_sig_id = l2cap_next_sig_id();
1698             channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
1699             l2cap_send_classic_signaling_packet(channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id,
1700                                                 channel->psm, channel->local_cid);
1701             l2cap_start_rtx(channel);
1702             break;
1703 
1704         case L2CAP_STATE_CONFIG:
1705             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1706 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1707             // fallback to basic mode if ERTM requested but not not supported by remote
1708             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1709                 if (!l2cap_ertm_mode(channel)){
1710                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1711                     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
1712                 }
1713             }
1714 #endif
1715             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
1716                 uint16_t flags = 0;
1717                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1718                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
1719                     flags = 1;
1720                 } else {
1721                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1722                 }
1723                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
1724                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1725                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1726                                                         channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS,
1727                                                         1, &channel->unknown_option);
1728 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1729                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
1730                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1731                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1732                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1733                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1734                                                         channel->remote_cid, flags,
1735                                                         L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS, options_size,
1736                                                         &config_options);
1737                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM){
1738                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
1739                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1740                     uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1741                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1742                                                         channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS,
1743                                                         options_size, &config_options);
1744 #endif
1745                 } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
1746                     channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1747                     uint16_t options_size = l2cap_setup_options_mtu_response(channel, config_options);
1748                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1749                                                         channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS,
1750                                                         options_size, &config_options);
1751                 } else {
1752                     l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id,
1753                                                         channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
1754                 }
1755                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1756             }
1757             else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
1758                 channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1759                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
1760                 channel->local_sig_id = l2cap_next_sig_id();
1761                 uint16_t options_size = l2cap_setup_options_request(channel, config_options);
1762                 l2cap_send_classic_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id,
1763                                                     channel->remote_cid, 0, options_size, &config_options);
1764                 l2cap_start_rtx(channel);
1765             }
1766             if (l2cap_channel_ready_for_open(channel)){
1767                 channel->state = L2CAP_STATE_OPEN;
1768                 l2cap_emit_channel_opened(channel, 0);  // success
1769             }
1770             break;
1771 
1772         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1773             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1774             channel->state = L2CAP_STATE_INVALID;
1775             l2cap_send_classic_signaling_packet(channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id,
1776                                                 channel->local_cid, channel->remote_cid);
1777             // 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 :)
1778             l2cap_finalize_channel_close(channel);  // -- remove from list
1779             channel = NULL;
1780             break;
1781 
1782         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1783             if (!hci_can_send_acl_packet_now(channel->con_handle)) return false;
1784             channel->local_sig_id = l2cap_next_sig_id();
1785             channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1786             l2cap_send_classic_signaling_packet(channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id,
1787                                                 channel->remote_cid, channel->local_cid);
1788             break;
1789         default:
1790             break;
1791     }
1792 
1793     // handle channel finalize on L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE and L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE
1794     return channel == NULL;
1795 }
1796 
1797 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1798 static void l2cap_run_for_classic_channel_ertm(l2cap_channel_t * channel){
1799 
1800     // ERTM mode
1801     if (channel->mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) return;
1802 
1803     // check if we can still send
1804     if (channel->con_handle == HCI_CON_HANDLE_INVALID) return;
1805     if (!hci_can_send_acl_packet_now(channel->con_handle)) return;
1806 
1807     if (channel->send_supervisor_frame_receiver_ready){
1808         channel->send_supervisor_frame_receiver_ready = 0;
1809         log_info("Send S-Frame: RR %u, final %u", channel->req_seq, channel->set_final_bit_after_packet_with_poll_bit_set);
1810         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);
1811         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1812         l2cap_ertm_send_supervisor_frame(channel, control);
1813         return;
1814     }
1815     if (channel->send_supervisor_frame_receiver_ready_poll){
1816         channel->send_supervisor_frame_receiver_ready_poll = 0;
1817         log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
1818         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
1819         l2cap_ertm_send_supervisor_frame(channel, control);
1820         return;
1821     }
1822     if (channel->send_supervisor_frame_receiver_not_ready){
1823         channel->send_supervisor_frame_receiver_not_ready = 0;
1824         log_info("Send S-Frame: RNR %u", channel->req_seq);
1825         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
1826         l2cap_ertm_send_supervisor_frame(channel, control);
1827         return;
1828     }
1829     if (channel->send_supervisor_frame_reject){
1830         channel->send_supervisor_frame_reject = 0;
1831         log_info("Send S-Frame: REJ %u", channel->req_seq);
1832         uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 0, 0, channel->req_seq);
1833         l2cap_ertm_send_supervisor_frame(channel, control);
1834         return;
1835     }
1836     if (channel->send_supervisor_frame_selective_reject){
1837         channel->send_supervisor_frame_selective_reject = 0;
1838         log_info("Send S-Frame: SREJ %u", channel->expected_tx_seq);
1839         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);
1840         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1841         l2cap_ertm_send_supervisor_frame(channel, control);
1842         return;
1843     }
1844 
1845     if (channel->srej_active){
1846         int i;
1847         for (i=0;i<channel->num_tx_buffers;i++){
1848             l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
1849             if (tx_state->retransmission_requested) {
1850                 tx_state->retransmission_requested = 0;
1851                 uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set;
1852                 channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1853                 l2cap_ertm_send_information_frame(channel, i, final);
1854                 break;
1855             }
1856         }
1857         if (i == channel->num_tx_buffers){
1858             // no retransmission request found
1859             channel->srej_active = 0;
1860         } else {
1861             // packet was sent
1862             return;
1863         }
1864     }
1865 }
1866 #endif /* ERTM */
1867 #endif /* Classic */
1868 
1869 static void l2cap_run_signaling_response(void) {
1870 
1871     // check pending signaling responses
1872     while (l2cap_signaling_responses_pending){
1873 
1874         hci_con_handle_t handle = l2cap_signaling_responses[0].handle;
1875 
1876         if (!hci_can_send_acl_packet_now(handle)) break;
1877 
1878         uint8_t  sig_id        = l2cap_signaling_responses[0].sig_id;
1879         uint8_t  response_code = l2cap_signaling_responses[0].code;
1880         uint16_t result        = l2cap_signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT, REJECT_SM_PAIRING, L2CAP_CREDIT_BASED_CONNECTION_REQUEST
1881         uint8_t  buffer[2];                                          // REJECT_SM_PAIRING
1882         uint16_t source_cid    = l2cap_signaling_responses[0].cid;   // CONNECTION_REQUEST, REJECT_SM_PAIRING
1883 #ifdef ENABLE_CLASSIC
1884         uint16_t info_type     = l2cap_signaling_responses[0].data;  // INFORMATION_REQUEST
1885 #endif
1886 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1887         uint8_t num_channels = l2cap_signaling_responses[0].cid >> 8;                 // L2CAP_CREDIT_BASED_CONNECTION_REQUEST
1888         uint16_t signaling_cid = (uint16_t) l2cap_signaling_responses[0].cid & 0xff;  // L2CAP_CREDIT_BASED_CONNECTION_REQUEST, L2CAP_CREDIT_BASED_CONNECTION_REQUEST
1889 #endif
1890 
1891         // remove first item before sending (to avoid sending response mutliple times)
1892         l2cap_signaling_responses_pending--;
1893         int i;
1894         for (i=0; i < l2cap_signaling_responses_pending; i++){
1895             (void)memcpy(&l2cap_signaling_responses[i],
1896                          &l2cap_signaling_responses[i + 1],
1897                          sizeof(l2cap_signaling_response_t));
1898         }
1899 
1900         switch (response_code){
1901 #ifdef ENABLE_CLASSIC
1902             case CONNECTION_REQUEST:
1903                 l2cap_send_classic_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
1904                 break;
1905             case ECHO_REQUEST:
1906                 l2cap_send_classic_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
1907                 break;
1908             case INFORMATION_REQUEST:
1909                 switch (info_type){
1910                     case L2CAP_INFO_TYPE_CONNECTIONLESS_MTU: {
1911                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
1912                         l2cap_send_classic_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0,
1913                                                             sizeof(connectionless_mtu), &connectionless_mtu);
1914                         }
1915                         break;
1916                     case L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED: {
1917                             uint32_t features = l2cap_extended_features_mask();
1918                         l2cap_send_classic_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0,
1919                                                             sizeof(features), &features);
1920                         }
1921                         break;
1922                     case L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED: {
1923                             uint8_t map[8];
1924                             memset(map, 0, 8);
1925                             // L2CAP Signaling Channel + Connectionless reception
1926                             map[0] = (1 << L2CAP_CID_SIGNALING) | (1 << L2CAP_CID_CONNECTIONLESS_CHANNEL);
1927 #if defined(ENABLE_BLE) || defined (ENABLE_EXPLICIT_BR_EDR_SECURITY_MANAGER)
1928                             // BR/EDR Security Manager (bit 7) if BR/EDR Secure Connections possible
1929                             if (gap_secure_connections_active()){
1930                                 map[0] |= (1 << L2CAP_CID_BR_EDR_SECURITY_MANAGER);
1931                             }
1932 #endif
1933                             l2cap_send_classic_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0,
1934                                                             sizeof(map), &map);
1935                         }
1936                         break;
1937                     default:
1938                         // all other types are not supported
1939                         l2cap_send_classic_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 1, 0, NULL);
1940                         break;
1941                 }
1942                 break;
1943             case COMMAND_REJECT:
1944                 l2cap_send_classic_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
1945                 break;
1946 #endif
1947 #ifdef ENABLE_BLE
1948             case LE_CREDIT_BASED_CONNECTION_REQUEST:
1949                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
1950                 break;
1951             case COMMAND_REJECT_LE:
1952                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
1953                 break;
1954 #endif
1955 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
1956             case L2CAP_CREDIT_BASED_CONNECTION_REQUEST: {
1957                 // send variable size array or cids with each cid being zero
1958                 uint16_t cids[6];
1959                 (void) memset(cids, 0xff, sizeof(cids));
1960                 (void) memset(cids, 0x00, num_channels * sizeof(uint16_t));
1961                 l2cap_send_general_signaling_packet(handle, signaling_cid, L2CAP_CREDIT_BASED_CONNECTION_RESPONSE,
1962                                                     sig_id, 0, 0, 0, result, cids);
1963                 break;
1964             }
1965 
1966             case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
1967                 l2cap_send_general_signaling_packet(handle, signaling_cid, L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE,
1968                                                     sig_id, result);
1969                 break;
1970 #endif
1971             case SM_PAIRING_FAILED:
1972                 buffer[0] = SM_CODE_PAIRING_FAILED;
1973                 buffer[1] = (uint8_t) result;
1974                 l2cap_send_connectionless(handle, source_cid, buffer, 2);
1975                 break;
1976             default:
1977                 // should not happen
1978                 break;
1979         }
1980     }
1981 }
1982 
1983 #ifdef ENABLE_CLASSIC
1984 static bool l2ap_run_information_requests(void){
1985     // send l2cap information request if requested
1986     btstack_linked_list_iterator_t it;
1987     hci_connections_get_iterator(&it);
1988     uint8_t info_type;
1989     l2cap_information_state_t new_state;
1990     while(btstack_linked_list_iterator_has_next(&it)){
1991         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1992         switch (connection->l2cap_state.information_state){
1993             case L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST:
1994                 info_type = L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED;
1995                 new_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
1996                 break;
1997             case L2CAP_INFORMATION_STATE_W2_SEND_FIXED_CHANNELS_REQUEST:
1998                 info_type = L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED;
1999                 new_state = L2CAP_INFORMATION_STATE_W4_FIXED_CHANNELS_RESPONSE;
2000                 break;
2001             default:
2002                 continue;
2003         }
2004         if (!hci_can_send_acl_packet_now(connection->con_handle)) break;
2005 
2006         connection->l2cap_state.information_state = new_state;
2007         uint8_t sig_id = l2cap_next_sig_id();
2008         l2cap_send_classic_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
2009     }
2010     return false;
2011 }
2012 #endif
2013 
2014 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2015 static void l2cap_cbm_run_channels(void){
2016     btstack_linked_list_iterator_t it;
2017     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2018     while (btstack_linked_list_iterator_has_next(&it)){
2019         uint16_t mps;
2020         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2021 
2022         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CHANNEL_CBM) continue;
2023 
2024         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
2025         switch (channel->state){
2026             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
2027                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
2028                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
2029                 // le psm, source cid, mtu, mps, initial credits
2030                 channel->local_sig_id = l2cap_next_sig_id();
2031                 channel->credits_incoming =  channel->new_credits_incoming;
2032                 channel->new_credits_incoming = 0;
2033                 channel->local_mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
2034                 l2cap_send_le_signaling_packet( channel->con_handle, LE_CREDIT_BASED_CONNECTION_REQUEST,
2035                                                 channel->local_sig_id, channel->psm, channel->local_cid, channel->local_mtu,
2036                                                 channel->local_mps, channel->credits_incoming);
2037                 break;
2038             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
2039                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
2040                 // TODO: support larger MPS
2041                 channel->state = L2CAP_STATE_OPEN;
2042                 channel->credits_incoming =  channel->new_credits_incoming;
2043                 channel->new_credits_incoming = 0;
2044                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
2045                 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);
2046                 // notify client
2047                 l2cap_cbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
2048                 break;
2049             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
2050                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
2051                 channel->state = L2CAP_STATE_INVALID;
2052                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
2053                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
2054                 btstack_linked_list_iterator_remove(&it);
2055                 l2cap_free_channel_entry(channel);
2056                 break;
2057             case L2CAP_STATE_OPEN:
2058                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
2059                 if (channel->new_credits_incoming){
2060                     l2cap_credit_based_send_credits(channel);
2061                 }
2062                 break;
2063             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2064                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
2065                 channel->local_sig_id = l2cap_next_sig_id();
2066                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
2067                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
2068                 break;
2069             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
2070                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
2071                 channel->state = L2CAP_STATE_INVALID;
2072                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
2073                 l2cap_cbm_finialize_channel_close(channel);  // -- remove from list
2074                 break;
2075             default:
2076                 break;
2077         }
2078     }
2079 }
2080 
2081 static inline uint8_t l2cap_cbm_status_for_result(uint16_t result) {
2082     switch (result) {
2083         case L2CAP_CBM_CONNECTION_RESULT_SUCCESS:
2084             return ERROR_CODE_SUCCESS;
2085         case L2CAP_CBM_CONNECTION_RESULT_SPSM_NOT_SUPPORTED:
2086             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_PSM;
2087         case L2CAP_CBM_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE:
2088             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_RESOURCES;
2089         case L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHENTICATION:
2090         case L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHORIZATION:
2091         case L2CAP_CBM_CONNECTION_RESULT_ENCYRPTION_KEY_SIZE_TOO_SHORT:
2092         case L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_ENCRYPTION:
2093             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY;
2094         default:
2095             // invalid Source CID, Source CID already allocated, unacceptable parameters
2096             return L2CAP_CONNECTION_RESPONSE_UNKNOWN_ERROR;
2097     }
2098 }
2099 
2100 #endif
2101 
2102 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2103 
2104 static void l2cap_run_trigger_callback(void * context){
2105     UNUSED(context);
2106     l2cap_run();
2107 }
2108 
2109 static void l2cap_run_trigger(void){
2110     btstack_run_loop_execute_on_main_thread(&l2cap_trigger_run_registration);
2111 }
2112 
2113 // 11BH22222
2114 static void l2cap_ecbm_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
2115     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",
2116             status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
2117             channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
2118     uint8_t event[23];
2119     event[0] = L2CAP_EVENT_ECBM_CHANNEL_OPENED;
2120     event[1] = sizeof(event) - 2u;
2121     event[2] = status;
2122     event[3] = channel->address_type;
2123     reverse_bd_addr(channel->address, &event[4]);
2124     little_endian_store_16(event, 10, channel->con_handle);
2125     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
2126     little_endian_store_16(event, 13, channel->psm);
2127     little_endian_store_16(event, 15, channel->local_cid);
2128     little_endian_store_16(event, 17, channel->remote_cid);
2129     little_endian_store_16(event, 19, channel->local_mtu);
2130     little_endian_store_16(event, 21, channel->remote_mtu);
2131     hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
2132     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
2133 }
2134 
2135 static void l2cap_ecbm_emit_reconfigure_complete(l2cap_channel_t *channel, uint16_t result) {
2136     // emit event
2137     uint8_t event[6];
2138     event[0] = L2CAP_EVENT_ECBM_RECONFIGURATION_COMPLETE;
2139     event[1] = sizeof(event) - 2;
2140     little_endian_store_16(event, 2, channel->local_cid);
2141     little_endian_store_16(event, 4, result);
2142     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
2143 }
2144 
2145 static void l2cap_ecbm_run_channels(void) {
2146     hci_con_handle_t con_handle = HCI_CON_HANDLE_INVALID;
2147     // num max channels + 1 for signaling pdu generator
2148     uint16_t cids[L2CAP_ECBM_MAX_CID_ARRAY_SIZE + 1];
2149     uint8_t num_cids = 0;
2150     uint8_t sig_id;
2151     uint16_t spsm;
2152     L2CAP_STATE matching_state;
2153     bool match_remote_sig_cid;
2154     uint8_t result = 0;
2155     uint16_t local_mtu;
2156     uint16_t initial_credits;
2157     uint16_t signaling_cid;
2158     L2CAP_STATE new_state;
2159     uint16_t local_mps;
2160 
2161     // pick first channel that needs to send a combined signaling pdu and setup collection via break
2162     // then collect all others that belong to the same pdu
2163     btstack_linked_list_iterator_t it;
2164     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2165     while (btstack_linked_list_iterator_has_next(&it)) {
2166         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2167         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CHANNEL_ECBM) continue;
2168         if (con_handle == HCI_CON_HANDLE_INVALID) {
2169             switch (channel->state) {
2170                 case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST:
2171                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2172                     local_mtu = channel->local_mtu;
2173                     local_mps = channel->local_mps;
2174                     spsm = channel->psm;
2175                     result = channel->reason;
2176                     initial_credits = channel->credits_incoming;
2177                     sig_id = channel->local_sig_id;
2178                     new_state = L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE;
2179                     match_remote_sig_cid = false;
2180                     break;
2181                 case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE:
2182                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2183                     local_mtu = channel->local_mtu;
2184                     local_mps = channel->local_mps;
2185                     initial_credits = channel->credits_incoming;
2186                     sig_id = channel->remote_sig_id;
2187                     new_state = L2CAP_STATE_OPEN;
2188                     match_remote_sig_cid = true;
2189                     break;
2190                 case L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST:
2191                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2192                     sig_id = channel->local_sig_id;
2193                     local_mtu = channel->renegotiate_mtu;
2194                     local_mps = channel->local_mps;
2195                     new_state = L2CAP_STATE_WAIT_ENHANCED_RENEGOTIATION_RESPONSE;
2196                     match_remote_sig_cid = false;
2197                     break;
2198                 case L2CAP_STATE_OPEN:
2199                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2200                     if (channel->new_credits_incoming) {
2201                         l2cap_credit_based_send_credits(channel);
2202                     }
2203                     continue;
2204                 case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2205                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2206                     channel->local_sig_id = l2cap_next_sig_id();
2207                     channel->state = L2CAP_STATE_WAIT_DISCONNECT;
2208                     signaling_cid = channel->address_type == BD_ADDR_TYPE_ACL ? L2CAP_CID_SIGNALING : L2CAP_CID_SIGNALING_LE;
2209                     l2cap_send_general_signaling_packet(channel->con_handle, signaling_cid, DISCONNECTION_REQUEST,
2210                                                         channel->local_sig_id, channel->remote_cid, channel->local_cid);
2211                     continue;
2212                 case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
2213                     if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
2214                     channel->state = L2CAP_STATE_INVALID;
2215                     signaling_cid = channel->address_type == BD_ADDR_TYPE_ACL ? L2CAP_CID_SIGNALING : L2CAP_CID_SIGNALING_LE;
2216                     l2cap_send_general_signaling_packet(channel->con_handle, signaling_cid, DISCONNECTION_RESPONSE,
2217                                                         channel->remote_sig_id, channel->local_cid,
2218                                                         channel->remote_cid);
2219                     l2cap_cbm_finialize_channel_close(channel);  // -- remove from list
2220                     continue;
2221                 default:
2222                     continue;
2223             }
2224 
2225             // channel picked - setup cid array and collect info
2226             (void) memset(cids, 0xff, sizeof(cids));
2227             (void) memset(cids, 0, channel->num_cids * sizeof(uint16_t));
2228             matching_state = channel->state;
2229             con_handle = channel->con_handle;
2230             signaling_cid = channel->address_type == BD_ADDR_TYPE_ACL ? L2CAP_CID_SIGNALING : L2CAP_CID_SIGNALING_LE;
2231             num_cids = channel->num_cids;
2232 
2233         } else {
2234             // check if it matches first channel by state, con_handle, and signaling id
2235             if (matching_state != channel->state) continue;
2236             if (channel->con_handle != con_handle) continue;
2237             if (match_remote_sig_cid) {
2238                 if (channel->remote_sig_id != sig_id) continue;
2239             } else {
2240                 if (channel->local_sig_id != sig_id) continue;
2241             }
2242         }
2243 
2244         // add this cid
2245         cids[channel->cid_index] = channel->local_cid;
2246 
2247         // set new state
2248         channel->state = new_state;
2249 
2250         // handle open for L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE
2251         if (matching_state == L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE) {
2252             if (channel->reason == L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS) {
2253                 l2cap_ecbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
2254             } else {
2255                 result = channel->reason;
2256                 btstack_linked_list_iterator_remove(&it);
2257                 btstack_memory_l2cap_channel_free(channel);
2258             }
2259         }
2260     }
2261 
2262     if (con_handle != HCI_CON_HANDLE_INVALID) {
2263         switch (matching_state) {
2264             case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST:
2265                 log_info("send combined connection request for %u cids", num_cids);
2266                 l2cap_send_general_signaling_packet(con_handle, signaling_cid, L2CAP_CREDIT_BASED_CONNECTION_REQUEST,
2267                                                     sig_id, spsm, local_mtu, local_mps, initial_credits, cids);
2268                 break;
2269             case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE:
2270                 log_info("send combined connection response for %u cids", num_cids);
2271                 l2cap_send_general_signaling_packet(con_handle, signaling_cid, L2CAP_CREDIT_BASED_CONNECTION_RESPONSE,
2272                                                     sig_id, local_mtu, local_mps, initial_credits, result, cids);
2273                 break;
2274             case L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST:
2275                 log_info("send combined renegotiation request for %u cids", num_cids);
2276                 l2cap_send_general_signaling_packet(con_handle, signaling_cid, L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST,
2277                                                     sig_id, local_mtu, local_mps, cids);
2278                 break;
2279             default:
2280                 break;
2281         }
2282     }
2283 }
2284 #endif
2285 
2286 // MARK: L2CAP_RUN
2287 // process outstanding signaling tasks
2288 static void l2cap_run(void){
2289 
2290     // log_info("l2cap_run: entered");
2291     l2cap_run_signaling_response();
2292 
2293 #ifdef ENABLE_CLASSIC
2294     bool done = l2ap_run_information_requests();
2295     if (done) return;
2296 #endif
2297 
2298 #if defined(ENABLE_CLASSIC) || defined(ENABLE_BLE)
2299     btstack_linked_list_iterator_t it;
2300 #endif
2301 
2302 #ifdef ENABLE_CLASSIC
2303     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2304     while (btstack_linked_list_iterator_has_next(&it)){
2305 
2306         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2307 
2308         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CLASSIC) continue;
2309 
2310         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
2311         bool finalized = l2cap_run_for_classic_channel(channel);
2312 
2313         if (!finalized) {
2314 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2315             l2cap_run_for_classic_channel_ertm(channel);
2316 #endif
2317         }
2318     }
2319 #endif
2320 
2321 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2322     l2cap_cbm_run_channels();
2323 #endif
2324 
2325 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2326     l2cap_ecbm_run_channels();
2327 #endif
2328 
2329 #ifdef ENABLE_BLE
2330     // send l2cap con paramter update if necessary
2331     hci_connections_get_iterator(&it);
2332     while(btstack_linked_list_iterator_has_next(&it)){
2333         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
2334         if ((connection->address_type != BD_ADDR_TYPE_LE_PUBLIC) && (connection->address_type != BD_ADDR_TYPE_LE_RANDOM)) continue;
2335         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
2336         switch (connection->le_con_parameter_update_state){
2337             case CON_PARAMETER_UPDATE_SEND_REQUEST:
2338                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2339                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, l2cap_next_sig_id(),
2340                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
2341                 break;
2342             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
2343                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
2344                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
2345                 break;
2346             case CON_PARAMETER_UPDATE_DENY:
2347                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2348                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
2349                 break;
2350             default:
2351                 break;
2352         }
2353     }
2354 #endif
2355 
2356     if (l2cap_call_notify_channel_in_run){
2357         l2cap_call_notify_channel_in_run = false;
2358         l2cap_notify_channel_can_send();
2359     }
2360 
2361     // log_info("l2cap_run: exit");
2362 }
2363 
2364 #ifdef ENABLE_CLASSIC
2365 static void l2cap_ready_to_connect(l2cap_channel_t * channel){
2366 
2367 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2368     // assumption: outgoing connection
2369     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
2370         // ERTM requested: trigger information request if not already started then wait for response
2371         hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
2372         switch (connection->l2cap_state.information_state){
2373             case L2CAP_INFORMATION_STATE_DONE:
2374                 break;
2375             case L2CAP_INFORMATION_STATE_IDLE:
2376                 connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2377                 /* fall through */
2378             default:
2379                 channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
2380                 return;
2381         }
2382     }
2383 #endif
2384 
2385     // fine, go ahead
2386     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
2387 }
2388 
2389 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
2390     if ((channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE) || (channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION)) {
2391         log_info("connection complete con_handle %04x - for channel %p cid 0x%04x", (int) con_handle, channel, channel->local_cid);
2392         channel->con_handle = con_handle;
2393         // query remote features if pairing is required
2394         if (channel->required_security_level > LEVEL_0){
2395             channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
2396             hci_remote_features_query(con_handle);
2397         } else {
2398             l2cap_ready_to_connect(channel);
2399         }
2400     }
2401 }
2402 
2403 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
2404     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
2405 
2406     bool security_required = channel->required_security_level > LEVEL_0;
2407 
2408     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) != 0){
2409 
2410         // Core V5.2, Vol 3, Part C, 5.2.2.2 - Security Mode 4
2411         //   When a remote device attempts to access a service offered by a Bluetooth device that is in security mode 4
2412         //   and a sufficient link key exists and authentication has not been performed the local device shall authenticate
2413         //   the remote device and enable encryption after the channel establishment request is received but before a channel
2414         //   establishment confirmation (L2CAP_ConnectRsp with result code of 0x0000 or a higher-level channel establishment
2415         //   confirmation such as that of RFCOMM) is sent.
2416 
2417         //   If the remote device has indicated support for Secure Simple Pairing, a channel establishment request is
2418         //   received for a service other than SDP, and encryption has not yet been enabled, then the local device shall
2419         //   disconnect the ACL link with error code 0x05 - Authentication Failure.
2420 
2421         // => Disconnect if l2cap request received in mode 4 and ssp supported, non-sdp psm, not encrypted, no link key available
2422         if ((gap_get_security_mode() == GAP_SECURITY_MODE_4)
2423         && gap_ssp_supported_on_both_sides(channel->con_handle)
2424         && (channel->psm != PSM_SDP)
2425         && (gap_encryption_key_size(channel->con_handle) == 0)){
2426             hci_disconnect_security_block(channel->con_handle);
2427             return;
2428         }
2429 
2430         // incoming: assert security requirements
2431         channel->state = L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
2432         if (channel->required_security_level <= gap_security_level(channel->con_handle)){
2433             l2cap_handle_security_level_incoming_sufficient(channel);
2434         } else {
2435             // send connection pending if not already done
2436             if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONN_RESP_PEND) == 0){
2437                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND;
2438             }
2439             gap_request_security_level(channel->con_handle, channel->required_security_level);
2440         }
2441     } else {
2442         // outgoing: we have been waiting for remote supported features
2443         if (security_required){
2444             // request security level
2445             channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
2446             gap_request_security_level(channel->con_handle, channel->required_security_level);
2447         } else {
2448             l2cap_ready_to_connect(channel);
2449         }
2450     }
2451 }
2452 #endif
2453 
2454 #ifdef L2CAP_USES_CHANNELS
2455 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,
2456     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
2457 
2458     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
2459     if (!channel) {
2460         return NULL;
2461     }
2462 
2463     // fill in
2464     channel->packet_handler = packet_handler;
2465     channel->channel_type   = channel_type;
2466     bd_addr_copy(channel->address, address);
2467     channel->address_type = address_type;
2468     channel->psm = psm;
2469     channel->local_mtu  = local_mtu;
2470     channel->remote_mtu = L2CAP_DEFAULT_MTU;
2471     channel->required_security_level = security_level;
2472 
2473     //
2474     channel->local_cid = l2cap_next_local_cid();
2475     channel->con_handle = HCI_CON_HANDLE_INVALID;
2476 
2477     // set initial state
2478     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
2479     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
2480     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
2481     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
2482 
2483     log_info("create channel %p, local_cid 0x%04x", channel, channel->local_cid);
2484 
2485     return channel;
2486 }
2487 
2488 static void l2cap_free_channel_entry(l2cap_channel_t * channel){
2489     log_info("free channel %p, local_cid 0x%04x", channel, channel->local_cid);
2490     // assert all timers are stopped
2491     l2cap_stop_rtx(channel);
2492 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2493     l2cap_ertm_stop_retransmission_timer(channel);
2494     l2cap_ertm_stop_monitor_timer(channel);
2495 #endif
2496     // free  memory
2497     btstack_memory_l2cap_channel_free(channel);
2498 }
2499 #endif
2500 
2501 #ifdef ENABLE_CLASSIC
2502 
2503 /**
2504  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
2505  * @param packet_handler
2506  * @param address
2507  * @param psm
2508  * @param mtu
2509  * @param local_cid
2510  */
2511 
2512 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){
2513     // limit MTU to the size of our outgoing HCI buffer
2514     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
2515 
2516 	// determine security level based on psm
2517 	const gap_security_level_t security_level = l2cap_security_level_0_allowed_for_PSM(psm) ? LEVEL_0 : gap_get_security_level();
2518 	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);
2519 
2520     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);
2521     if (!channel) {
2522         return BTSTACK_MEMORY_ALLOC_FAILED;
2523     }
2524 
2525 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2526     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2527 #endif
2528 
2529     // add to connections list
2530     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2531 
2532     // store local_cid
2533     if (out_local_cid){
2534        *out_local_cid = channel->local_cid;
2535     }
2536 
2537 	// state: L2CAP_STATE_WILL_SEND_CREATE_CONNECTION
2538 
2539     // check if hci connection is already usable,
2540     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
2541     if (conn && conn->state == OPEN){
2542     	// simulate connection complete
2543 	    l2cap_handle_connection_complete(conn->con_handle, channel);
2544 
2545 	    // state: L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES or L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST
2546 
2547         // simulate if remote supported features if requested and already received
2548         if ((channel->state == L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) && hci_remote_features_available(conn->con_handle)) {
2549         	// simulate remote features received
2550             l2cap_handle_remote_supported_features_received(channel);
2551         }
2552     }
2553 
2554     l2cap_run();
2555 
2556     return ERROR_CODE_SUCCESS;
2557 }
2558 
2559 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
2560     // mark all channels before emitting open events as these could trigger new connetion requests to the same device
2561     btstack_linked_list_iterator_t it;
2562     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2563     while (btstack_linked_list_iterator_has_next(&it)){
2564         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2565         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2566         if (bd_addr_cmp( channel->address, address) != 0) continue;
2567         // channel for this address found
2568         switch (channel->state){
2569             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2570             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2571                 channel->state = L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD;
2572                 break;
2573             default:
2574                 break;
2575         }
2576     }
2577     // emit and free marked entries. restart loop to deal with list changes
2578     int done = 0;
2579     while (!done) {
2580         done = 1;
2581         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2582         while (btstack_linked_list_iterator_has_next(&it)){
2583             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2584             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2585             if (channel->state == L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD){
2586                 done = 0;
2587                 // failure, forward error code
2588                 l2cap_handle_channel_open_failed(channel, status);
2589                 // discard channel
2590                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2591                 l2cap_free_channel_entry(channel);
2592                 break;
2593             }
2594         }
2595     }
2596 
2597 }
2598 
2599 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
2600     btstack_linked_list_iterator_t it;
2601     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2602     while (btstack_linked_list_iterator_has_next(&it)){
2603         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2604         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2605         if ( ! bd_addr_cmp( channel->address, address) ){
2606             l2cap_handle_connection_complete(handle, channel);
2607         }
2608     }
2609 
2610 #ifdef ENABLE_L2CAP_INFORMATION_REQUESTS_ON_CONNECT
2611     // trigger query of extended features and fixed channels right away (instead of later)
2612     hci_connection_t * hci_connection = hci_connection_for_handle(handle);
2613     btstack_assert(hci_connection != NULL);
2614     hci_connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2615 #endif
2616 
2617     // process
2618     l2cap_run();
2619 }
2620 #endif
2621 
2622 static bool l2cap_channel_ready_to_send(l2cap_channel_t * channel){
2623     switch (channel->channel_type){
2624 #ifdef ENABLE_CLASSIC
2625         case L2CAP_CHANNEL_TYPE_CLASSIC:
2626             if (channel->state != L2CAP_STATE_OPEN) return false;
2627 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2628             // send if we have more data and remote windows isn't full yet
2629             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2630                 if (channel->unacked_frames >= btstack_min(channel->num_stored_tx_frames, channel->remote_tx_window_size)) return false;
2631                 return hci_can_send_acl_packet_now(channel->con_handle);
2632             }
2633 #endif
2634             if (!channel->waiting_for_can_send_now) return false;
2635             return hci_can_send_acl_packet_now(channel->con_handle);
2636         case L2CAP_CHANNEL_TYPE_FIXED_CLASSIC:
2637         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2638             if (!channel->waiting_for_can_send_now) return false;
2639             return hci_can_send_acl_classic_packet_now();
2640 #endif
2641 #ifdef ENABLE_BLE
2642         case L2CAP_CHANNEL_TYPE_FIXED_LE:
2643             if (!channel->waiting_for_can_send_now) return false;
2644             return hci_can_send_acl_le_packet_now();
2645 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2646         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
2647             if (channel->state != L2CAP_STATE_OPEN) return false;
2648             if (channel->send_sdu_buffer == NULL) return false;
2649             if (channel->credits_outgoing == 0u) return false;
2650             return hci_can_send_acl_packet_now(channel->con_handle);
2651 #endif
2652 #endif
2653 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2654         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
2655             if (channel->state != L2CAP_STATE_OPEN) return false;
2656             if (channel->send_sdu_buffer == NULL) return false;
2657             if (channel->credits_outgoing == 0u) return false;
2658             return hci_can_send_acl_packet_now(channel->con_handle);
2659 #endif
2660         default:
2661             return false;
2662     }
2663 }
2664 
2665 static void l2cap_channel_trigger_send(l2cap_channel_t * channel){
2666     switch (channel->channel_type){
2667 #ifdef ENABLE_CLASSIC
2668         case L2CAP_CHANNEL_TYPE_CLASSIC:
2669 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2670             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2671                 l2cap_ertm_channel_send_information_frame(channel);
2672                 return;
2673             }
2674 #endif
2675             channel->waiting_for_can_send_now = 0;
2676             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2677             break;
2678         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2679         case L2CAP_CHANNEL_TYPE_FIXED_CLASSIC:
2680             channel->waiting_for_can_send_now = 0;
2681             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2682             break;
2683 #endif
2684 #ifdef ENABLE_BLE
2685         case L2CAP_CHANNEL_TYPE_FIXED_LE:
2686             channel->waiting_for_can_send_now = 0;
2687             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2688             break;
2689 #endif
2690 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2691         case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
2692             l2cap_credit_based_send_pdu(channel);
2693             break;
2694 #endif
2695 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2696         case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
2697             l2cap_credit_based_send_pdu(channel);
2698             break;
2699 #endif
2700         default:
2701             btstack_unreachable();
2702             break;
2703     }
2704 }
2705 
2706 static void l2cap_notify_channel_can_send(void){
2707     bool done = false;
2708     while (!done){
2709         done = true;
2710         btstack_linked_list_iterator_t it;
2711         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2712         while (btstack_linked_list_iterator_has_next(&it)){
2713             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2714             bool ready = l2cap_channel_ready_to_send(channel);
2715             if (!ready) continue;
2716 
2717             // requeue channel for fairness
2718             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2719             btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2720 
2721             // trigger sending
2722             l2cap_channel_trigger_send(channel);
2723 
2724             // exit inner loop as we just broke the iterator, but try again
2725             done = false;
2726             break;
2727         }
2728     }
2729 }
2730 
2731 #ifdef L2CAP_USES_CHANNELS
2732 
2733 uint8_t l2cap_disconnect(uint16_t local_cid){
2734     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2735     if (!channel) {
2736         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
2737     }
2738     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2739     l2cap_run();
2740     return ERROR_CODE_SUCCESS;
2741 }
2742 
2743 static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){
2744     // open cannot fail for for incoming connections
2745     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0;
2746 
2747     // check state
2748     switch (channel->state){
2749         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2750         case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2751         case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES:
2752         case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2753         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
2754         case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES:
2755         case L2CAP_STATE_WAIT_CONNECT_RSP:
2756         case L2CAP_STATE_CONFIG:
2757         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
2758         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
2759         case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE:
2760         case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD:
2761             return 1;
2762 
2763         case L2CAP_STATE_OPEN:
2764         case L2CAP_STATE_CLOSED:
2765         case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES:
2766         case L2CAP_STATE_WAIT_DISCONNECT:
2767         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY:
2768         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
2769         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
2770         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2771         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
2772         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
2773         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
2774         case L2CAP_STATE_INVALID:
2775         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2776             return 0;
2777 
2778         default:
2779             // get a "warning" about new states
2780             btstack_assert(false);
2781             return 0;
2782     }
2783 }
2784 #endif
2785 
2786 #ifdef ENABLE_CLASSIC
2787 static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){
2788     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2789         l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2790     } else {
2791         l2cap_handle_channel_closed(channel);
2792     }
2793     l2cap_free_channel_entry(channel);
2794 }
2795 #endif
2796 
2797 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2798 static void l2cap_handle_hci_le_disconnect_event(l2cap_channel_t * channel){
2799     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2800         l2cap_cbm_emit_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2801     } else {
2802         l2cap_emit_channel_closed(channel);
2803     }
2804     l2cap_free_channel_entry(channel);
2805 }
2806 #endif
2807 
2808 #ifdef ENABLE_CLASSIC
2809 static void l2cap_check_classic_timeout(hci_con_handle_t handle){
2810     if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) {
2811         return;
2812     }
2813     if (hci_authentication_active_for_handle(handle)) {
2814         return;
2815     }
2816     bool hci_con_used = false;
2817     btstack_linked_list_iterator_t it;
2818     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2819     while (btstack_linked_list_iterator_has_next(&it)){
2820         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2821         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2822         if (channel->con_handle != handle) continue;
2823         hci_con_used = true;
2824         break;
2825     }
2826     if (hci_con_used) {
2827         return;
2828     }
2829     if (!hci_can_send_command_packet_now()) {
2830         return;
2831     }
2832     hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
2833 }
2834 
2835 static void l2cap_handle_features_complete(hci_con_handle_t handle){
2836     if (hci_remote_features_available(handle) == false){
2837         return;
2838     }
2839     btstack_linked_list_iterator_t it;
2840     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2841     while (btstack_linked_list_iterator_has_next(&it)){
2842         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2843         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2844         if (channel->con_handle != handle) continue;
2845         log_info("remote supported features, channel %p, cid %04x - state %u", channel, channel->local_cid, channel->state);
2846         l2cap_handle_remote_supported_features_received(channel);
2847     }
2848 }
2849 
2850 static void l2cap_handle_security_level_incoming_sufficient(l2cap_channel_t * channel){
2851     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2852     l2cap_emit_incoming_connection(channel);
2853 }
2854 
2855 static void l2cap_handle_security_level(hci_con_handle_t handle, gap_security_level_t actual_level){
2856     log_info("security level update for handle 0x%04x", handle);
2857 
2858     // trigger l2cap information requests
2859     if (actual_level > LEVEL_0){
2860         hci_connection_t * hci_connection = hci_connection_for_handle(handle);
2861         btstack_assert(hci_connection != NULL);
2862         if (hci_connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
2863             hci_connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2864         }
2865     }
2866 
2867     bool done = false;
2868     while (!done){
2869         done = true;
2870         btstack_linked_list_iterator_t it;
2871         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2872         while (btstack_linked_list_iterator_has_next(&it)){
2873             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2874             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2875             if (channel->con_handle != handle) continue;
2876 
2877             gap_security_level_t required_level = channel->required_security_level;
2878 
2879             log_info("channel %p, cid %04x - state %u: actual %u >= required %u?", channel, channel->local_cid, channel->state, actual_level, required_level);
2880 
2881             switch (channel->state){
2882                 case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2883                     if (actual_level >= required_level){
2884                         l2cap_handle_security_level_incoming_sufficient(channel);
2885                     } else {
2886                         channel->reason = L2CAP_CONNECTION_RESULT_SECURITY_BLOCK;
2887                         channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2888                     }
2889                     break;
2890 
2891                 case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2892                     if (actual_level >= required_level){
2893                         l2cap_ready_to_connect(channel);
2894                     } else {
2895                         // security level insufficient, report error and free channel
2896                         l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY);
2897                         btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t  *) channel);
2898                         l2cap_free_channel_entry(channel);
2899                     }
2900                     break;
2901 
2902                 default:
2903                     break;
2904             }
2905         }
2906     }
2907 }
2908 #endif
2909 
2910 #ifdef L2CAP_USES_CHANNELS
2911 static void l2cap_handle_disconnection_complete(hci_con_handle_t handle){
2912     // collect channels to close
2913     btstack_linked_list_t channels_to_close = NULL;
2914     btstack_linked_list_iterator_t it;
2915     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2916     while (btstack_linked_list_iterator_has_next(&it)) {
2917         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2918         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2919         if (channel->con_handle != handle) continue;
2920         btstack_linked_list_iterator_remove(&it);
2921         btstack_linked_list_add(&channels_to_close, (btstack_linked_item_t *) channel);
2922     }
2923     // send l2cap open failed or closed events for all channels on this handle and free them
2924     btstack_linked_list_iterator_init(&it, &channels_to_close);
2925     while (btstack_linked_list_iterator_has_next(&it)) {
2926         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2927         btstack_linked_list_iterator_remove(&it);
2928         switch(channel->channel_type){
2929 #ifdef ENABLE_CLASSIC
2930             case L2CAP_CHANNEL_TYPE_CLASSIC:
2931                 l2cap_handle_hci_disconnect_event(channel);
2932                 break;
2933 #endif
2934 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
2935             case L2CAP_CHANNEL_TYPE_CHANNEL_CBM:
2936                 l2cap_handle_hci_le_disconnect_event(channel);
2937                 break;
2938 #endif
2939 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
2940             case L2CAP_CHANNEL_TYPE_CHANNEL_ECBM:
2941                 switch (channel->state) {
2942                     case L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST:
2943                     case L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE:
2944                         // emit open failed if disconnected before connection complete
2945                         l2cap_ecbm_emit_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2946                         break;
2947                     case L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST:
2948                     case L2CAP_STATE_WAIT_ENHANCED_RENEGOTIATION_RESPONSE:
2949                         // emit reconfigure failure - result = 0xffff
2950                         l2cap_ecbm_emit_reconfigure_complete(channel, 0xffff);
2951                         break;
2952                     default:
2953                         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
2954                         break;
2955                 }
2956                 l2cap_free_channel_entry(channel);
2957                 break;
2958 #endif
2959             default:
2960                 break;
2961         }
2962     }
2963 }
2964 #endif
2965 
2966 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
2967 
2968     UNUSED(packet_type); // ok: registered with hci_event_callback_registration
2969     UNUSED(cid);         // ok: there is no channel
2970     UNUSED(size);        // ok: fixed format events read from HCI buffer
2971 
2972 #ifdef ENABLE_CLASSIC
2973     bd_addr_t address;
2974     gap_security_level_t security_level;
2975 #endif
2976 #ifdef L2CAP_USES_CHANNELS
2977     hci_con_handle_t handle;
2978 #endif
2979 
2980     switch(hci_event_packet_get_type(packet)){
2981 
2982         // Notify channel packet handler if they can send now
2983         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2984         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
2985         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
2986 #ifdef ENABLE_TESTING_SUPPORT
2987         case HCI_EVENT_NOP:
2988 #endif
2989             l2cap_call_notify_channel_in_run = true;
2990             break;
2991 
2992         case HCI_EVENT_COMMAND_STATUS:
2993 #ifdef ENABLE_CLASSIC
2994             // check command status for create connection for errors
2995             if (hci_event_command_status_get_command_opcode(packet) == HCI_OPCODE_HCI_CREATE_CONNECTION){
2996                 // cache outgoing address and reset
2997                 (void)memcpy(address, l2cap_outgoing_classic_addr, 6);
2998                 memset(l2cap_outgoing_classic_addr, 0, 6);
2999                 // error => outgoing connection failed
3000                 uint8_t status = hci_event_command_status_get_status(packet);
3001                 if (status){
3002                     l2cap_handle_connection_failed_for_addr(address, status);
3003                 }
3004             }
3005 #endif
3006             l2cap_run();    // try sending signaling packets first
3007             break;
3008 
3009 #ifdef ENABLE_CLASSIC
3010         // handle connection complete events
3011         case HCI_EVENT_CONNECTION_COMPLETE:
3012             reverse_bd_addr(&packet[5], address);
3013             if (packet[2] == 0){
3014                 handle = little_endian_read_16(packet, 3);
3015                 l2cap_handle_connection_success_for_addr(address, handle);
3016             } else {
3017                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
3018             }
3019             break;
3020 
3021         // handle successful create connection cancel command
3022         case HCI_EVENT_COMMAND_COMPLETE:
3023             if (hci_event_command_complete_get_command_opcode(packet) == HCI_OPCODE_HCI_CREATE_CONNECTION_CANCEL) {
3024                 if (packet[5] == 0){
3025                     reverse_bd_addr(&packet[6], address);
3026                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
3027                     l2cap_handle_connection_failed_for_addr(address, 0x16);
3028                 }
3029             }
3030             l2cap_run();    // try sending signaling packets first
3031             break;
3032 #endif
3033 
3034 #ifdef L2CAP_USES_CHANNELS
3035         // handle disconnection complete events
3036         case HCI_EVENT_DISCONNECTION_COMPLETE:
3037             handle = little_endian_read_16(packet, 3);
3038             l2cap_handle_disconnection_complete(handle);
3039             break;
3040 #endif
3041 
3042         // HCI Connection Timeouts
3043 #ifdef ENABLE_CLASSIC
3044         case L2CAP_EVENT_TIMEOUT_CHECK:
3045             handle = little_endian_read_16(packet, 2);
3046             l2cap_check_classic_timeout(handle);
3047             break;
3048 
3049         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
3050         case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE:
3051             handle = little_endian_read_16(packet, 3);
3052             l2cap_handle_features_complete(handle);
3053             break;
3054 
3055         case GAP_EVENT_SECURITY_LEVEL:
3056             handle = little_endian_read_16(packet, 2);
3057             security_level = (gap_security_level_t) packet[4];
3058             l2cap_handle_security_level(handle, security_level);
3059             break;
3060 #endif
3061         default:
3062             break;
3063     }
3064 
3065     l2cap_run();
3066 }
3067 
3068 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t cid, uint16_t data){
3069     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indicates the connection was refused."
3070     if (l2cap_signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
3071         l2cap_signaling_responses[l2cap_signaling_responses_pending].handle = handle;
3072         l2cap_signaling_responses[l2cap_signaling_responses_pending].code = code;
3073         l2cap_signaling_responses[l2cap_signaling_responses_pending].sig_id = sig_id;
3074         l2cap_signaling_responses[l2cap_signaling_responses_pending].cid = cid;
3075         l2cap_signaling_responses[l2cap_signaling_responses_pending].data = data;
3076         l2cap_signaling_responses_pending++;
3077         l2cap_run();
3078     }
3079 }
3080 
3081 #ifdef ENABLE_CLASSIC
3082 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint8_t identifier){
3083     switch (channel->state){
3084         case L2CAP_STATE_CONFIG:
3085         case L2CAP_STATE_OPEN:
3086         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
3087         case L2CAP_STATE_WAIT_DISCONNECT:
3088             break;
3089         default:
3090             // ignore in other states
3091             return;
3092     }
3093 
3094     channel->remote_sig_id = identifier;
3095     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
3096     l2cap_run();
3097 }
3098 
3099 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
3100 
3101     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
3102     l2cap_service_t *service = l2cap_get_service(psm);
3103     if (!service) {
3104         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CONNECTION_RESULT_PSM_NOT_SUPPORTED);
3105         return;
3106     }
3107 
3108     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
3109     if (!hci_connection) {
3110         //
3111         log_error("no hci_connection for handle %u", handle);
3112         return;
3113     }
3114 
3115     // if SC only mode is active and service requires encryption, reject connection if SC not active or use security level
3116     gap_security_level_t required_level = service->required_security_level;
3117     if (gap_get_secure_connections_only_mode() && (required_level != LEVEL_0)){
3118         if (gap_secure_connection(handle)){
3119             required_level = LEVEL_4;
3120         } else {
3121             l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CONNECTION_RESULT_SECURITY_BLOCK);
3122             return;
3123         }
3124     }
3125 
3126     // alloc structure
3127     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, hci_connection->address, BD_ADDR_TYPE_ACL,
3128     psm, service->mtu, required_level);
3129     if (!channel){
3130         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE);
3131         return;
3132     }
3133 
3134     channel->con_handle = handle;
3135     channel->remote_cid = source_cid;
3136     channel->remote_sig_id = sig_id;
3137 
3138     // limit local mtu to max acl packet length - l2cap header
3139     if (channel->local_mtu > l2cap_max_mtu()) {
3140         channel->local_mtu = l2cap_max_mtu();
3141     }
3142 
3143     // set initial state
3144     channel->state =     L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
3145     channel->state_var = L2CAP_CHANNEL_STATE_VAR_INCOMING;
3146 
3147     // add to connections list
3148     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
3149 
3150     //
3151     if (required_level > LEVEL_0){
3152         // send conn resp pending if remote supported features have not been received yet
3153         if (hci_remote_features_available(handle)) {
3154             l2cap_handle_remote_supported_features_received(channel);
3155         } else {
3156             channel->state_var |= L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND;
3157             hci_remote_features_query(handle);
3158         }
3159     } else {
3160         l2cap_handle_security_level_incoming_sufficient(channel);
3161     }
3162 }
3163 
3164 void l2cap_accept_connection(uint16_t local_cid){
3165     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
3166     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3167     if (!channel) {
3168         log_error("accept called but local_cid 0x%x not found", local_cid);
3169         return;
3170     }
3171 
3172 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3173     // configure L2CAP Basic mode
3174     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
3175 #endif
3176 
3177     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
3178 
3179     // process
3180     l2cap_run();
3181 }
3182 
3183 void l2cap_decline_connection(uint16_t local_cid){
3184     log_info("decline local_cid 0x%x", local_cid);
3185     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
3186     if (!channel) {
3187         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
3188         return;
3189     }
3190     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
3191     channel->reason = L2CAP_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE;
3192     l2cap_run();
3193 }
3194 
3195 // @pre command len is valid, see check in l2cap_signaling_handler_channel
3196 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
3197 
3198 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3199     uint8_t use_fcs = 1;
3200 #endif
3201 
3202     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
3203 
3204     uint16_t flags = little_endian_read_16(command, 6);
3205     if (flags & 1) {
3206         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
3207     }
3208 
3209     // accept the other's configuration options
3210     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3211     uint16_t pos     = 8;
3212     while (pos < end_pos){
3213         uint8_t option_hint = command[pos] >> 7;
3214         uint8_t option_type = command[pos] & 0x7f;
3215         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
3216         pos++;
3217         uint8_t length = command[pos++];
3218         // MTU { type(8): 1, len(8):2, MTU(16) }
3219         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) && (length == 2)){
3220             channel->remote_mtu = little_endian_read_16(command, pos);
3221             log_info("Remote MTU %u", channel->remote_mtu);
3222             if (channel->remote_mtu > l2cap_max_mtu()){
3223                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
3224                 channel->remote_mtu = l2cap_max_mtu();
3225             }
3226             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
3227         }
3228         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
3229         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT) && (length == 2)){
3230             channel->flush_timeout = little_endian_read_16(command, pos);
3231             log_info("Flush timeout: %u ms", channel->flush_timeout);
3232         }
3233 
3234 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3235         // Retransmission and Flow Control Option
3236         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
3237             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
3238             switch(channel->mode){
3239                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
3240                     // Store remote config
3241                     channel->remote_tx_window_size = command[pos+1];
3242                     channel->remote_max_transmit   = command[pos+2];
3243                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
3244                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
3245                     {
3246                         uint16_t remote_mps = little_endian_read_16(command, pos + 7);
3247                         // optimize our tx buffer configuration based on actual remote mps if remote mps is smaller than planned
3248                         if (remote_mps < channel->remote_mps){
3249                             // get current tx storage
3250                             uint16_t num_bytes_per_tx_buffer_before = sizeof(l2cap_ertm_tx_packet_state_t) + channel->remote_mps;
3251                             uint16_t tx_storage = channel->num_tx_buffers * num_bytes_per_tx_buffer_before;
3252 
3253                             channel->remote_mps = remote_mps;
3254                             uint16_t num_bytes_per_tx_buffer_now = sizeof(l2cap_ertm_tx_packet_state_t) + channel->remote_mps;
3255                             channel->num_tx_buffers = tx_storage / num_bytes_per_tx_buffer_now;
3256                             uint32_t total_storage = (sizeof(l2cap_ertm_rx_packet_state_t) + channel->local_mps) * channel->num_rx_buffers + tx_storage + channel->local_mtu;
3257                             l2cap_ertm_setup_buffers(channel, (uint8_t *) channel->rx_packets_state, total_storage);
3258                         }
3259                         // limit remote mtu by our tx buffers. Include 2 bytes SDU Length
3260                         uint16_t effective_mtu = channel->remote_mps * channel->num_tx_buffers - 2;
3261                         channel->remote_mtu    = btstack_min( effective_mtu, channel->remote_mtu);
3262                     }
3263                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
3264                         channel->remote_tx_window_size,
3265                         channel->remote_max_transmit,
3266                         channel->remote_retransmission_timeout_ms,
3267                         channel->remote_monitor_timeout_ms,
3268                         channel->remote_mps);
3269                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
3270                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3271                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3272                     } else {
3273                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
3274                     }
3275                     break;
3276                 case L2CAP_CHANNEL_MODE_BASIC:
3277                     switch (mode){
3278                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
3279                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
3280                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
3281                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3282                             }
3283                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
3284                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
3285                             break;
3286                         default: // case L2CAP_CHANNEL_MODE_BASIC:
3287                             // TODO store and evaluate configuration
3288                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
3289                             break;
3290                     }
3291                     break;
3292                 default:
3293                     break;
3294             }
3295         }
3296         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
3297             use_fcs = command[pos];
3298         }
3299 #endif
3300         // check for unknown options
3301         if ((option_hint == 0) && ((option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) || (option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE))){
3302             log_info("l2cap cid %u, unknown option 0x%02x", channel->local_cid, option_type);
3303             channel->unknown_option = option_type;
3304             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
3305         }
3306         pos += length;
3307     }
3308 
3309 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3310         // "FCS" has precedence over "No FCS"
3311         uint8_t update = channel->fcs_option || use_fcs;
3312         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
3313         channel->fcs_option = update;
3314         // If ERTM mandatory, but remote didn't send Retransmission and Flowcontrol options -> disconnect
3315         if (((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM) == 0) & (channel->ertm_mandatory)){
3316             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3317         }
3318 #endif
3319 }
3320 
3321 // @pre command len is valid, see check in l2cap_signaling_handler_channel
3322 static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint16_t result, uint8_t *command){
3323     log_info("l2cap_signaling_handle_configure_response");
3324 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3325     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3326     uint16_t pos     = 10;
3327     while (pos < end_pos){
3328         uint8_t option_hint = command[pos] >> 7;
3329         uint8_t option_type = command[pos] & 0x7f;
3330         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
3331         pos++;
3332         uint8_t length = command[pos++];
3333 
3334         // Retransmission and Flow Control Option
3335         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
3336             switch (channel->mode){
3337                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
3338                     if (channel->ertm_mandatory){
3339                         // ??
3340                     } else {
3341                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
3342                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
3343                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3344                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3345                         }
3346                     }
3347                     break;
3348                 case L2CAP_CHANNEL_MODE_BASIC:
3349                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
3350                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
3351                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3352                     }
3353                     break;
3354                 default:
3355                     break;
3356             }
3357         }
3358 
3359         // check for unknown options
3360         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
3361             log_info("l2cap cid %u, unknown option 0x%02x", channel->local_cid, option_type);
3362             channel->unknown_option = option_type;
3363             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
3364         }
3365 
3366         pos += length;
3367     }
3368 #else
3369     UNUSED(channel);  // ok: no code
3370     UNUSED(result);   // ok: no code
3371     UNUSED(command);  // ok: no code
3372 #endif
3373 }
3374 
3375 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
3376     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
3377     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
3378     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
3379     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
3380     if (channel->state == L2CAP_STATE_OPEN) return 0;
3381     return 1;
3382 }
3383 
3384 
3385 // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
3386 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
3387 
3388     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3389     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
3390     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3391     uint16_t result = 0;
3392 
3393     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
3394 
3395     // handle DISCONNECT REQUESTS seperately
3396     if (code == DISCONNECTION_REQUEST){
3397         l2cap_handle_disconnect_request(channel, identifier);
3398         return;
3399     }
3400 
3401     // @STATEMACHINE(l2cap)
3402     switch (channel->state) {
3403 
3404         case L2CAP_STATE_WAIT_CONNECT_RSP:
3405             switch (code){
3406                 case CONNECTION_RESPONSE:
3407                     if (cmd_len < 8){
3408                         // command imcomplete
3409                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3410                         break;
3411                     }
3412                     l2cap_stop_rtx(channel);
3413                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3414                     switch (result) {
3415                         case 0:
3416                             // successful connection
3417                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3418                             channel->state = L2CAP_STATE_CONFIG;
3419                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
3420                             break;
3421                         case 1:
3422                             // connection pending. get some coffee, but start the ERTX
3423                             l2cap_start_ertx(channel);
3424                             break;
3425                         default:
3426                             // channel closed
3427                             channel->state = L2CAP_STATE_CLOSED;
3428                             // map l2cap connection response result to BTstack status enumeration
3429                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
3430 
3431                             // drop link key if security block
3432                             if ((L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result) == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
3433                                 gap_drop_link_key_for_bd_addr(channel->address);
3434                             }
3435 
3436                             // discard channel
3437                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3438                             l2cap_free_channel_entry(channel);
3439                             break;
3440                     }
3441                     break;
3442 
3443                 default:
3444                     //@TODO: implement other signaling packets
3445                     break;
3446             }
3447             break;
3448 
3449         case L2CAP_STATE_CONFIG:
3450             switch (code) {
3451                 case CONFIGURE_REQUEST:
3452                     if (cmd_len < 4){
3453                         // command incomplete
3454                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3455                         break;
3456                     }
3457                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
3458                     l2cap_signaling_handle_configure_request(channel, command);
3459                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
3460                         // only done if continuation not set
3461                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
3462                     }
3463                     break;
3464                 case CONFIGURE_RESPONSE:
3465                     if (cmd_len < 6){
3466                         // command incomplete
3467                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
3468                         break;
3469                     }
3470                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3471                     l2cap_stop_rtx(channel);
3472                     l2cap_signaling_handle_configure_response(channel, result, command);
3473                     switch (result){
3474                         case 0: // success
3475                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
3476                             break;
3477                         case 4: // pending
3478                             l2cap_start_ertx(channel);
3479                             break;
3480                         default:
3481 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3482                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
3483                                 // remote does not offer ertm but it's required
3484                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3485                                 break;
3486                             }
3487 #endif
3488                             // retry on negative result
3489                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
3490                             break;
3491                     }
3492                     break;
3493                 default:
3494                     break;
3495             }
3496             if (l2cap_channel_ready_for_open(channel)){
3497 
3498 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3499                 // assert that packet can be stored in fragment buffers in ertm
3500                 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3501                     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
3502                     uint16_t usable_mtu = channel->num_tx_buffers == 1 ? effective_mps : channel->num_tx_buffers * effective_mps - 2;
3503                     if (usable_mtu < channel->remote_mtu){
3504                         log_info("Remote MTU %u > max storable ERTM packet, only using MTU = %u", channel->remote_mtu, usable_mtu);
3505                         channel->remote_mtu = usable_mtu;
3506                     }
3507                 }
3508 #endif
3509                 // for open:
3510                 channel->state = L2CAP_STATE_OPEN;
3511                 l2cap_emit_channel_opened(channel, 0);
3512             }
3513             break;
3514 
3515         case L2CAP_STATE_WAIT_DISCONNECT:
3516             switch (code) {
3517                 case DISCONNECTION_RESPONSE:
3518                     l2cap_finalize_channel_close(channel);
3519                     break;
3520                 default:
3521                     //@TODO: implement other signaling packets
3522                     break;
3523             }
3524             break;
3525 
3526         case L2CAP_STATE_CLOSED:
3527             // @TODO handle incoming requests
3528             break;
3529 
3530         case L2CAP_STATE_OPEN:
3531             //@TODO: implement other signaling packets, e.g. re-configure
3532             break;
3533         default:
3534             break;
3535     }
3536     // log_info("new state %u", channel->state);
3537 }
3538 
3539 #ifdef ENABLE_CLASSIC
3540 static void l2cap_handle_information_request_complete(hci_connection_t * connection){
3541 
3542     connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
3543 
3544     // emit event
3545     uint8_t event[8];
3546     event[0] = L2CAP_EVENT_INFORMATION_RESPONSE;
3547     event[1] = sizeof(event) - 2;
3548     little_endian_store_16(event, 2, connection->con_handle);
3549     little_endian_store_16(event, 4, connection->l2cap_state.extended_feature_mask);
3550     little_endian_store_16(event, 6, connection->l2cap_state.fixed_channels_supported);
3551     l2cap_emit_event(event, sizeof(event));
3552 
3553     // trigger connection request
3554     btstack_linked_list_iterator_t it;
3555     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3556     while (btstack_linked_list_iterator_has_next(&it)){
3557         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3558         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3559         if (channel->con_handle != connection->con_handle) continue;
3560 
3561         // incoming connection: information request was triggered after user has accepted connection,
3562         // now: verify channel configuration, esp. if ertm will be mandatory
3563         if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
3564             // default: continue
3565             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
3566 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3567             if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
3568                 // ERTM not possible, select basic mode and release buffer
3569                 channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3570                 l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3571 
3572                 // bail if ERTM is mandatory
3573                 if (channel->ertm_mandatory){
3574                     // We chose 'no resources available' for "ERTM mandatory but you don't even know ERTM exists"
3575                     log_info("ERTM mandatory -> reject connection");
3576                     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
3577                     channel->reason = L2CAP_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE;
3578                 }  else {
3579                     log_info("ERTM not supported by remote -> use Basic mode");
3580                 }
3581             }
3582 #endif
3583             continue;
3584         }
3585 
3586         // outgoing connection: information request is triggered before connection request
3587         if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
3588 
3589 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3590             // if ERTM was requested, but is not listed in extended feature mask:
3591             if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
3592 
3593                 if (channel->ertm_mandatory){
3594                     // bail if ERTM is mandatory
3595                     channel->state = L2CAP_STATE_CLOSED;
3596                     // map l2cap connection response result to BTstack status enumeration
3597                     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
3598                     // discard channel
3599                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3600                     l2cap_free_channel_entry(channel);
3601                     continue;
3602 
3603                 } else {
3604                     // fallback to Basic mode
3605                     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
3606                     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
3607                 }
3608             }
3609 #endif
3610 
3611             // respond to connection request
3612             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
3613             continue;
3614         }
3615     }
3616 }
3617 #endif
3618 
3619 // @pre command len is valid, see check in l2cap_acl_classic_handler
3620 static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
3621 
3622     hci_connection_t * connection;
3623     btstack_linked_list_iterator_t it;
3624 
3625     // get code, signal identifier and command len
3626     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3627     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
3628     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3629 
3630     // general commands without an assigned channel
3631     switch(code) {
3632 
3633         case CONNECTION_REQUEST:
3634             if (cmd_len == 4){
3635                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3636                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3637                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
3638             } else {
3639                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3640             }
3641             return;
3642 
3643         case ECHO_REQUEST:
3644             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
3645             return;
3646 
3647         case INFORMATION_REQUEST:
3648             if (cmd_len == 2) {
3649                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3650                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
3651                 return;
3652             }
3653             break;
3654 
3655         case INFORMATION_RESPONSE:
3656             connection = hci_connection_for_handle(handle);
3657             if (!connection) return;
3658             switch (connection->l2cap_state.information_state){
3659                 case L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE:
3660                     // get extended features from response if valid
3661                     if (cmd_len >= 6) {
3662                         uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3663                         uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3664                         if (result == 0 && info_type == L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) {
3665                             connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3666                         }
3667                         log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
3668                         if ((connection->l2cap_state.extended_feature_mask & 0x80) != 0){
3669                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_FIXED_CHANNELS_REQUEST;
3670                         } else {
3671                             // information request complete
3672                             l2cap_handle_information_request_complete(connection);
3673                         }
3674                     }
3675                     break;
3676                 case L2CAP_INFORMATION_STATE_W4_FIXED_CHANNELS_RESPONSE:
3677                     if (cmd_len >= 12) {
3678                         uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3679                         uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3680                         if (result == 0 && info_type == L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED) {
3681                             connection->l2cap_state.fixed_channels_supported = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3682                         }
3683                         log_info("fixed channels mask 0x%02x", connection->l2cap_state.fixed_channels_supported);
3684                         // information request complete
3685                         l2cap_handle_information_request_complete(connection);
3686                     }
3687                     break;
3688                 default:
3689                     break;
3690             }
3691             return;
3692 
3693 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
3694         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
3695         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
3696         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
3697         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
3698             l2cap_ecbm_signaling_handler_dispatch(handle, L2CAP_CID_SIGNALING, command, sig_id);
3699             return;
3700         case L2CAP_FLOW_CONTROL_CREDIT_INDICATION:
3701             // return if valid
3702             if (l2cap_credit_based_handle_credit_indication(handle, command, cmd_len)) return;
3703             break;
3704 
3705         case COMMAND_REJECT:
3706             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3707             while (btstack_linked_list_iterator_has_next(&it)) {
3708                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3709                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3710                 if (channel->con_handle != handle) continue;
3711                 if (channel->local_sig_id != sig_id) continue;
3712                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE) continue;
3713 
3714                 // open failed
3715                 channel->state = L2CAP_STATE_CLOSED;
3716                 l2cap_ecbm_emit_channel_opened(channel,
3717                                                ERROR_CODE_CONNECTION_REJECTED_DUE_TO_LIMITED_RESOURCES);
3718                 // drop failed channel
3719                 btstack_linked_list_iterator_remove(&it);
3720                 l2cap_free_channel_entry(channel);
3721             }
3722             break;
3723 #endif
3724 
3725         default:
3726             break;
3727     }
3728 
3729     // Get potential destination CID
3730     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3731 
3732     // Find channel for this sig_id and connection handle
3733     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3734     while (btstack_linked_list_iterator_has_next(&it)){
3735         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3736         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3737         if (channel->con_handle != handle) continue;
3738         if (code & 1) {
3739             // match odd commands (responses) by previous signaling identifier
3740             if (channel->local_sig_id == sig_id) {
3741                 l2cap_signaling_handler_channel(channel, command);
3742                 return;
3743             }
3744         } else {
3745             // match even commands (requests) by local channel id
3746             if (channel->local_cid == dest_cid) {
3747                 l2cap_signaling_handler_channel(channel, command);
3748                 return;
3749             }
3750         }
3751     }
3752 
3753     // send command reject
3754     l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3755 }
3756 #endif
3757 
3758 #ifdef L2CAP_USES_CHANNELS
3759 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3760     btstack_linked_list_iterator_t it;
3761     btstack_linked_list_iterator_init(&it, services);
3762     while (btstack_linked_list_iterator_has_next(&it)){
3763         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
3764         if ( service->psm == psm){
3765             return service;
3766         };
3767     }
3768     return NULL;
3769 }
3770 #endif
3771 
3772 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
3773 
3774 static uint8_t l2cap_ecbm_setup_channels(btstack_linked_list_t * channels,
3775                                          btstack_packet_handler_t packet_handler, uint8_t num_channels,
3776                                          hci_connection_t * connection, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
3777     uint8_t i;
3778     uint8_t status = ERROR_CODE_SUCCESS;
3779     for (i=0;i<num_channels;i++){
3780         l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_ECBM, connection->address, connection->address_type, psm, mtu, security_level);
3781         if (!channel) {
3782             status = BTSTACK_MEMORY_ALLOC_FAILED;
3783             break;
3784         }
3785         channel->con_handle = connection->con_handle;
3786         btstack_linked_list_add_tail(channels, (btstack_linked_item_t *) channel);
3787     }
3788 
3789     // free channels if not all allocated
3790     if (status != ERROR_CODE_SUCCESS){
3791         while (true) {
3792             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_pop(channels);
3793             if (channel == NULL) break;
3794             l2cap_free_channel_entry(channel);
3795         }
3796     }
3797 
3798     return status;
3799 }
3800 
3801 static inline l2cap_service_t * l2cap_ecbm_get_service(uint16_t spsm){
3802     return l2cap_get_service_internal(&l2cap_enhanced_services, spsm);
3803 }
3804 
3805 static inline uint8_t l2cap_ecbm_status_for_result(uint16_t result) {
3806     switch (result) {
3807         case L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS:
3808             return ERROR_CODE_SUCCESS;
3809         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_SPSM_NOT_SUPPORTED:
3810             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_PSM;
3811         case L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INSUFFICIENT_RESOURCES_AVAILABLE:
3812             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_RESOURCES;
3813         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHENTICATION:
3814         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHORIZATION:
3815         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_ENCYRPTION_KEY_SIZE_TOO_SHORT:
3816         case L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_ENCRYPTION:
3817             return L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY;
3818         default:
3819             // invalid Source CID, Source CID already allocated, unacceptable parameters
3820             return L2CAP_CONNECTION_RESPONSE_UNKNOWN_ERROR;
3821     }
3822 }
3823 
3824 static void
3825 l2cap_ecbm_emit_incoming_connection(l2cap_channel_t *channel, uint8_t num_channels) {
3826     uint8_t event[16];
3827     event[0] = L2CAP_EVENT_ECBM_INCOMING_CONNECTION;
3828     event[1] = sizeof(event) - 2;
3829     event[2] = channel->address_type;
3830     reverse_bd_addr(channel->address, &event[3]);
3831     little_endian_store_16(event, 9, channel->con_handle);
3832     little_endian_store_16(event, 11, channel->psm);
3833     event[13] = num_channels;
3834     little_endian_store_16(event, 14, channel->local_cid);
3835     hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
3836     (*channel->packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
3837 }
3838 
3839 static uint8_t
3840 l2cap_ecbm_security_status_for_connection_request(hci_con_handle_t handle, gap_security_level_t required_security_level,
3841                                                   bool requires_authorization) {
3842     // check security in increasing error priority
3843     uint8_t security_status = L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS;
3844 
3845     // security: check encryption
3846     if (required_security_level >= LEVEL_2) {
3847         if (gap_encryption_key_size(handle) < 16) {
3848             security_status = L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_ENCYRPTION_KEY_SIZE_TOO_SHORT;
3849         }
3850         if (gap_encryption_key_size(handle) == 0){
3851             security_status = L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_ENCRYPTION;
3852         }
3853     }
3854 
3855     // security: check authentication
3856     if (required_security_level >= LEVEL_3) {
3857         if (!gap_authenticated(handle)) {
3858             security_status = requires_authorization ?
3859                     L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHORIZATION :
3860                     L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INSUFFICIENT_AUTHENTICATION;
3861         }
3862     }
3863     return security_status;
3864 }
3865 
3866 static void l2cap_ecbm_handle_security_level_incoming(l2cap_channel_t * channel){
3867     // count number of l2cap_channels in state L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE with same remote_sig_id
3868     uint8_t sig_id = channel->remote_sig_id;
3869     hci_con_handle_t con_handle = channel->con_handle;
3870 
3871     uint8_t security_status = l2cap_ecbm_security_status_for_connection_request(channel->con_handle,
3872                                                                                 channel->required_security_level,
3873                                                                                 false);
3874     bool security_sufficient = security_status == L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS;
3875 
3876     uint8_t num_channels = 0;
3877     btstack_linked_list_iterator_t it;
3878     btstack_linked_list_iterator_init(&it, &l2cap_channels);
3879     while (btstack_linked_list_iterator_has_next(&it)) {
3880         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3881         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
3882         if (channel->con_handle != con_handle) continue;
3883         if (channel->remote_sig_id != sig_id) continue;
3884         if (channel->state != L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE) continue;
3885         num_channels++;
3886 
3887         if (security_sufficient){
3888             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
3889         } else {
3890             btstack_linked_list_iterator_remove(&it);
3891             btstack_memory_l2cap_channel_free(channel);
3892         }
3893     }
3894 
3895     if (security_sufficient){
3896         l2cap_ecbm_emit_incoming_connection(channel, num_channels);
3897     } else {
3898         // combine signaling cid and number channels for l2cap_register_signaling_response
3899         uint16_t signaling_cid = L2CAP_CID_SIGNALING;
3900         uint16_t num_channels_and_signaling_cid = (num_channels << 8) | signaling_cid;
3901         l2cap_register_signaling_response(con_handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3902                                           num_channels_and_signaling_cid, security_status);
3903     }
3904 }
3905 
3906 void l2cap_ecbm_trigger_pending_connection_responses(hci_con_handle_t con_handle){
3907     bool done = false;
3908     while (!done) {
3909         done = true;
3910         btstack_linked_list_iterator_t it;
3911         btstack_linked_list_iterator_init(&it, &l2cap_channels);
3912         while (btstack_linked_list_iterator_has_next(&it)) {
3913             l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3914             if (channel->channel_type != L2CAP_CHANNEL_TYPE_CHANNEL_ECBM) continue;
3915             if (channel->con_handle != con_handle) continue;
3916             if  (channel->state == L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE) {
3917                 l2cap_ecbm_handle_security_level_incoming(channel);
3918                 done = false;
3919             };
3920         }
3921     }
3922 }
3923 
3924 static int l2cap_ecbm_signaling_handler_dispatch(hci_con_handle_t handle, uint16_t signaling_cid, uint8_t *command,
3925                                                  uint8_t sig_id) {
3926 
3927     hci_connection_t *connection;
3928     btstack_linked_list_iterator_t it;
3929     l2cap_service_t *service;
3930     uint16_t spsm;
3931     uint8_t num_channels;
3932     uint16_t num_channels_and_signaling_cid;
3933     uint8_t i;
3934     uint16_t new_mtu;
3935     uint16_t new_mps;
3936     uint16_t initial_credits;
3937     uint16_t result;
3938     uint8_t status;
3939 
3940     uint8_t code = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3941     uint16_t len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3942     log_info("enhanced dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
3943 
3944     switch (code) {
3945         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
3946             // check size
3947             if (len < 10u) return 0u;
3948 
3949             // get hci connection, bail if not found (must not happen)
3950             connection = hci_connection_for_handle(handle);
3951             btstack_assert(connection != NULL);
3952 
3953             // get num channels to establish
3954             num_channels = (len - 8) / sizeof(uint16_t);
3955 
3956             // combine signaling cid and number channels for l2cap_register_signaling_response
3957             num_channels_and_signaling_cid = (num_channels << 8) | signaling_cid;
3958 
3959             // check if service registered
3960             spsm = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3961             service = l2cap_ecbm_get_service(spsm);
3962 
3963             if (service) {
3964 
3965                 uint16_t remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3966                 uint16_t remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3967                 uint16_t credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
3968 
3969                 // param: check remote mtu
3970                 if (service->mtu > remote_mtu) {
3971                     l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3972                                                       num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_INVALID_PARAMETERS);
3973                     return 1;
3974                 }
3975 
3976                 // check if authentication is required and possible
3977                 bool send_pending = false;
3978                 uint8_t security_status = l2cap_ecbm_security_status_for_connection_request(handle,
3979                                                                                             service->required_security_level,
3980                                                                                             service->requires_authorization);
3981                 if (security_status != L2CAP_ECBM_CONNECTION_RESULT_ALL_SUCCESS) {
3982                     if (gap_get_bondable_mode() != 0) {
3983                         // if possible, send pending and continue
3984                         send_pending = true;
3985                     } else {
3986                         // otherwise, send refused and abort
3987                         l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
3988                                                           num_channels_and_signaling_cid, security_status);
3989                         return 1;
3990                     }
3991                 }
3992 
3993                 // report the last result code != 0
3994                 result = 0;
3995                 // store one of the local channels for the event
3996                 l2cap_channel_t * a_channel = NULL;
3997                 for (i = 0; i < num_channels; i++) {
3998 
3999                     // check source cids
4000                     uint16_t source_cid = little_endian_read_16(command, 12 + (i * 2));
4001                     if (source_cid < 0x40u) {
4002                         result = L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INVALID_SOURCE_CID;
4003                         continue;
4004                     }
4005 
4006                     // go through list of channels for this ACL connection and check if we get a match
4007                     btstack_linked_list_iterator_init(&it, &l2cap_channels);
4008                     bool source_cid_allocated = false;
4009                     while (btstack_linked_list_iterator_has_next(&it)) {
4010                         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4011                         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4012                         if (channel->con_handle != handle) continue;
4013                         if (channel->remote_cid != source_cid) continue;
4014                         source_cid_allocated = true;
4015                         break;
4016                     }
4017                     if (source_cid_allocated) {
4018                         result = 0x00a;
4019                         continue;
4020                     }
4021 
4022                     // setup channel
4023                     l2cap_channel_t *channel = l2cap_create_channel_entry(service->packet_handler,
4024                                                                           L2CAP_CHANNEL_TYPE_CHANNEL_ECBM,
4025                                                                           connection->address,
4026                                                                           connection->address_type, spsm,
4027                                                                           service->mtu,
4028                                                                           service->required_security_level);
4029 
4030                     if (channel == NULL) {
4031                         // Some connections refused – insufficient resources available
4032                         result = 0x004;
4033                         continue;
4034                     }
4035 
4036                     // setup state
4037                     channel->state = L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
4038                     channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
4039                     channel->con_handle = connection->con_handle;
4040                     channel->remote_sig_id = sig_id;
4041                     channel->remote_cid = source_cid;
4042                     channel->remote_mtu = remote_mtu;
4043                     channel->remote_mps = remote_mps;
4044                     channel->credits_outgoing = credits_outgoing;
4045                     channel->cid_index = i;
4046                     channel->num_cids = num_channels;
4047 
4048                     // if more than one error, we can report any of them
4049                     channel->reason = result;
4050 
4051                     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
4052 
4053                     a_channel = channel;
4054                 }
4055 
4056                 // if no channels have been created, all have been refused, and we can respond right away
4057                 if (a_channel == NULL) {
4058                     l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
4059                                                       num_channels_and_signaling_cid, result);
4060                     return 1;
4061                 }
4062 
4063                 // if security is pending, send intermediate response, otherwise, ask user
4064                 if (send_pending){
4065                     l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
4066                                                       num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_PENDING_AUTHENTICATION);
4067                 } else {
4068                     // if security is ok but authorization is required, send intermediate response and ask user
4069                     if (service->requires_authorization){
4070                         l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
4071                                                           num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_PENDING_AUTHORIZATION);
4072                     }
4073                     l2cap_ecbm_handle_security_level_incoming(a_channel);
4074                 }
4075 
4076             } else {
4077                 l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_CONNECTION_REQUEST, sig_id,
4078                                                   num_channels_and_signaling_cid, L2CAP_ECBM_CONNECTION_RESULT_ALL_REFUSED_SPSM_NOT_SUPPORTED);
4079             }
4080             return 1;
4081 
4082         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
4083             // check size
4084             if (len < 10u) return 0u;
4085 
4086             // get hci connection, ignore if not found
4087             connection = hci_connection_for_handle(handle);
4088             if (connection == NULL) return 0;
4089 
4090             // get channel config: mtu, mps, initial credits, result
4091             new_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4092             new_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
4093             initial_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
4094             result = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
4095             status = l2cap_ecbm_status_for_result(result);
4096 
4097             // get num channels to modify
4098             num_channels = (len - 8) / sizeof(uint16_t);
4099             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4100             while (btstack_linked_list_iterator_has_next(&it)) {
4101                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4102                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4103                 if (channel->con_handle != handle) continue;
4104                 if (channel->local_sig_id != sig_id) continue;
4105                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE) continue;
4106                 if (channel->cid_index < num_channels) {
4107                     uint16_t remote_cid = little_endian_read_16(command, 12 + channel->cid_index * sizeof(uint16_t));
4108                     if (remote_cid != 0) {
4109                         channel->state = L2CAP_STATE_OPEN;
4110                         channel->remote_cid = remote_cid;
4111                         channel->remote_mtu = new_mtu;
4112                         channel->remote_mps = new_mps;
4113                         channel->credits_outgoing = initial_credits;
4114                         l2cap_ecbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
4115                         continue;
4116                     }
4117                 }
4118                 // open failed
4119                 l2cap_ecbm_emit_channel_opened(channel, status);
4120                 // drop failed channel
4121                 btstack_linked_list_iterator_remove(&it);
4122                 btstack_memory_l2cap_channel_free(channel);
4123             }
4124             return 1;
4125 
4126         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
4127             // check minimal size
4128             if (len < 6) return 0u;
4129 
4130             // get hci connection, bail if not found (must not happen)
4131             connection = hci_connection_for_handle(handle);
4132             btstack_assert(connection != NULL);
4133 
4134             // get num channels to modify
4135             num_channels = (len - 4) / sizeof(uint16_t);
4136 
4137             // get new mtu and mps
4138             new_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4139             new_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
4140 
4141             // validate request
4142             result = 0;
4143             for (i = 0; i < num_channels; i++) {
4144                 // check cid
4145                 uint16_t remote_cid = little_endian_read_16(command, 8 + (i * sizeof(uint16_t)));
4146                 l2cap_channel_t *channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
4147                 if (channel == NULL) {
4148                     result = L2CAP_ECBM_RECONFIGURE_FAILED_DESTINATION_CID_INVALID;
4149                     break;
4150                 }
4151                 // check MTU is not reduced
4152                 if (channel->remote_mtu > new_mtu) {
4153                     result = L2CAP_ECBM_RECONFIGURE_FAILED_MTU_REDUCTION_NOT_ALLOWED;
4154                     break;
4155                 }
4156                 // check MPS reduction
4157                 if ((num_channels > 1) && (channel->remote_mps > new_mps)) {
4158                     result = L2CAP_ECBM_RECONFIGURE_FAILED_MPS_REDUCTION_MULTIPLE_CHANNELS;
4159                     break;
4160                 }
4161                 // check MPS valid
4162                 if (new_mps < l2cap_enhanced_mps_min) {
4163                     result = L2CAP_ECBM_RECONFIGURE_FAILED_UNACCEPTABLE_PARAMETERS;
4164                     break;
4165                 }
4166             }
4167 
4168             // send reject
4169             if (result != 0) {
4170                 l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST, sig_id, signaling_cid,
4171                                                   result);
4172                 return 1;
4173             }
4174 
4175             // update channels
4176             for (i = 0; i < num_channels; i++) {
4177                 uint16_t remote_cid = little_endian_read_16(command, 8 + (i * sizeof(uint16_t)));
4178                 l2cap_channel_t *channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
4179                 channel->remote_mps = new_mps;
4180                 channel->remote_mtu = new_mtu;
4181                 // emit event
4182                 uint8_t event[8];
4183                 event[0] = L2CAP_EVENT_ECBM_RECONFIGURED;
4184                 event[1] = sizeof(event) - 2;
4185                 little_endian_store_16(event, 2, channel->local_cid);
4186                 little_endian_store_16(event, 4, new_mtu);
4187                 little_endian_store_16(event, 6, new_mps);
4188                 l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
4189             }
4190 
4191             // send accept
4192             l2cap_register_signaling_response(handle, L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST, sig_id, signaling_cid, 0);
4193             return 1;
4194 
4195         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
4196             // check size
4197             if (len < 2u) return 0u;
4198 
4199             result = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4200             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4201             while (btstack_linked_list_iterator_has_next(&it)) {
4202                 l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4203                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4204                 if (channel->con_handle != handle) continue;
4205                 if (channel->local_sig_id != sig_id) continue;
4206                 if (channel->state != L2CAP_STATE_WAIT_ENHANCED_RENEGOTIATION_RESPONSE) continue;
4207                 // complete request
4208                 if (result == 0) {
4209                     channel->receive_sdu_buffer = channel->renegotiate_sdu_buffer;
4210                     channel->local_mtu = channel->renegotiate_mtu;
4211                 }
4212                 channel->state = L2CAP_STATE_OPEN;
4213                 // emit event
4214                 l2cap_ecbm_emit_reconfigure_complete(channel, result);
4215             }
4216             break;
4217 
4218         default:
4219             btstack_unreachable();
4220             break;
4221     }
4222     return 0;
4223 }
4224 
4225 #endif
4226 
4227 #ifdef ENABLE_BLE
4228 
4229 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
4230     uint8_t event[6];
4231     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
4232     event[1] = 4;
4233     little_endian_store_16(event, 2, con_handle);
4234     little_endian_store_16(event, 4, result);
4235     l2cap_emit_event(event, sizeof(event));
4236 }
4237 
4238 // @return valid
4239 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
4240     hci_connection_t * connection;
4241     uint16_t result;
4242     uint8_t  event[12];
4243 
4244 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4245     l2cap_channel_t * channel;
4246     btstack_linked_list_iterator_t it;
4247 #endif
4248 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4249     uint16_t local_cid;
4250     uint16_t le_psm;
4251     l2cap_service_t * service;
4252     uint16_t source_cid;
4253 #endif
4254 
4255     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
4256     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
4257     log_info("le dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
4258 
4259     switch (code){
4260 
4261         case CONNECTION_PARAMETER_UPDATE_REQUEST:
4262             // check size
4263             if (len < 8u) return 0u;
4264             connection = hci_connection_for_handle(handle);
4265             if (connection != NULL){
4266                 if (connection->role != HCI_ROLE_MASTER){
4267                     // reject command without notifying upper layer when not in master role
4268                     return 0;
4269                 }
4270                 le_connection_parameter_range_t existing_range;
4271                 gap_get_connection_parameter_range(&existing_range);
4272                 uint16_t le_conn_interval_min   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
4273                 uint16_t le_conn_interval_max   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
4274                 uint16_t le_conn_latency        = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
4275                 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
4276 
4277                 int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
4278                 if (update_parameter){
4279                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
4280                     connection->le_conn_interval_min = le_conn_interval_min;
4281                     connection->le_conn_interval_max = le_conn_interval_max;
4282                     connection->le_conn_latency = le_conn_latency;
4283                     connection->le_supervision_timeout = le_supervision_timeout;
4284                 } else {
4285                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
4286                 }
4287                 connection->le_con_param_update_identifier = sig_id;
4288             }
4289 
4290             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
4291             event[1] = 10;
4292             little_endian_store_16(event, 2, handle);
4293             (void)memcpy(&event[4], &command[4], 8);
4294             l2cap_emit_event(event, sizeof(event));
4295             break;
4296 
4297         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
4298             // check size
4299             if (len < 2u) return 0u;
4300             result = little_endian_read_16(command, 4);
4301             l2cap_emit_connection_parameter_update_response(handle, result);
4302             break;
4303 
4304 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
4305         case L2CAP_CREDIT_BASED_CONNECTION_REQUEST:
4306         case L2CAP_CREDIT_BASED_CONNECTION_RESPONSE:
4307         case L2CAP_CREDIT_BASED_RECONFIGURE_REQUEST:
4308         case L2CAP_CREDIT_BASED_RECONFIGURE_RESPONSE:
4309             return l2cap_ecbm_signaling_handler_dispatch(handle, L2CAP_CID_SIGNALING_LE, command, sig_id);
4310 #endif
4311 
4312 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4313         case COMMAND_REJECT:
4314             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4315             while (btstack_linked_list_iterator_has_next(&it)){
4316                 channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4317                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
4318                 if (channel->con_handle   != handle) continue;
4319                 if (channel->local_sig_id != sig_id) continue;
4320 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4321                 // if received while waiting for le connection response, assume legacy device
4322                 if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
4323                     channel->state = L2CAP_STATE_CLOSED;
4324                     // no official value for this, use: Connection refused – LE_PSM not supported
4325                     l2cap_cbm_emit_channel_opened(channel, L2CAP_CBM_CONNECTION_RESULT_SPSM_NOT_SUPPORTED);
4326 
4327                     // discard channel
4328                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4329                     l2cap_free_channel_entry(channel);
4330                     continue;
4331                 }
4332 #endif
4333 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
4334                 // if received while waiting for le connection response, assume legacy device
4335                 if (channel->state == L2CAP_STATE_WAIT_ENHANCED_CONNECTION_RESPONSE){
4336                     channel->state = L2CAP_STATE_CLOSED;
4337                     // treat as SPSM not supported
4338                     l2cap_ecbm_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_PSM);
4339 
4340                     // discard channel
4341                     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4342                     l2cap_free_channel_entry(channel);
4343                     continue;
4344                 }
4345 #endif
4346             }
4347             break;
4348 #endif
4349 
4350 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4351         case LE_CREDIT_BASED_CONNECTION_REQUEST:
4352             // check size
4353             if (len < 10u) return 0u;
4354 
4355             // get hci connection, bail if not found (must not happen)
4356             connection = hci_connection_for_handle(handle);
4357             if (!connection) return 0;
4358 
4359             // check if service registered
4360             le_psm  = little_endian_read_16(command, 4);
4361             service = l2cap_cbm_get_service(le_psm);
4362             source_cid = little_endian_read_16(command, 6);
4363 
4364             if (service){
4365                 if (source_cid < 0x40u){
4366                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INVALID_SOURCE_CID);
4367                     return 1;
4368                 }
4369 
4370                 // go through list of channels for this ACL connection and check if we get a match
4371                 btstack_linked_list_iterator_init(&it, &l2cap_channels);
4372                 while (btstack_linked_list_iterator_has_next(&it)){
4373                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4374                     if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
4375                     if (a_channel->con_handle != handle) continue;
4376                     if (a_channel->remote_cid != source_cid) continue;
4377                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_SOURCE_CID_ALREADY_ALLOCATED);
4378                     return 1;
4379                 }
4380 
4381                 // security: check encryption
4382                 if (service->required_security_level >= LEVEL_2){
4383                     if (gap_encryption_key_size(handle) == 0){
4384                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_ENCRYPTION);
4385                         return 1;
4386                     }
4387                     // anything less than 16 byte key size is insufficient
4388                     if (gap_encryption_key_size(handle) < 16){
4389                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_ENCYRPTION_KEY_SIZE_TOO_SHORT);
4390                         return 1;
4391                     }
4392                 }
4393 
4394                 // security: check authentication
4395                 if (service->required_security_level >= LEVEL_3){
4396                     if (!gap_authenticated(handle)){
4397                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHENTICATION);
4398                         return 1;
4399                     }
4400                 }
4401 
4402                 // security: check authorization
4403                 if (service->required_security_level >= LEVEL_4){
4404                     if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
4405                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_INSUFFICIENT_AUTHORIZATION);
4406                         return 1;
4407                     }
4408                 }
4409 
4410                 // allocate channel
4411                 channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_CBM, connection->address,
4412                                                      BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
4413                 if (!channel){
4414                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE);
4415                     return 1;
4416                 }
4417 
4418                 channel->con_handle = handle;
4419                 channel->remote_cid = source_cid;
4420                 channel->remote_sig_id = sig_id;
4421                 channel->remote_mtu = little_endian_read_16(command, 8);
4422                 channel->remote_mps = little_endian_read_16(command, 10);
4423                 channel->credits_outgoing = little_endian_read_16(command, 12);
4424 
4425                 // set initial state
4426                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
4427                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
4428 
4429                 // add to connections list
4430                 btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
4431 
4432                 // post connection request event
4433                 l2cap_cbm_emit_incoming_connection(channel);
4434 
4435             } else {
4436                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, L2CAP_CBM_CONNECTION_RESULT_SPSM_NOT_SUPPORTED);
4437             }
4438             break;
4439 
4440         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
4441             // check size
4442             if (len < 10u) return 0u;
4443 
4444             // Find channel for this sig_id and connection handle
4445             channel = NULL;
4446             btstack_linked_list_iterator_init(&it, &l2cap_channels);
4447             while (btstack_linked_list_iterator_has_next(&it)){
4448                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
4449                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
4450                 if (a_channel->con_handle   != handle) continue;
4451                 if (a_channel->local_sig_id != sig_id) continue;
4452                 channel = a_channel;
4453                 break;
4454             }
4455             if (!channel) break;
4456 
4457             // cid + 0
4458             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
4459             if (result){
4460                 channel->state = L2CAP_STATE_CLOSED;
4461                 uint8_t status = l2cap_cbm_status_for_result(result);
4462                 l2cap_cbm_emit_channel_opened(channel, status);
4463 
4464                 // discard channel
4465                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4466                 l2cap_free_channel_entry(channel);
4467                 break;
4468             }
4469 
4470             // success
4471             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4472             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
4473             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
4474             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
4475             channel->state = L2CAP_STATE_OPEN;
4476             l2cap_cbm_emit_channel_opened(channel, ERROR_CODE_SUCCESS);
4477             break;
4478 #endif
4479 
4480 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4481         case L2CAP_FLOW_CONTROL_CREDIT_INDICATION:
4482             return l2cap_credit_based_handle_credit_indication(handle, command, len) ? 1 : 0;
4483 
4484         case DISCONNECTION_REQUEST:
4485 
4486             // check size
4487             if (len < 4u) return 0u;
4488 
4489             // find channel
4490             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4491             channel = l2cap_get_channel_for_local_cid_and_handle(local_cid, handle);
4492             if (!channel) {
4493                 log_error("credit: no channel for cid 0x%02x", local_cid);
4494                 break;
4495             }
4496             channel->remote_sig_id = sig_id;
4497             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
4498             break;
4499 
4500         case DISCONNECTION_RESPONSE:
4501             // check size
4502             if (len < 4u) return 0u;
4503 
4504             // find channel
4505             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
4506             channel = l2cap_get_channel_for_local_cid_and_handle(local_cid, handle);
4507             if (!channel) break;
4508             if (channel->local_sig_id == sig_id) {
4509                 if (channel->state == L2CAP_STATE_WAIT_DISCONNECT){
4510                     l2cap_finalize_channel_close(channel);
4511                 }
4512             }
4513             break;
4514 #endif
4515 
4516         default:
4517             // command unknown -> reject command
4518             return 0;
4519     }
4520     return 1;
4521 }
4522 #endif
4523 
4524 #ifdef ENABLE_CLASSIC
4525 static void l2cap_acl_classic_handler_for_channel(l2cap_channel_t * l2cap_channel, uint8_t * packet, uint16_t size){
4526 
4527     // forward data only in OPEN state
4528     if (l2cap_channel->state != L2CAP_STATE_OPEN) return;
4529 
4530 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4531     if (l2cap_channel->channel_type == L2CAP_CHANNEL_TYPE_CHANNEL_ECBM){
4532         l2cap_credit_based_handle_pdu(l2cap_channel, packet, size);
4533         return;
4534     }
4535 #endif
4536 
4537 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
4538     if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
4539 
4540         int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
4541 
4542         // assert control + FCS fields are inside
4543         if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) return;
4544 
4545         if (l2cap_channel->fcs_option){
4546             // verify FCS (required if one side requested it)
4547             uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
4548             uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
4549 
4550 #ifdef L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL
4551             // simulate fcs error
4552             static int counter = 0;
4553             if (++counter == L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL) {
4554                 log_info("Simulate fcs error");
4555                 fcs_calculated++;
4556                 counter = 0;
4557             }
4558 #endif
4559 
4560             if (fcs_calculated == fcs_packet){
4561                 log_info("Packet FCS 0x%04x verified", fcs_packet);
4562             } else {
4563                 log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
4564                 // ERTM State Machine in Bluetooth Spec does not handle 'I-Frame with invalid FCS'
4565                 return;
4566             }
4567         }
4568 
4569         // switch on packet type
4570         uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
4571         uint8_t  req_seq = (control >> 8) & 0x3f;
4572         int final = (control >> 7) & 0x01;
4573         if (control & 1){
4574             // S-Frame
4575             int poll  = (control >> 4) & 0x01;
4576             l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
4577             log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
4578             l2cap_ertm_tx_packet_state_t * tx_state;
4579             switch (s){
4580                 case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
4581                     log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
4582                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4583                     if (poll && final){
4584                         // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
4585                         log_error("P=F=1 in S-Frame");
4586                         break;
4587                     }
4588                     if (poll){
4589                         // check if we did request selective retransmission before <==> we have stored SDU segments
4590                         int i;
4591                         int num_stored_out_of_order_packets = 0;
4592                         for (i=0;i<l2cap_channel->num_rx_buffers;i++){
4593                             int index = l2cap_channel->rx_store_index + i;
4594                             if (index >= l2cap_channel->num_rx_buffers){
4595                                 index -= l2cap_channel->num_rx_buffers;
4596                             }
4597                             l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
4598                             if (!rx_state->valid) continue;
4599                             num_stored_out_of_order_packets++;
4600                         }
4601                         if (num_stored_out_of_order_packets){
4602                             l2cap_channel->send_supervisor_frame_selective_reject = 1;
4603                         } else {
4604                             l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
4605                         }
4606                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
4607                     }
4608                     if (final){
4609                         // Stop-MonitorTimer
4610                         l2cap_ertm_stop_monitor_timer(l2cap_channel);
4611                         // If UnackedFrames > 0 then Start-RetransTimer
4612                         if (l2cap_channel->unacked_frames){
4613                             l2cap_ertm_start_retransmission_timer(l2cap_channel);
4614                         }
4615                         // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
4616                         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4617                     }
4618                     break;
4619                 case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
4620                     log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
4621                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4622                     // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
4623                     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4624                     break;
4625                 case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
4626                     log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
4627                     break;
4628                 case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
4629                     log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
4630                     if (poll){
4631                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4632                     }
4633                     // find requested i-frame
4634                     tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
4635                     if (tx_state){
4636                         log_info("Retransmission for tx_seq %u requested", req_seq);
4637                         l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
4638                         tx_state->retransmission_requested = 1;
4639                         l2cap_channel->srej_active = 1;
4640                     }
4641                     break;
4642                 default:
4643                     break;
4644             }
4645         } else {
4646             // I-Frame
4647             // get control
4648             l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
4649             uint8_t tx_seq = (control >> 1) & 0x3f;
4650             log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
4651             log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
4652             log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
4653             l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
4654             if (final){
4655                 // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
4656                 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
4657             }
4658 
4659             // get SDU
4660             const uint8_t * payload_data = &packet[COMPLETE_L2CAP_HEADER+2];
4661             uint16_t        payload_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
4662 
4663             // assert SDU size is smaller or equal to our buffers
4664             uint16_t max_payload_size = 0;
4665             switch (sar){
4666                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
4667                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
4668                     // SDU Length + MPS
4669                     max_payload_size = l2cap_channel->local_mps + 2;
4670                     break;
4671                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
4672                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
4673                     max_payload_size = l2cap_channel->local_mps;
4674                     break;
4675                 default:
4676                     btstack_assert(false);
4677                     break;
4678             }
4679             if (payload_len > max_payload_size){
4680                 log_info("payload len %u > max payload %u -> drop packet", payload_len, max_payload_size);
4681                 return;
4682             }
4683 
4684             // check ordering
4685             if (l2cap_channel->expected_tx_seq == tx_seq){
4686                 log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
4687                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
4688                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
4689 
4690                 // process SDU
4691                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, payload_data, payload_len);
4692 
4693                 // process stored segments
4694                 while (true){
4695                     int index = l2cap_channel->rx_store_index;
4696                     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
4697                     if (!rx_state->valid) break;
4698 
4699                     log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
4700                     l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
4701                     l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
4702 
4703                     rx_state->valid = 0;
4704                     l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
4705 
4706                     // update rx store index
4707                     index++;
4708                     if (index >= l2cap_channel->num_rx_buffers){
4709                         index = 0;
4710                     }
4711                     l2cap_channel->rx_store_index = index;
4712                 }
4713 
4714                 //
4715                 l2cap_channel->send_supervisor_frame_receiver_ready = 1;
4716 
4717             } else {
4718                 int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
4719                 if (delta < 2){
4720                     // store segment
4721                     l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, payload_data, payload_len);
4722 
4723                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
4724                     l2cap_channel->send_supervisor_frame_selective_reject = 1;
4725                 } else {
4726                     log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
4727                     l2cap_channel->send_supervisor_frame_reject = 1;
4728                 }
4729             }
4730         }
4731         return;
4732     }
4733 #endif
4734 
4735     // check size
4736     uint16_t payload_size = size - COMPLETE_L2CAP_HEADER;
4737     if (l2cap_channel->local_mtu < payload_size) return;
4738 
4739     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], payload_size);
4740 }
4741 #endif
4742 
4743 static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
4744 #ifdef ENABLE_CLASSIC
4745     l2cap_channel_t * l2cap_channel;
4746     l2cap_fixed_channel_t * l2cap_fixed_channel;
4747 
4748     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
4749     uint8_t  broadcast_flag = READ_ACL_FLAGS(packet) >> 2;
4750     switch (channel_id) {
4751 
4752         case L2CAP_CID_SIGNALING: {
4753             if (broadcast_flag != 0) break;
4754             uint32_t command_offset = 8;
4755             while ((command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET) < size) {
4756                 // assert signaling command is fully inside packet
4757                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
4758                 uint32_t next_command_offset = command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
4759                 if (next_command_offset > size){
4760                     log_error("l2cap signaling command len invalid -> drop");
4761                     break;
4762                 }
4763                 // handle signaling command
4764                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
4765                 // go to next command
4766                 command_offset = next_command_offset;
4767             }
4768             break;
4769         }
4770 
4771         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
4772             if (broadcast_flag == 0) break;
4773             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL);
4774             if (!l2cap_fixed_channel) break;
4775             if (!l2cap_fixed_channel->packet_handler) break;
4776             (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4777             break;
4778 
4779 #ifdef ENABLE_BLE
4780         case L2CAP_CID_BR_EDR_SECURITY_MANAGER:
4781             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_BR_EDR_SECURITY_MANAGER);
4782             if ((l2cap_fixed_channel == NULL) || (l2cap_fixed_channel->packet_handler == NULL)){
4783                 // Pairing Failed
4784                 l2cap_register_signaling_response(handle, (uint8_t) SM_PAIRING_FAILED, 0, L2CAP_CID_BR_EDR_SECURITY_MANAGER, SM_REASON_PAIRING_NOT_SUPPORTED);
4785             } else {
4786                 (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4787             }
4788             break;
4789 #endif
4790 
4791         default:
4792             if (broadcast_flag != 0) break;
4793             // Find channel for this channel_id and connection handle
4794             l2cap_channel = l2cap_get_channel_for_local_cid_and_handle(channel_id, handle);
4795             if (l2cap_channel != NULL){
4796                 l2cap_acl_classic_handler_for_channel(l2cap_channel, packet, size);
4797             }
4798             break;
4799     }
4800 #else
4801     UNUSED(handle); // ok: no code
4802     UNUSED(packet); // ok: no code
4803     UNUSED(size);   // ok: no code
4804 #endif
4805 }
4806 
4807 static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
4808 #ifdef ENABLE_BLE
4809 
4810     l2cap_fixed_channel_t * l2cap_fixed_channel;
4811 
4812 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4813     l2cap_channel_t * l2cap_channel;
4814 #endif
4815     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
4816     switch (channel_id) {
4817 
4818         case L2CAP_CID_SIGNALING_LE: {
4819             uint8_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
4820             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
4821             if ((COMPLETE_L2CAP_HEADER + 4u + len) > size) break;
4822             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
4823             if (!valid){
4824                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
4825             }
4826             break;
4827         }
4828 
4829         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
4830             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL);
4831             if (!l2cap_fixed_channel) break;
4832             if (!l2cap_fixed_channel->packet_handler) break;
4833             (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4834             break;
4835 
4836         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
4837             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
4838             if ((l2cap_fixed_channel == NULL) || (l2cap_fixed_channel->packet_handler == NULL)){
4839                 // Pairing Failed
4840                 l2cap_register_signaling_response(handle, (uint8_t) SM_PAIRING_FAILED, 0, L2CAP_CID_SECURITY_MANAGER_PROTOCOL, SM_REASON_PAIRING_NOT_SUPPORTED);
4841             } else {
4842                 (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
4843             }
4844             break;
4845 
4846         default:
4847 
4848 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
4849             l2cap_channel = l2cap_get_channel_for_local_cid_and_handle(channel_id, handle);
4850             if (l2cap_channel != NULL) {
4851                 l2cap_credit_based_handle_pdu(l2cap_channel, packet, size);
4852             }
4853 #endif
4854             break;
4855     }
4856 #else
4857     UNUSED(handle); // ok: no code
4858     UNUSED(packet); // ok: no code
4859     UNUSED(size);   // ok: no code
4860 #endif
4861 }
4862 
4863 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
4864     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
4865     UNUSED(channel);        // ok: there is no channel
4866 
4867     // Assert full L2CAP header present
4868     if (size < COMPLETE_L2CAP_HEADER) return;
4869 
4870     // Dispatch to Classic or LE handler (SCO packets are not dispatched to L2CAP)
4871     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
4872     hci_connection_t *conn = hci_connection_for_handle(handle);
4873     if (!conn) return;
4874     if (conn->address_type == BD_ADDR_TYPE_ACL){
4875         l2cap_acl_classic_handler(handle, packet, size);
4876     } else {
4877         l2cap_acl_le_handler(handle, packet, size);
4878     }
4879 
4880     l2cap_run();
4881 }
4882 
4883 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
4884 void l2cap_register_fixed_channel(btstack_packet_handler_t packet_handler, uint16_t channel_id) {
4885     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
4886     if (!channel) return;
4887     channel->packet_handler = packet_handler;
4888 }
4889 
4890 #ifdef L2CAP_USES_CHANNELS
4891 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
4892 void l2cap_finalize_channel_close(l2cap_channel_t * channel){
4893     channel->state = L2CAP_STATE_CLOSED;
4894     l2cap_handle_channel_closed(channel);
4895     // discard channel
4896     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
4897     l2cap_free_channel_entry(channel);
4898 }
4899 #endif
4900 
4901 #ifdef ENABLE_CLASSIC
4902 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
4903     return l2cap_get_service_internal(&l2cap_services, psm);
4904 }
4905 
4906 static void l2cap_update_minimal_security_level(void){
4907     // update minimal service security level
4908     gap_security_level_t minimal_level = LEVEL_1;
4909     btstack_linked_list_iterator_t it;
4910     btstack_linked_list_iterator_init(&it, &l2cap_services);
4911     while (btstack_linked_list_iterator_has_next(&it)){
4912         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
4913         if (service->required_security_level > minimal_level){
4914             minimal_level = service->required_security_level;
4915         };
4916     }
4917     gap_set_minimal_service_security_level(minimal_level);
4918 }
4919 
4920 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
4921 
4922     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
4923 
4924     // check for alread registered psm
4925     l2cap_service_t *service = l2cap_get_service(psm);
4926     if (service) {
4927         log_error("register: PSM %u already registered", psm);
4928         return L2CAP_SERVICE_ALREADY_REGISTERED;
4929     }
4930 
4931     // alloc structure
4932     service = btstack_memory_l2cap_service_get();
4933     if (!service) {
4934         log_error("register: no memory for l2cap_service_t");
4935         return BTSTACK_MEMORY_ALLOC_FAILED;
4936     }
4937 
4938     // fill in
4939     service->psm = psm;
4940     service->mtu = mtu;
4941     service->packet_handler = service_packet_handler;
4942     service->required_security_level = security_level;
4943 
4944     // add to services list
4945     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
4946 
4947     l2cap_update_minimal_security_level();
4948 
4949 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
4950     // enable page scan
4951     gap_connectable_control(1);
4952 #endif
4953 
4954 
4955     return ERROR_CODE_SUCCESS;
4956 }
4957 
4958 uint8_t l2cap_unregister_service(uint16_t psm){
4959 
4960     log_info("unregister psm 0x%x", psm);
4961 
4962     l2cap_service_t *service = l2cap_get_service(psm);
4963     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
4964     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
4965     btstack_memory_l2cap_service_free(service);
4966 
4967     l2cap_update_minimal_security_level();
4968 
4969 #ifndef ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL
4970     // disable page scan when no services registered
4971     if (btstack_linked_list_empty(&l2cap_services)) {
4972         gap_connectable_control(0);
4973     }
4974 #endif
4975 
4976     return ERROR_CODE_SUCCESS;
4977 }
4978 #endif
4979 
4980 
4981 #ifdef L2CAP_USES_CREDIT_BASED_CHANNELS
4982 
4983 static void l2cap_credit_based_send_pdu(l2cap_channel_t *channel) {
4984     btstack_assert(channel != NULL);
4985     btstack_assert(channel->send_sdu_buffer != NULL);
4986     btstack_assert(channel->credits_outgoing > 0);
4987 
4988     // send part of SDU
4989     hci_reserve_packet_buffer();
4990     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
4991     uint8_t *l2cap_payload = acl_buffer + 8;
4992     uint16_t pos = 0;
4993     if (!channel->send_sdu_pos) {
4994         // store SDU len
4995         channel->send_sdu_pos += 2u;
4996         little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
4997         pos += 2u;
4998     }
4999     uint16_t payload_size = btstack_min(channel->send_sdu_len + 2u - channel->send_sdu_pos, channel->remote_mps - pos);
5000     log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size,
5001              channel->credits_outgoing);
5002     (void) memcpy(&l2cap_payload[pos],
5003                   &channel->send_sdu_buffer[channel->send_sdu_pos - 2u],
5004                   payload_size); // -2 for virtual SDU len
5005     pos += payload_size;
5006     channel->send_sdu_pos += payload_size;
5007     l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
5008 
5009     channel->credits_outgoing--;
5010 
5011     // update state (mark SDU as done) before calling hci_send_acl_packet_buffer (trigger l2cap_le_send_pdu again)
5012     bool done = channel->send_sdu_pos >= (channel->send_sdu_len + 2u);
5013     if (done) {
5014         channel->send_sdu_buffer = NULL;
5015     }
5016 
5017     hci_send_acl_packet_buffer(8u + pos);
5018 
5019     if (done) {
5020         // send done event
5021         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_PACKET_SENT);
5022         // inform about can send now
5023         l2cap_credit_based_notify_channel_can_send(channel);
5024     }
5025 }
5026 
5027 static uint8_t l2cap_credit_based_send_data(l2cap_channel_t * channel, const uint8_t * data, uint16_t size){
5028 
5029     if (size > channel->remote_mtu){
5030         log_error("l2cap send, cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
5031         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
5032     }
5033 
5034     if (channel->send_sdu_buffer){
5035         log_info("l2cap send, cid 0x%02x, cannot send", channel->local_cid);
5036         return BTSTACK_ACL_BUFFERS_FULL;
5037     }
5038 
5039     channel->send_sdu_buffer = data;
5040     channel->send_sdu_len    = size;
5041     channel->send_sdu_pos    = 0;
5042 
5043     l2cap_notify_channel_can_send();
5044     return ERROR_CODE_SUCCESS;
5045 }
5046 
5047 static uint8_t l2cap_credit_based_provide_credits(uint16_t local_cid, uint16_t credits){
5048     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5049     if (!channel) {
5050         log_error("le credits no channel for cid 0x%02x", local_cid);
5051         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5052     }
5053 
5054     // check state
5055     if (channel->state != L2CAP_STATE_OPEN){
5056         log_error("le credits but channel 0x%02x not open yet", local_cid);
5057     }
5058 
5059     // ignore if set to automatic credits
5060     if (channel->automatic_credits) return ERROR_CODE_SUCCESS;
5061 
5062     // assert incoming credits + credits <= 0xffff
5063     uint32_t total_credits = channel->credits_incoming;
5064     total_credits += channel->new_credits_incoming;
5065     total_credits += credits;
5066     if (total_credits > 0xffffu){
5067         log_error("le credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
5068                   channel->new_credits_incoming, credits);
5069     }
5070 
5071     // set credits_granted
5072     channel->new_credits_incoming += credits;
5073 
5074     // go
5075     l2cap_run();
5076     return ERROR_CODE_SUCCESS;
5077 }
5078 
5079 static void l2cap_credit_based_send_credits(l2cap_channel_t *channel) {
5080     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
5081     channel->local_sig_id = l2cap_next_sig_id();
5082     uint16_t new_credits = channel->new_credits_incoming;
5083     channel->new_credits_incoming = 0;
5084     channel->credits_incoming += new_credits;
5085     uint16_t signaling_cid = channel->address_type == BD_ADDR_TYPE_ACL ? L2CAP_CID_SIGNALING : L2CAP_CID_SIGNALING_LE;
5086     l2cap_send_general_signaling_packet(channel->con_handle, signaling_cid, L2CAP_FLOW_CONTROL_CREDIT_INDICATION, channel->local_sig_id, channel->local_cid, new_credits);
5087 }
5088 
5089 // @return valid
5090 static bool l2cap_credit_based_handle_credit_indication(hci_con_handle_t handle, const uint8_t * command, uint16_t len){
5091     // check size
5092     if (len < 4u) return false;
5093 
5094     // find channel
5095     uint16_t remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
5096     l2cap_channel_t * channel = l2cap_get_channel_for_remote_handle_and_cid(handle, remote_cid);
5097     if (!channel) {
5098         log_error("credit: no channel for handle 0x%04x/cid 0x%02x", handle, remote_cid);
5099         return true;
5100     }
5101     uint16_t new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
5102     uint16_t credits_before = channel->credits_outgoing;
5103     channel->credits_outgoing += new_credits;
5104     // check for credit overrun
5105     if (credits_before > channel->credits_outgoing) {
5106         log_error("credit: new credits caused overrrun for cid 0x%02x, disconnecting", channel->local_cid);
5107         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
5108         return true;
5109     }
5110     log_info("credit: %u credits for 0x%02x, now %u", new_credits, channel->local_cid, channel->credits_outgoing);
5111     l2cap_call_notify_channel_in_run = true;
5112     return true;
5113 }
5114 
5115 static void l2cap_credit_based_handle_pdu(l2cap_channel_t * l2cap_channel, const uint8_t * packet, uint16_t size){
5116     // ignore empty packets
5117     if (size == COMPLETE_L2CAP_HEADER) return;
5118 
5119     // credit counting
5120     if (l2cap_channel->credits_incoming == 0u){
5121         log_info("(e)CBM: packet received but no incoming credits");
5122         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
5123         return;
5124     }
5125     l2cap_channel->credits_incoming--;
5126 
5127     // automatic credits
5128     if ((l2cap_channel->credits_incoming < L2CAP_CREDIT_BASED_FLOW_CONTROL_MODE_AUTOMATIC_CREDITS_WATERMARK) && l2cap_channel->automatic_credits){
5129         l2cap_channel->new_credits_incoming = L2CAP_CREDIT_BASED_FLOW_CONTROL_MODE_AUTOMATIC_CREDITS_INCREMENT;
5130     }
5131 
5132     // first fragment
5133     uint16_t pos = 0;
5134     if (!l2cap_channel->receive_sdu_len){
5135         if (size < (COMPLETE_L2CAP_HEADER + 2)) return;
5136         uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
5137         if (sdu_len > l2cap_channel->local_mtu) {
5138             log_info("(e)CBM: packet received larger than MTU");
5139             l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
5140             return;
5141         }
5142         l2cap_channel->receive_sdu_len = sdu_len;
5143         l2cap_channel->receive_sdu_pos = 0;
5144         pos  += 2u;
5145         size -= 2u;
5146     }
5147 
5148     uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
5149 
5150     // check fragment_size
5151     if (fragment_size > l2cap_channel->local_mps) {
5152         log_info("(e)CBM: fragment larger than local MPS");
5153         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
5154         return;
5155     }
5156 
5157     // check sdu overrun
5158     if ((l2cap_channel->receive_sdu_pos + fragment_size) > l2cap_channel->receive_sdu_len){
5159         log_info("(e)CBM: fragments larger than SDU");
5160         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
5161         return;
5162     }
5163 
5164     (void)memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos],
5165                  &packet[COMPLETE_L2CAP_HEADER + pos],
5166                  fragment_size);
5167     l2cap_channel->receive_sdu_pos += fragment_size;
5168 
5169     // done?
5170     log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
5171     if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
5172         l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
5173         l2cap_channel->receive_sdu_len = 0;
5174     }
5175 }
5176 
5177 static void l2cap_credit_based_notify_channel_can_send(l2cap_channel_t *channel){
5178     if (!channel->waiting_for_can_send_now) return;
5179     if (channel->send_sdu_buffer) return;
5180     channel->waiting_for_can_send_now = 0;
5181     log_debug("le can send now, local_cid 0x%x", channel->local_cid);
5182     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CAN_SEND_NOW);
5183 }
5184 #endif
5185 
5186 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
5187 // 1BH2222
5188 static void l2cap_cbm_emit_incoming_connection(l2cap_channel_t *channel) {
5189     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",
5190              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
5191     uint8_t event[19];
5192     event[0] = L2CAP_EVENT_CBM_INCOMING_CONNECTION;
5193     event[1] = sizeof(event) - 2u;
5194     event[2] = channel->address_type;
5195     reverse_bd_addr(channel->address, &event[3]);
5196     little_endian_store_16(event,  9, channel->con_handle);
5197     little_endian_store_16(event, 11, channel->psm);
5198     little_endian_store_16(event, 13, channel->local_cid);
5199     little_endian_store_16(event, 15, channel->remote_cid);
5200     little_endian_store_16(event, 17, channel->remote_mtu);
5201     hci_dump_packet( HCI_EVENT_PACKET, 1, event, sizeof(event));
5202     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
5203 }
5204 // 11BH22222
5205 static void l2cap_cbm_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
5206     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",
5207              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
5208              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
5209     uint8_t event[23];
5210     event[0] = L2CAP_EVENT_CBM_CHANNEL_OPENED;
5211     event[1] = sizeof(event) - 2u;
5212     event[2] = status;
5213     event[3] = channel->address_type;
5214     reverse_bd_addr(channel->address, &event[4]);
5215     little_endian_store_16(event, 10, channel->con_handle);
5216     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
5217     little_endian_store_16(event, 13, channel->psm);
5218     little_endian_store_16(event, 15, channel->local_cid);
5219     little_endian_store_16(event, 17, channel->remote_cid);
5220     little_endian_store_16(event, 19, channel->local_mtu);
5221     little_endian_store_16(event, 21, channel->remote_mtu);
5222     hci_dump_packet( HCI_EVENT_PACKET, 1, event, sizeof(event));
5223     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
5224 }
5225 
5226 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
5227 void l2cap_cbm_finialize_channel_close(l2cap_channel_t * channel){
5228     channel->state = L2CAP_STATE_CLOSED;
5229     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
5230     // discard channel
5231     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
5232     l2cap_free_channel_entry(channel);
5233 }
5234 
5235 static inline l2cap_service_t * l2cap_cbm_get_service(uint16_t le_psm){
5236     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
5237 }
5238 
5239 uint8_t l2cap_cbm_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
5240 
5241     log_info("l2cap_cbm_register_service psm 0x%x", psm);
5242 
5243     // check for alread registered psm
5244     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5245     if (service) {
5246         return L2CAP_SERVICE_ALREADY_REGISTERED;
5247     }
5248 
5249     // alloc structure
5250     service = btstack_memory_l2cap_service_get();
5251     if (!service) {
5252         log_error("register: no memory for l2cap_service_t");
5253         return BTSTACK_MEMORY_ALLOC_FAILED;
5254     }
5255 
5256     // fill in
5257     service->psm = psm;
5258     service->mtu = 0;
5259     service->packet_handler = packet_handler;
5260     service->required_security_level = security_level;
5261     service->requires_authorization = false;
5262 
5263     // add to services list
5264     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
5265 
5266     // done
5267     return ERROR_CODE_SUCCESS;
5268 }
5269 
5270 uint8_t l2cap_cbm_unregister_service(uint16_t psm) {
5271     log_info("l2cap_cbm_unregister_service psm 0x%x", psm);
5272     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5273     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
5274 
5275     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
5276     btstack_memory_l2cap_service_free(service);
5277     return ERROR_CODE_SUCCESS;
5278 }
5279 
5280 uint8_t l2cap_cbm_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
5281     // get channel
5282     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5283     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5284 
5285     // validate state
5286     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
5287         return ERROR_CODE_COMMAND_DISALLOWED;
5288     }
5289 
5290     // set state accept connection
5291     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
5292     channel->receive_sdu_buffer = receive_sdu_buffer;
5293     channel->local_mtu = mtu;
5294     channel->new_credits_incoming = initial_credits;
5295     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5296 
5297     // go
5298     l2cap_run();
5299     return ERROR_CODE_SUCCESS;
5300 }
5301 
5302 uint8_t l2cap_cbm_decline_connection(uint16_t local_cid, uint16_t result) {
5303     // get channel
5304     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5305     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5306 
5307     // validate state
5308     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
5309         return ERROR_CODE_COMMAND_DISALLOWED;
5310     }
5311 
5312     // set state decline connection
5313     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
5314     channel->reason = result;
5315     l2cap_run();
5316     return ERROR_CODE_SUCCESS;
5317 }
5318 
5319 static gap_security_level_t l2cap_cbm_security_level_for_connection(hci_con_handle_t con_handle){
5320     uint8_t encryption_key_size = gap_encryption_key_size(con_handle);
5321     if (encryption_key_size == 0) return LEVEL_0;
5322 
5323     bool authenticated = gap_authenticated(con_handle);
5324     if (!authenticated) return LEVEL_2;
5325 
5326     return encryption_key_size == 16 ? LEVEL_4 : LEVEL_3;
5327 }
5328 
5329 // used to handle pairing complete after triggering to increase
5330 static void l2cap_cbm_sm_packet_handler(uint8_t packet_type, uint16_t channel_nr, uint8_t *packet, uint16_t size) {
5331     UNUSED(channel_nr);
5332     UNUSED(size);
5333     UNUSED(packet_type);
5334     btstack_assert(packet_type == HCI_EVENT_PACKET);
5335     if (hci_event_packet_get_type(packet) != SM_EVENT_PAIRING_COMPLETE) return;
5336     hci_con_handle_t con_handle = sm_event_pairing_complete_get_handle(packet);
5337     btstack_linked_list_iterator_t it;
5338     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5339     while (btstack_linked_list_iterator_has_next(&it)) {
5340         l2cap_channel_t *channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5341         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5342         if (channel->con_handle != con_handle) continue;
5343         if (channel->state != L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE) continue;
5344 
5345         // found channel, check security level
5346         if (l2cap_cbm_security_level_for_connection(con_handle) < channel->required_security_level){
5347             // pairing failed or wasn't good enough, inform user
5348             l2cap_cbm_emit_channel_opened(channel, ERROR_CODE_INSUFFICIENT_SECURITY);
5349             // discard channel
5350             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
5351             l2cap_free_channel_entry(channel);
5352         } else {
5353             // send conn request now
5354             channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5355             l2cap_run();
5356         }
5357     }
5358 }
5359 
5360 uint8_t l2cap_cbm_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5361     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
5362     uint16_t * out_local_cid) {
5363 
5364     static btstack_packet_callback_registration_t sm_event_callback_registration;
5365     static bool sm_callback_registered = false;
5366 
5367     log_info("create, handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
5368 
5369     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5370     if (!connection) {
5371         log_error("no hci_connection for handle 0x%04x", con_handle);
5372         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5373     }
5374 
5375     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CHANNEL_CBM, connection->address, connection->address_type, psm, mtu, security_level);
5376     if (!channel) {
5377         return BTSTACK_MEMORY_ALLOC_FAILED;
5378     }
5379     log_info("created %p", channel);
5380 
5381     // store local_cid
5382     if (out_local_cid){
5383        *out_local_cid = channel->local_cid;
5384     }
5385 
5386     // setup channel entry
5387     channel->con_handle = con_handle;
5388     channel->receive_sdu_buffer = receive_sdu_buffer;
5389     channel->new_credits_incoming = initial_credits;
5390     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5391 
5392     // add to connections list
5393     btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
5394 
5395     // check security level
5396     if (l2cap_cbm_security_level_for_connection(con_handle) < channel->required_security_level){
5397         if (!sm_callback_registered){
5398             sm_callback_registered = true;
5399             // lazy registration for SM events
5400             sm_event_callback_registration.callback = &l2cap_cbm_sm_packet_handler;
5401             sm_add_event_handler(&sm_event_callback_registration);
5402         }
5403 
5404         // start pairing
5405         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
5406         sm_request_pairing(con_handle);
5407     } else {
5408         // send conn request right away
5409         channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5410         l2cap_run();
5411     }
5412 
5413     return ERROR_CODE_SUCCESS;
5414 }
5415 
5416 uint8_t l2cap_cbm_provide_credits(uint16_t local_cid, uint16_t credits){
5417     return l2cap_credit_based_provide_credits(local_cid, credits);
5418 }
5419 #endif
5420 
5421 #ifdef ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE
5422 
5423 uint8_t l2cap_ecbm_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, uint16_t min_remote_mtu,
5424                                     gap_security_level_t security_level, bool authorization_required) {
5425 
5426     // check for already registered psm
5427     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5428     if (service) {
5429         return L2CAP_SERVICE_ALREADY_REGISTERED;
5430     }
5431 
5432     // alloc structure
5433     service = btstack_memory_l2cap_service_get();
5434     if (!service) {
5435         log_error("register: no memory for l2cap_service_t");
5436         return BTSTACK_MEMORY_ALLOC_FAILED;
5437     }
5438 
5439     // fill in
5440     service->psm = psm;
5441     service->mtu = min_remote_mtu;
5442     service->packet_handler = packet_handler;
5443     service->required_security_level = security_level;
5444     service->requires_authorization = authorization_required;
5445 
5446     // add to services list
5447     btstack_linked_list_add(&l2cap_enhanced_services, (btstack_linked_item_t *) service);
5448 
5449     // done
5450     return ERROR_CODE_SUCCESS;
5451 }
5452 
5453 uint8_t l2cap_ecbm_unregister_service(uint16_t psm) {
5454     l2cap_service_t *service = l2cap_cbm_get_service(psm);
5455     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
5456 
5457     btstack_linked_list_remove(&l2cap_enhanced_services, (btstack_linked_item_t *) service);
5458     btstack_memory_l2cap_service_free(service);
5459     return ERROR_CODE_SUCCESS;
5460 }
5461 
5462 void l2cap_ecbm_mps_set_min(uint16_t mps_min){
5463     l2cap_enhanced_mps_min = mps_min;
5464 }
5465 
5466 void l2cap_ecbm_mps_set_max(uint16_t mps_max){
5467     l2cap_enhanced_mps_max = mps_max;
5468 }
5469 
5470 uint8_t l2cap_ecbm_create_channels(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5471                                        gap_security_level_t security_level,
5472                                        uint16_t psm, uint8_t num_channels, uint16_t initial_credits, uint16_t mtu,
5473                                        uint8_t ** receive_sdu_buffers, uint16_t * out_local_cid){
5474 
5475     log_info("create enhanced, handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
5476 
5477     hci_connection_t * connection = hci_connection_for_handle(con_handle);
5478     if (!connection) {
5479         log_error("no hci_connection for handle 0x%04x", con_handle);
5480         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
5481     }
5482 
5483     // setup all channels
5484     btstack_linked_list_t channels = NULL;
5485     uint8_t status = l2cap_ecbm_setup_channels(&channels, packet_handler, num_channels, connection, psm, mtu,
5486                                                security_level);
5487     uint16_t local_mps = btstack_min(l2cap_enhanced_mps_max, btstack_min(l2cap_max_le_mtu(), mtu));
5488 
5489     // add to connections list and set state + local_sig_id
5490     l2cap_channel_t * channel;
5491     uint8_t i = 0;
5492     uint8_t local_sig_id = l2cap_next_sig_id();
5493     while (true) {
5494         channel = (l2cap_channel_t *) btstack_linked_list_pop(&channels);
5495         if (channel == NULL) break;
5496         channel->state              = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_REQUEST;
5497         channel->local_sig_id       = local_sig_id;
5498         channel->local_mps = local_mps;
5499         channel->cid_index = i;
5500         channel->num_cids = num_channels;
5501         channel->credits_incoming   = initial_credits;
5502         channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5503         channel->receive_sdu_buffer = receive_sdu_buffers[i];
5504         // store local_cid
5505         if (out_local_cid){
5506             out_local_cid[i] = channel->local_cid;
5507         }
5508         btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
5509         i++;
5510     }
5511 
5512 #if 0
5513     // check security level
5514     if (l2cap_le_security_level_for_connection(con_handle) < channel->required_security_level){
5515         if (!sm_callback_registered){
5516             sm_callback_registered = true;
5517             // lazy registration for SM events
5518             sm_event_callback_registration.callback = &l2cap_sm_packet_handler;
5519             sm_add_event_handler(&sm_event_callback_registration);
5520         }
5521 
5522         // start pairing
5523         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
5524         sm_request_pairing(con_handle);
5525     } else {
5526         // send conn request right away
5527         channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
5528         l2cap_run();
5529     }
5530 #endif
5531 
5532     l2cap_run();
5533 
5534     return status;
5535 }
5536 
5537 uint8_t l2cap_ecbm_accept_channels(uint16_t local_cid, uint8_t num_channels, uint16_t initial_credits,
5538                                             uint16_t receive_buffer_size, uint8_t ** receive_buffers, uint16_t * out_local_cids){
5539 
5540     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5541     if (!channel) {
5542 
5543         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5544     }
5545 
5546     uint16_t local_mps = btstack_min(l2cap_enhanced_mps_max, btstack_min(l2cap_max_le_mtu(), receive_buffer_size));
5547 
5548     //
5549     hci_con_handle_t  con_handle    = channel->con_handle;
5550     uint8_t           local_sig_id  = channel->local_sig_id;
5551     uint8_t           channel_index = 0;
5552     btstack_linked_list_iterator_t it;
5553     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5554     while (btstack_linked_list_iterator_has_next(&it)) {
5555         channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5556         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5557         if (channel->con_handle != con_handle) continue;
5558         if (channel->local_sig_id != local_sig_id) continue;
5559         if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT) continue;
5560 
5561         if (channel_index < num_channels){
5562             // assign buffer and cid
5563             out_local_cids[channel_index] = channel->local_cid;
5564             channel->receive_sdu_buffer = receive_buffers[channel_index];
5565             channel->local_mtu = receive_buffer_size;
5566             channel->local_mps = local_mps;
5567             channel->credits_incoming   = initial_credits;
5568             channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
5569             channel_index++;
5570         } else {
5571             // clear local cid for response packet
5572             channel->local_cid = 0;
5573             channel->reason = L2CAP_ECBM_CONNECTION_RESULT_SOME_REFUSED_INSUFFICIENT_RESOURCES_AVAILABLE;
5574         }
5575         // update state
5576         channel->state = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE;
5577     }
5578     l2cap_run_trigger();
5579     return ERROR_CODE_SUCCESS;
5580 }
5581 
5582 uint8_t l2cap_ecbm_decline_channels(uint16_t local_cid, uint16_t result){
5583     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
5584     if (!channel) {
5585         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5586     }
5587     //
5588     hci_con_handle_t  con_handle    = channel->con_handle;
5589     uint8_t           local_sig_id  = channel->local_sig_id;
5590     btstack_linked_list_iterator_t it;
5591     btstack_linked_list_iterator_init(&it, &l2cap_channels);
5592     while (btstack_linked_list_iterator_has_next(&it)) {
5593         channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
5594         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
5595         if (channel->con_handle != con_handle) continue;
5596         if (channel->local_sig_id != local_sig_id) continue;
5597         if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT) continue;
5598 
5599         // prepare response
5600         channel->local_cid = 0;
5601         channel->reason = result;
5602         channel->state = L2CAP_STATE_WILL_SEND_ENHANCED_CONNECTION_RESPONSE;
5603     }
5604     l2cap_run_trigger();
5605     return ERROR_CODE_SUCCESS;
5606 }
5607 
5608 uint8_t l2cap_ecbm_reconfigure_channels(uint8_t num_cids, uint16_t * local_cids, int16_t receive_buffer_size, uint8_t ** receive_buffers){
5609     btstack_assert(receive_buffers != NULL);
5610     btstack_assert(local_cids != NULL);
5611 
5612     if (num_cids > L2CAP_ECBM_MAX_CID_ARRAY_SIZE){
5613         return ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS;
5614     }
5615 
5616     // check if all cids exist and have the same con handle
5617     uint8_t i;
5618     hci_con_handle_t con_handle = HCI_CON_HANDLE_INVALID;
5619     for (i = 0 ; i < num_cids ; i++){
5620         l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cids[i]);
5621         if (!channel) {
5622             return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
5623         }
5624         if (channel->state != L2CAP_STATE_OPEN){
5625             return ERROR_CODE_COMMAND_DISALLOWED;
5626         }
5627         if (con_handle == HCI_CON_HANDLE_INVALID){
5628             con_handle = channel->con_handle;
5629         } else if (con_handle != channel->con_handle){
5630             return ERROR_CODE_UNACCEPTABLE_CONNECTION_PARAMETERS;
5631         }
5632     }
5633     // set renegotiation data and state
5634     uint8_t sig_id = l2cap_next_sig_id();
5635     for (i = 0 ; i < num_cids ; i++){
5636         l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cids[i]);
5637         channel->cid_index = i;
5638         channel->num_cids = num_cids;
5639         channel->local_sig_id = sig_id;
5640         channel->renegotiate_mtu = receive_buffer_size;
5641         channel->renegotiate_sdu_buffer = receive_buffers[i];
5642         channel->state = L2CAP_STATE_WILL_SEND_EHNANCED_RENEGOTIATION_REQUEST;
5643     }
5644 
5645 
5646     l2cap_run();
5647     return ERROR_CODE_SUCCESS;
5648 }
5649 
5650 uint8_t l2cap_ecbm_provide_credits(uint16_t local_cid, uint16_t credits){
5651     return l2cap_credit_based_provide_credits(local_cid, credits);
5652 }
5653 #endif
5654 
5655 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
5656 // @deprecated - please use l2cap_ertm_create_channel
5657 uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
5658                                   l2cap_ertm_config_t * ertm_contig, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
5659     log_error("deprecated - please use l2cap_ertm_create_channel");
5660     return l2cap_ertm_create_channel(packet_handler, address, psm, ertm_contig, buffer, size, out_local_cid);
5661 };
5662 
5663 // @deprecated - please use l2cap_ertm_accept_connection
5664 uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, l2cap_ertm_config_t * ertm_contig, uint8_t * buffer, uint32_t size){
5665     log_error("deprecated - please use l2cap_ertm_accept_connection");
5666     return l2cap_ertm_accept_connection(local_cid, ertm_contig, buffer, size);
5667 }
5668 #endif
5669 
5670 #ifdef ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE
5671 // @deprecated - please use l2cap_cbm_register_service
5672 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
5673     log_error("deprecated - please use l2cap_cbm_register_service");
5674     return l2cap_cbm_register_service(packet_handler, psm, security_level);
5675 }
5676 
5677 // @deprecated - please use l2cap_cbm_unregister_service
5678 uint8_t l2cap_le_unregister_service(uint16_t psm){
5679     log_error("deprecated - please use l2cap_cbm_unregister_service");
5680     return l2cap_cbm_unregister_service(psm);
5681 }
5682 
5683 // @deprecated - please use l2cap_cbm_accept_connection
5684 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
5685     log_error("deprecated - please use l2cap_cbm_accept_connection");
5686     return l2cap_cbm_accept_connection(local_cid, receive_sdu_buffer, mtu, initial_credits);
5687 }
5688 
5689 // @deprecated - please use l2cap_cbm_decline_connection
5690 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
5691     log_error("deprecated - please use l2cap_cbm_decline_connection");
5692     return l2cap_cbm_decline_connection(local_cid, L2CAP_CBM_CONNECTION_RESULT_NO_RESOURCES_AVAILABLE);
5693 }
5694 
5695 // @deprecated - please use l2cap_cbm_create_channel
5696 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
5697                                 uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
5698                                 uint16_t * out_local_cid){
5699     log_error("deprecated - please use l2cap_cbm_create_channel");
5700     return l2cap_cbm_create_channel(packet_handler, con_handle, psm, receive_sdu_buffer, mtu, initial_credits, security_level, out_local_cid);
5701 }
5702 
5703 // @deprecated - please use l2cap_cbm_provide_credits
5704 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
5705     log_error("deprecated - please use l2cap_cbm_provide_credits");
5706     return l2cap_cbm_provide_credits(local_cid, credits);
5707 }
5708 
5709 // @deprecated - please use l2cap_can_send_packet_now
5710 bool l2cap_le_can_send_now(uint16_t local_cid){
5711     log_error("deprecated - please use l2cap_can_send_packet_now");
5712     return l2cap_can_send_packet_now(local_cid);
5713 }
5714 
5715 // @deprecated - please use l2cap_request_can_send_now_event
5716 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
5717     log_error("deprecated - please use l2cap_request_can_send_now_event");
5718     return l2cap_request_can_send_now_event(local_cid);
5719 }
5720 
5721 // @deprecated - please use l2cap_cbm_send_data
5722 uint8_t l2cap_le_send_data(uint16_t local_cid, const uint8_t * data, uint16_t size){
5723     log_error("deprecated - please use l2cap_cbm_send_data");
5724     return l2cap_send(local_cid, data, size);
5725 }
5726 
5727 // @deprecated - please use l2cap_disconnect
5728 uint8_t l2cap_le_disconnect(uint16_t local_cid){
5729     log_error("deprecated - please use l2cap_disconnect");
5730     return l2cap_disconnect(local_cid);
5731 }
5732 #endif
5733