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