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