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