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