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