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