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