xref: /btstack/src/l2cap.c (revision 75e67d8a2b896068a232275885ecf2886b27f34f)
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 MATTHIAS
24  * RINGWALD 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  *
43  *  Logical Link Control and Adaption Protocl (L2CAP)
44  *
45  *  Created by Matthias Ringwald on 5/16/09.
46  */
47 
48 #include "l2cap.h"
49 #include "hci.h"
50 #include "hci_dump.h"
51 #include "bluetooth_sdp.h"
52 #include "bluetooth_psm.h"
53 #include "btstack_debug.h"
54 #include "btstack_event.h"
55 #include "btstack_memory.h"
56 
57 #include <stdarg.h>
58 #include <string.h>
59 
60 #include <stdio.h>
61 
62 /*
63  * @brief L2CAP Supervisory function in S-Frames
64  */
65 typedef enum {
66     L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY = 0,
67     L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT,
68     L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY,
69     L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT
70 } l2cap_supervisory_function_t;
71 
72 /**
73  * @brief L2CAP Information Types used in Information Request & Response
74  */
75 typedef enum {
76   L2CAP_INFO_TYPE_CONNECTIONLESS_MTU = 1,
77   L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED,
78   L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED,
79 } l2cap_info_type_t;
80 
81 /**
82  * @brief L2CAP Configuration Option Types used in Configurateion Request & Response
83  */
84 typedef enum {
85   L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT = 1,
86   L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT,
87   L2CAP_CONFIG_OPTION_TYPE_QUALITY_OF_SERVICE,
88   L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL,
89   L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE,
90   L2CAP_CONFIG_OPTION_TYPE_EXTENDED_FLOW_SPECIFICATION,
91   L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE,
92 } l2cap_config_option_type_t;
93 
94 
95 #define L2CAP_SIG_ID_INVALID 0
96 
97 // size of HCI ACL + L2CAP Header for regular data packets (8)
98 #define COMPLETE_L2CAP_HEADER (HCI_ACL_HEADER_SIZE + L2CAP_HEADER_SIZE)
99 
100 // L2CAP Configuration Result Codes
101 #define L2CAP_CONF_RESULT_SUCCESS                  0x0000
102 #define L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS  0x0001
103 #define L2CAP_CONF_RESULT_REJECT                   0x0002
104 #define L2CAP_CONF_RESULT_UNKNOWN_OPTIONS          0x0003
105 #define L2CAP_CONF_RESULT_PENDING                  0x0004
106 #define L2CAP_CONF_RESULT_FLOW_SPEC_REJECTED       0x0005
107 
108 // L2CAP Reject Result Codes
109 #define L2CAP_REJ_CMD_UNKNOWN                      0x0000
110 
111 // Response Timeout eXpired
112 #define L2CAP_RTX_TIMEOUT_MS   10000
113 
114 // Extended Response Timeout eXpired
115 #define L2CAP_ERTX_TIMEOUT_MS 120000
116 
117 // nr of buffered acl packets in outgoing queue to get max performance
118 #define NR_BUFFERED_ACL_PACKETS 3
119 
120 // used to cache l2cap rejects, echo, and informational requests
121 #define NR_PENDING_SIGNALING_RESPONSES 3
122 
123 // nr of credits provided to remote if credits fall below watermark
124 #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK 5
125 #define L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT 5
126 
127 // offsets for L2CAP SIGNALING COMMANDS
128 #define L2CAP_SIGNALING_COMMAND_CODE_OFFSET   0
129 #define L2CAP_SIGNALING_COMMAND_SIGID_OFFSET  1
130 #define L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET 2
131 #define L2CAP_SIGNALING_COMMAND_DATA_OFFSET   4
132 
133 #if defined(ENABLE_LE_DATA_CHANNELS) || defined(ENABLE_CLASSIC)
134 #define L2CAP_USES_CHANNELS
135 #endif
136 
137 // prototypes
138 static void l2cap_run(void);
139 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size);
140 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size );
141 static void l2cap_notify_channel_can_send(void);
142 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel);
143 static uint8_t  l2cap_next_sig_id(void);
144 static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid);
145 #ifdef ENABLE_CLASSIC
146 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel);
147 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel);
148 static void l2cap_finialize_channel_close(l2cap_channel_t *channel);
149 static inline l2cap_service_t * l2cap_get_service(uint16_t psm);
150 static void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status);
151 static void l2cap_emit_channel_closed(l2cap_channel_t *channel);
152 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel);
153 static int  l2cap_channel_ready_for_open(l2cap_channel_t *channel);
154 #endif
155 #ifdef ENABLE_LE_DATA_CHANNELS
156 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status);
157 static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel);
158 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel);
159 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel);
160 static void l2cap_le_finialize_channel_close(l2cap_channel_t *channel);
161 static void l2cap_le_send_pdu(l2cap_channel_t *channel);
162 static inline l2cap_service_t * l2cap_le_get_service(uint16_t psm);
163 #endif
164 #ifdef L2CAP_USES_CHANNELS
165 static uint16_t l2cap_next_local_cid(void);
166 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid);
167 static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code);
168 static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size);
169 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid);
170 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,
171         uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level);
172 static void l2cap_free_channel_entry(l2cap_channel_t * channel);
173 #endif
174 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
175 static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel);
176 static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts);
177 static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts);
178 #endif
179 
180 // l2cap_fixed_channel_t entries
181 #ifdef ENABLE_BLE
182 static l2cap_fixed_channel_t l2cap_fixed_channel_att;
183 static l2cap_fixed_channel_t l2cap_fixed_channel_sm;
184 #endif
185 #ifdef ENABLE_CLASSIC
186 static l2cap_fixed_channel_t l2cap_fixed_channel_connectionless;
187 #endif
188 
189 #ifdef ENABLE_CLASSIC
190 static btstack_linked_list_t l2cap_services;
191 static uint8_t require_security_level2_for_outgoing_sdp;
192 static bd_addr_t l2cap_outgoing_classic_addr;
193 #endif
194 
195 #ifdef ENABLE_LE_DATA_CHANNELS
196 static btstack_linked_list_t l2cap_le_services;
197 #endif
198 
199 // single list of channels for Classic Channels, LE Data Channels, Classic Connectionless, ATT, and SM
200 static btstack_linked_list_t l2cap_channels;
201 #ifdef L2CAP_USES_CHANNELS
202 // next channel id for new connections
203 static uint16_t  local_source_cid  = 0x40;
204 #endif
205 // next signaling sequence number
206 static uint8_t   sig_seq_nr  = 0xff;
207 
208 // used to cache l2cap rejects, echo, and informational requests
209 static l2cap_signaling_response_t signaling_responses[NR_PENDING_SIGNALING_RESPONSES];
210 static int signaling_responses_pending;
211 static btstack_packet_callback_registration_t hci_event_callback_registration;
212 
213 #ifdef ENABLE_BLE
214 // only used for connection parameter update events
215 static btstack_packet_handler_t l2cap_event_packet_handler;
216 static uint16_t l2cap_le_custom_max_mtu;
217 #endif
218 
219 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
220 
221 // enable for testing
222 // #define L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL 16
223 
224 /*
225  * CRC lookup table for generator polynom D^16 + D^15 + D^2 + 1
226  */
227 static const uint16_t crc16_table[256] = {
228     0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
229     0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841,
230     0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41,
231     0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040,
232     0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441,
233     0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840,
234     0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40,
235     0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041,
236     0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
237     0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840,
238     0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
239     0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041,
240     0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440,
241     0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841,
242     0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41,
243     0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040,
244 };
245 
246 static uint16_t crc16_calc(uint8_t * data, uint16_t len){
247     uint16_t crc = 0;   // initial value = 0
248     while (len--){
249         crc = (crc >> 8) ^ crc16_table[ (crc ^ ((uint16_t) *data++)) & 0x00FF ];
250     }
251     return crc;
252 }
253 
254 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){
255     return (((uint16_t) sar) << 14) | (req_seq << 8) | (final << 7) | (tx_seq << 1) | 0;
256 }
257 
258 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){
259     return (req_seq << 8) | (final << 7) | (poll << 4) | (((int) supervisory_function) << 2) | 1;
260 }
261 
262 static int l2cap_next_ertm_seq_nr(int seq_nr){
263     return (seq_nr + 1) & 0x3f;
264 }
265 
266 static int l2cap_ertm_can_store_packet_now(l2cap_channel_t * channel){
267     // get num free tx buffers
268     int num_free_tx_buffers = channel->num_tx_buffers - channel->num_stored_tx_frames;
269     // calculate num tx buffers for remote MTU
270     int num_tx_buffers_for_max_remote_mtu;
271     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
272     if (channel->remote_mtu <= effective_mps){
273         // MTU fits into single packet
274         num_tx_buffers_for_max_remote_mtu = 1;
275     } else {
276         // include SDU Length
277         num_tx_buffers_for_max_remote_mtu = (channel->remote_mtu + 2 + (effective_mps - 1)) / effective_mps;
278     }
279     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);
280     return num_tx_buffers_for_max_remote_mtu <= num_free_tx_buffers;
281 }
282 
283 static void l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel_t * l2cap_channel){
284     log_info("Retransmit unacknowleged frames");
285     l2cap_channel->unacked_frames = 0;;
286     l2cap_channel->tx_send_index  = l2cap_channel->tx_read_index;
287 }
288 
289 static void l2cap_ertm_next_tx_write_index(l2cap_channel_t * channel){
290     channel->tx_write_index++;
291     if (channel->tx_write_index < channel->num_tx_buffers) return;
292     channel->tx_write_index = 0;
293 }
294 
295 static void l2cap_ertm_start_monitor_timer(l2cap_channel_t * channel){
296     log_info("Start Monitor timer");
297     btstack_run_loop_remove_timer(&channel->monitor_timer);
298     btstack_run_loop_set_timer_handler(&channel->monitor_timer, &l2cap_ertm_monitor_timeout_callback);
299     btstack_run_loop_set_timer_context(&channel->monitor_timer, channel);
300     btstack_run_loop_set_timer(&channel->monitor_timer, channel->local_monitor_timeout_ms);
301     btstack_run_loop_add_timer(&channel->monitor_timer);
302 }
303 
304 static void l2cap_ertm_stop_monitor_timer(l2cap_channel_t * channel){
305     log_info("Stop Monitor timer");
306     btstack_run_loop_remove_timer(&channel->monitor_timer);
307 }
308 
309 static void l2cap_ertm_start_retransmission_timer(l2cap_channel_t * channel){
310     log_info("Start Retransmission timer");
311     btstack_run_loop_remove_timer(&channel->retransmission_timer);
312     btstack_run_loop_set_timer_handler(&channel->retransmission_timer, &l2cap_ertm_retransmission_timeout_callback);
313     btstack_run_loop_set_timer_context(&channel->retransmission_timer, channel);
314     btstack_run_loop_set_timer(&channel->retransmission_timer, channel->local_retransmission_timeout_ms);
315     btstack_run_loop_add_timer(&channel->retransmission_timer);
316 }
317 
318 static void l2cap_ertm_stop_retransmission_timer(l2cap_channel_t * l2cap_channel){
319     log_info("Stop Retransmission timer");
320     btstack_run_loop_remove_timer(&l2cap_channel->retransmission_timer);
321 }
322 
323 static void l2cap_ertm_monitor_timeout_callback(btstack_timer_source_t * ts){
324     log_info("Monitor timeout");
325     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
326 
327     // TODO: we assume that it's the oldest packet
328     l2cap_ertm_tx_packet_state_t * tx_state;
329     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
330 
331     // check retry count
332     if (tx_state->retry_count < l2cap_channel->remote_max_transmit){
333         // increment retry count
334         tx_state->retry_count++;
335 
336         // start retransmit
337         l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
338 
339         // start monitor timer
340         l2cap_ertm_start_monitor_timer(l2cap_channel);
341 
342         // send RR/P=1
343         l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
344     } else {
345         log_info("Monitor timer expired & retry count >= max transmit -> disconnect");
346         l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
347     }
348     l2cap_run();
349 }
350 
351 static void l2cap_ertm_retransmission_timeout_callback(btstack_timer_source_t * ts){
352     log_info("Retransmission timeout");
353     l2cap_channel_t * l2cap_channel = (l2cap_channel_t *) btstack_run_loop_get_timer_context(ts);
354 
355     // TODO: we assume that it's the oldest packet
356     l2cap_ertm_tx_packet_state_t * tx_state;
357     tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
358 
359     // set retry count = 1
360     tx_state->retry_count = 1;
361 
362     // start retransmit
363     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
364 
365     // start monitor timer
366     l2cap_ertm_start_monitor_timer(l2cap_channel);
367 
368     // send RR/P=1
369     l2cap_channel->send_supervisor_frame_receiver_ready_poll = 1;
370     l2cap_run();
371 }
372 
373 static int l2cap_ertm_send_information_frame(l2cap_channel_t * channel, int index, int final){
374     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
375     hci_reserve_packet_buffer();
376     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
377     uint16_t control = l2cap_encanced_control_field_for_information_frame(tx_state->tx_seq, final, channel->req_seq, tx_state->sar);
378     log_info("I-Frame: control 0x%04x", control);
379     little_endian_store_16(acl_buffer, 8, control);
380     (void)memcpy(&acl_buffer[8 + 2],
381                  &channel->tx_packets_data[index * channel->local_mps],
382                  tx_state->len);
383     // (re-)start retransmission timer on
384     l2cap_ertm_start_retransmission_timer(channel);
385     // send
386     return l2cap_send_prepared(channel->local_cid, 2 + tx_state->len);
387 }
388 
389 static void l2cap_ertm_store_fragment(l2cap_channel_t * channel, l2cap_segmentation_and_reassembly_t sar, uint16_t sdu_length, uint8_t * data, uint16_t len){
390     // get next index for storing packets
391     int index = channel->tx_write_index;
392 
393     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[index];
394     tx_state->tx_seq = channel->next_tx_seq;
395     tx_state->sar = sar;
396     tx_state->retry_count = 0;
397 
398     uint8_t * tx_packet = &channel->tx_packets_data[index * channel->local_mps];
399     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);
400     int pos = 0;
401     if (sar == L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU){
402         little_endian_store_16(tx_packet, 0, sdu_length);
403         pos += 2;
404     }
405     (void)memcpy(&tx_packet[pos], data, len);
406     tx_state->len = pos + len;
407 
408     // update
409     channel->num_stored_tx_frames++;
410     channel->next_tx_seq = l2cap_next_ertm_seq_nr(channel->next_tx_seq);
411     l2cap_ertm_next_tx_write_index(channel);
412 
413     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);
414 
415 }
416 
417 static int l2cap_ertm_send(l2cap_channel_t * channel, uint8_t * data, uint16_t len){
418     if (len > channel->remote_mtu){
419         log_error("l2cap_ertm_send cid 0x%02x, data length exceeds remote MTU.", channel->local_cid);
420         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
421     }
422 
423     if (!l2cap_ertm_can_store_packet_now(channel)){
424         log_error("l2cap_ertm_send cid 0x%02x, fragment store full", channel->local_cid);
425         return BTSTACK_ACL_BUFFERS_FULL;
426     }
427 
428     // check if it needs to get fragmented
429     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
430     if (len > effective_mps){
431         // fragmentation needed.
432         l2cap_segmentation_and_reassembly_t sar =  L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU;
433         int chunk_len;
434         while (len){
435             switch (sar){
436                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
437                     chunk_len = effective_mps - 2;    // sdu_length
438                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
439                     len -= chunk_len;
440                     sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU;
441                     break;
442                 case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
443                     chunk_len = effective_mps;
444                     if (chunk_len >= len){
445                         sar = L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU;
446                         chunk_len = len;
447                     }
448                     l2cap_ertm_store_fragment(channel, sar, len, data, chunk_len);
449                     len -= chunk_len;
450                     break;
451                 default:
452                     break;
453             }
454         }
455 
456     } else {
457         l2cap_ertm_store_fragment(channel, L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU, 0, data, len);
458     }
459 
460     // try to send
461     l2cap_notify_channel_can_send();
462     return 0;
463 }
464 
465 static uint16_t l2cap_setup_options_ertm_request(l2cap_channel_t * channel, uint8_t * config_options){
466     int pos = 0;
467     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
468     config_options[pos++] = 9;      // length
469     config_options[pos++] = (uint8_t) channel->mode;
470     config_options[pos++] = channel->num_rx_buffers;    // == TxWindows size
471     config_options[pos++] = channel->local_max_transmit;
472     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
473     pos += 2;
474     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
475     pos += 2;
476     little_endian_store_16( config_options, pos, channel->local_mps);
477     pos += 2;
478     //
479     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT;
480     config_options[pos++] = 2;     // length
481     little_endian_store_16(config_options, pos, channel->local_mtu);
482     pos += 2;
483 
484     // Issue: iOS (e.g. 10.2) uses "No FCS" as default while Core 5.0 specifies "FCS" as default
485     // Workaround: try to actively negotiate FCS option
486     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
487     config_options[pos++] = 1;     // length
488     config_options[pos++] = channel->fcs_option;
489     return pos; // 11+4+3=18
490 }
491 
492 static uint16_t l2cap_setup_options_ertm_response(l2cap_channel_t * channel, uint8_t * config_options){
493     int pos = 0;
494     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL;
495     config_options[pos++] = 9;      // length
496     config_options[pos++] = (uint8_t) channel->mode;
497     // less or equal to remote tx window size
498     config_options[pos++] = btstack_min(channel->num_tx_buffers, channel->remote_tx_window_size);
499     // max transmit in response shall be ignored -> use sender values
500     config_options[pos++] = channel->remote_max_transmit;
501     // A value for the Retransmission time-out shall be sent in a positive Configuration Response
502     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
503     little_endian_store_16( config_options, pos, channel->local_retransmission_timeout_ms);
504     pos += 2;
505     // A value for the Monitor time-out shall be sent in a positive Configuration Response
506     // and indicates the value that will be used by the sender of the Configuration Response -> use our value
507     little_endian_store_16( config_options, pos, channel->local_monitor_timeout_ms);
508     pos += 2;
509     // less or equal to remote mps
510     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
511     little_endian_store_16( config_options, pos, effective_mps);
512     pos += 2;
513     //
514     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
515     config_options[pos++] = 2;     // length
516     little_endian_store_16(config_options, pos, channel->remote_mtu);
517     pos += 2;
518 #if 0
519     //
520     config_options[pos++] = L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE;
521     config_options[pos++] = 1;     // length
522     config_options[pos++] = channel->fcs_option;
523 #endif
524     return pos; // 11+4=15
525 }
526 
527 static int l2cap_ertm_send_supervisor_frame(l2cap_channel_t * channel, uint16_t control){
528     hci_reserve_packet_buffer();
529     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
530     log_info("S-Frame: control 0x%04x", control);
531     little_endian_store_16(acl_buffer, 8, control);
532     return l2cap_send_prepared(channel->local_cid, 2);
533 }
534 
535 static uint8_t l2cap_ertm_validate_local_config(l2cap_ertm_config_t * ertm_config){
536 
537     uint8_t result = ERROR_CODE_SUCCESS;
538     if (ertm_config->max_transmit < 1){
539         log_error("max_transmit must be >= 1");
540         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
541     }
542     if (ertm_config->retransmission_timeout_ms < 2000){
543         log_error("retransmission_timeout_ms must be >= 2000 ms");
544         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
545     }
546     if (ertm_config->monitor_timeout_ms < 12000){
547         log_error("monitor_timeout_ms must be >= 12000 ms");
548         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
549     }
550     if (ertm_config->local_mtu < 48){
551         log_error("local_mtu must be >= 48");
552         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
553     }
554     if (ertm_config->num_rx_buffers < 1){
555         log_error("num_rx_buffers must be >= 1");
556         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
557     }
558     if (ertm_config->num_tx_buffers < 1){
559         log_error("num_rx_buffers must be >= 1");
560         result = ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
561     }
562     return result;
563 }
564 
565 static void l2cap_ertm_configure_channel(l2cap_channel_t * channel, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
566 
567     channel->mode  = L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION;
568     channel->ertm_mandatory = ertm_config->ertm_mandatory;
569     channel->local_max_transmit = ertm_config->max_transmit;
570     channel->local_retransmission_timeout_ms = ertm_config->retransmission_timeout_ms;
571     channel->local_monitor_timeout_ms = ertm_config->monitor_timeout_ms;
572     channel->local_mtu = ertm_config->local_mtu;
573     channel->num_rx_buffers = ertm_config->num_rx_buffers;
574     channel->num_tx_buffers = ertm_config->num_tx_buffers;
575 
576     // align buffer to 16-byte boundary to assert l2cap_ertm_rx_packet_state_t is aligned
577     int bytes_till_alignment = 16 - (((uintptr_t) buffer) & 0x0f);
578     buffer += bytes_till_alignment;
579     size   -= bytes_till_alignment;
580 
581     // setup state buffers - use void cast to avoid -Wcast-align warning
582     uint32_t pos = 0;
583     channel->rx_packets_state = (l2cap_ertm_rx_packet_state_t *) (void *) &buffer[pos];
584     pos += ertm_config->num_rx_buffers * sizeof(l2cap_ertm_rx_packet_state_t);
585     channel->tx_packets_state = (l2cap_ertm_tx_packet_state_t *) (void *) &buffer[pos];
586     pos += ertm_config->num_tx_buffers * sizeof(l2cap_ertm_tx_packet_state_t);
587 
588     // setup reassembly buffer
589     channel->reassembly_buffer = &buffer[pos];
590     pos += ertm_config->local_mtu;
591 
592     // divide rest of data equally
593     channel->local_mps = (size - pos) / (ertm_config->num_rx_buffers + ertm_config->num_tx_buffers);
594     log_info("Local MPS: %u", channel->local_mps);
595     channel->rx_packets_data = &buffer[pos];
596     pos += ertm_config->num_rx_buffers * channel->local_mps;
597     channel->tx_packets_data = &buffer[pos];
598 
599     channel->fcs_option = ertm_config->fcs_option;
600 }
601 
602 uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
603     l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid){
604 
605     log_info("L2CAP_CREATE_ERTM_CHANNEL addr %s, psm 0x%x, local mtu %u", bd_addr_to_str(address), psm, ertm_config->local_mtu);
606 
607     // validate local config
608     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
609     if (result) return result;
610 
611     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, address, BD_ADDR_TYPE_ACL, psm, ertm_config->local_mtu, LEVEL_0);
612     if (!channel) {
613         return BTSTACK_MEMORY_ALLOC_FAILED;
614     }
615 
616     // configure ERTM
617     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
618 
619     // add to connections list
620     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
621 
622     // store local_cid
623     if (out_local_cid){
624        *out_local_cid = channel->local_cid;
625     }
626 
627     // check if hci connection is already usable
628     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
629     if (conn){
630         log_info("l2cap_create_channel, hci connection already exists");
631         l2cap_handle_connection_complete(conn->con_handle, channel);
632         // check if remote supported fearures are already received
633         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
634             l2cap_handle_remote_supported_features_received(channel);
635         }
636     }
637 
638     l2cap_run();
639 
640     return 0;
641 }
642 
643 static void l2cap_ertm_notify_channel_can_send(l2cap_channel_t * channel){
644     if (l2cap_ertm_can_store_packet_now(channel)){
645         channel->waiting_for_can_send_now = 0;
646         l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
647     }
648 }
649 
650 uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, l2cap_ertm_config_t * ertm_config, uint8_t * buffer, uint32_t size){
651 
652     log_info("L2CAP_ACCEPT_ERTM_CONNECTION local_cid 0x%x", local_cid);
653     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
654     if (!channel) {
655         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
656         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
657     }
658 
659     // validate local config
660     uint8_t result = l2cap_ertm_validate_local_config(ertm_config);
661     if (result) return result;
662 
663     // configure L2CAP ERTM
664     l2cap_ertm_configure_channel(channel, ertm_config, buffer, size);
665 
666     // default: continue
667     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
668 
669     // verify remote ERTM support
670     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
671     if (connection == NULL) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
672 
673     if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
674         // ERTM not possible, select basic mode and release buffer
675         channel->mode = L2CAP_CHANNEL_MODE_BASIC;
676         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
677 
678         // bail if ERTM is mandatory
679         if (channel->ertm_mandatory){
680             // We chose 'no resources available' for "ERTM mandatory but you don't even know ERTM exists"
681             log_info("ERTM mandatory -> reject connection");
682             channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
683             channel->reason = 0x04; // no resources available
684         }  else {
685             log_info("ERTM not supported by remote -> use Basic mode");
686         }
687     }
688 
689     // process
690     l2cap_run();
691 
692     return ERROR_CODE_SUCCESS;
693 }
694 
695 uint8_t l2cap_ertm_set_busy(uint16_t local_cid){
696     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
697     if (!channel) {
698         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
699         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
700     }
701     if (!channel->local_busy){
702         channel->local_busy = 1;
703         channel->send_supervisor_frame_receiver_not_ready = 1;
704         l2cap_run();
705     }
706     return ERROR_CODE_SUCCESS;
707 }
708 
709 uint8_t l2cap_ertm_set_ready(uint16_t local_cid){
710     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
711     if (!channel) {
712         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
713         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
714     }
715     if (channel->local_busy){
716         channel->local_busy = 0;
717         channel->send_supervisor_frame_receiver_ready_poll = 1;
718         l2cap_run();
719     }
720     return ERROR_CODE_SUCCESS;
721 }
722 
723 // Process-ReqSeq
724 static void l2cap_ertm_process_req_seq(l2cap_channel_t * l2cap_channel, uint8_t req_seq){
725     int num_buffers_acked = 0;
726     l2cap_ertm_tx_packet_state_t * tx_state;
727     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);
728     while (true){
729 
730         // no unack packets left
731         if (l2cap_channel->unacked_frames == 0) {
732             // stop retransmission timer
733             l2cap_ertm_stop_retransmission_timer(l2cap_channel);
734             break;
735         }
736 
737         tx_state = &l2cap_channel->tx_packets_state[l2cap_channel->tx_read_index];
738         // calc delta
739         int delta = (req_seq - tx_state->tx_seq) & 0x03f;
740         if (delta == 0) break;  // all packets acknowledged
741         if (delta > l2cap_channel->remote_tx_window_size) break;
742 
743         num_buffers_acked++;
744         l2cap_channel->num_stored_tx_frames--;
745         l2cap_channel->unacked_frames--;
746         log_info("RR seq %u => packet with tx_seq %u done", req_seq, tx_state->tx_seq);
747 
748         l2cap_channel->tx_read_index++;
749         if (l2cap_channel->tx_read_index >= l2cap_channel->num_rx_buffers){
750             l2cap_channel->tx_read_index = 0;
751         }
752     }
753     if (num_buffers_acked){
754         log_info("num_buffers_acked %u", num_buffers_acked);
755     l2cap_ertm_notify_channel_can_send(l2cap_channel);
756 }
757 }
758 
759 static l2cap_ertm_tx_packet_state_t * l2cap_ertm_get_tx_state(l2cap_channel_t * l2cap_channel, uint8_t tx_seq){
760     int i;
761     for (i=0;i<l2cap_channel->num_tx_buffers;i++){
762         l2cap_ertm_tx_packet_state_t * tx_state = &l2cap_channel->tx_packets_state[i];
763         if (tx_state->tx_seq == tx_seq) return tx_state;
764     }
765     return NULL;
766 }
767 
768 // @param delta number of frames in the future, >= 1
769 // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
770 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){
771     log_info("Store SDU with delta %u", delta);
772     // get rx state for packet to store
773     int index = l2cap_channel->rx_store_index + delta - 1;
774     if (index > l2cap_channel->num_rx_buffers){
775         index -= l2cap_channel->num_rx_buffers;
776     }
777     log_info("Index of packet to store %u", index);
778     l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
779     // check if buffer is free
780     if (rx_state->valid){
781         log_error("Packet buffer already used");
782         return;
783     }
784     rx_state->valid = 1;
785     rx_state->sar = sar;
786     rx_state->len = size;
787     uint8_t * rx_buffer = &l2cap_channel->rx_packets_data[index];
788     (void)memcpy(rx_buffer, payload, size);
789 }
790 
791 // @assumption size <= l2cap_channel->local_mps (checked in l2cap_acl_classic_handler)
792 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){
793     uint16_t reassembly_sdu_length;
794     switch (sar){
795         case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
796             // assert total packet size <= our mtu
797             if (size > l2cap_channel->local_mtu) break;
798             // packet complete -> disapatch
799             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, (uint8_t*) payload, size);
800             break;
801         case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
802             // read SDU len
803             reassembly_sdu_length = little_endian_read_16(payload, 0);
804             payload += 2;
805             size    -= 2;
806             // assert reassembled size <= our mtu
807             if (reassembly_sdu_length > l2cap_channel->local_mtu) break;
808             // store start segment
809             l2cap_channel->reassembly_sdu_length = reassembly_sdu_length;
810             (void)memcpy(&l2cap_channel->reassembly_buffer[0], payload, size);
811             l2cap_channel->reassembly_pos = size;
812             break;
813         case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
814             // assert size of reassembled data <= our mtu
815             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
816             // store continuation segment
817             (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
818                          payload, size);
819             l2cap_channel->reassembly_pos += size;
820             break;
821         case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
822             // assert size of reassembled data <= our mtu
823             if (l2cap_channel->reassembly_pos + size > l2cap_channel->local_mtu) break;
824             // store continuation segment
825             (void)memcpy(&l2cap_channel->reassembly_buffer[l2cap_channel->reassembly_pos],
826                          payload, size);
827             l2cap_channel->reassembly_pos += size;
828             // assert size of reassembled data matches announced sdu length
829             if (l2cap_channel->reassembly_pos != l2cap_channel->reassembly_sdu_length) break;
830             // packet complete -> disapatch
831             l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->reassembly_buffer, l2cap_channel->reassembly_pos);
832             l2cap_channel->reassembly_pos = 0;
833             break;
834     }
835 }
836 
837 static void l2cap_ertm_channel_send_information_frame(l2cap_channel_t * channel){
838     channel->unacked_frames++;
839     int index = channel->tx_send_index;
840     channel->tx_send_index++;
841     if (channel->tx_send_index >= channel->num_tx_buffers){
842         channel->tx_send_index = 0;
843     }
844     l2cap_ertm_send_information_frame(channel, index, 0);   // final = 0
845 }
846 
847 #endif
848 
849 #ifdef L2CAP_USES_CHANNELS
850 static uint16_t l2cap_next_local_cid(void){
851     do {
852         if (local_source_cid == 0xffff) {
853             local_source_cid = 0x40;
854         } else {
855             local_source_cid++;
856         }
857     } while (l2cap_get_channel_for_local_cid(local_source_cid) != NULL);
858     return local_source_cid;
859 }
860 #endif
861 
862 static uint8_t l2cap_next_sig_id(void){
863     if (sig_seq_nr == 0xff) {
864         sig_seq_nr = 1;
865     } else {
866         sig_seq_nr++;
867     }
868     return sig_seq_nr;
869 }
870 
871 void l2cap_init(void){
872     signaling_responses_pending = 0;
873 
874     l2cap_channels = NULL;
875 
876 #ifdef ENABLE_CLASSIC
877     l2cap_services = NULL;
878     require_security_level2_for_outgoing_sdp = 0;
879 
880     // Setup Connectionless Channel
881     l2cap_fixed_channel_connectionless.local_cid     = L2CAP_CID_CONNECTIONLESS_CHANNEL;
882     l2cap_fixed_channel_connectionless.channel_type  = L2CAP_CHANNEL_TYPE_CONNECTIONLESS;
883     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_connectionless);
884 #endif
885 
886 #ifdef ENABLE_LE_DATA_CHANNELS
887     l2cap_le_services = NULL;
888 #endif
889 
890 #ifdef ENABLE_BLE
891     l2cap_event_packet_handler = NULL;
892     l2cap_le_custom_max_mtu = 0;
893 
894     // Setup fixed ATT Channel
895     l2cap_fixed_channel_att.local_cid    = L2CAP_CID_ATTRIBUTE_PROTOCOL;
896     l2cap_fixed_channel_att.channel_type = L2CAP_CHANNEL_TYPE_LE_FIXED;
897     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_att);
898 
899     // Setup fixed SM Channel
900     l2cap_fixed_channel_sm.local_cid     = L2CAP_CID_SECURITY_MANAGER_PROTOCOL;
901     l2cap_fixed_channel_sm.channel_type  = L2CAP_CHANNEL_TYPE_LE_FIXED;
902     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) &l2cap_fixed_channel_sm);
903 #endif
904 
905     //
906     // register callback with HCI
907     //
908     hci_event_callback_registration.callback = &l2cap_hci_event_handler;
909     hci_add_event_handler(&hci_event_callback_registration);
910 
911     hci_register_acl_packet_handler(&l2cap_acl_handler);
912 
913 #ifdef ENABLE_CLASSIC
914     gap_connectable_control(0); // no services yet
915 #endif
916 }
917 
918 void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size)){
919 #ifdef ENABLE_BLE
920     l2cap_event_packet_handler = handler;
921 #else
922     UNUSED(handler);    // ok: no code
923 #endif
924 }
925 
926 void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id){
927     UNUSED(con_handle);  // ok: there is no con handle
928 
929     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
930     if (!channel) return;
931     channel->waiting_for_can_send_now = 1;
932     l2cap_notify_channel_can_send();
933 }
934 
935 int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id){
936     UNUSED(channel_id); // ok: only depends on Controller LE buffers
937 
938     return hci_can_send_acl_packet_now(con_handle);
939 }
940 
941 uint8_t *l2cap_get_outgoing_buffer(void){
942     return hci_get_outgoing_packet_buffer() + COMPLETE_L2CAP_HEADER; // 8 bytes
943 }
944 
945 // only for L2CAP Basic Channels
946 int l2cap_reserve_packet_buffer(void){
947     return hci_reserve_packet_buffer();
948 }
949 
950 // only for L2CAP Basic Channels
951 void l2cap_release_packet_buffer(void){
952     hci_release_packet_buffer();
953 }
954 
955 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){
956     // 0 - Connection handle : PB=pb : BC=00
957     little_endian_store_16(acl_buffer, 0, con_handle | (packet_boundary << 12) | (0 << 14));
958     // 2 - ACL length
959     little_endian_store_16(acl_buffer, 2,  len + 4);
960     // 4 - L2CAP packet length
961     little_endian_store_16(acl_buffer, 4,  len + 0);
962     // 6 - L2CAP channel DEST
963     little_endian_store_16(acl_buffer, 6,  remote_cid);
964 }
965 
966 // assumption - only on LE connections
967 int l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len){
968 
969     if (!hci_is_packet_buffer_reserved()){
970         log_error("l2cap_send_prepared_connectionless called without reserving packet first");
971         return BTSTACK_ACL_BUFFERS_FULL;
972     }
973 
974     if (!hci_can_send_prepared_acl_packet_now(con_handle)){
975         log_info("l2cap_send_prepared_connectionless handle 0x%02x, cid 0x%02x, cannot send", con_handle, cid);
976         return BTSTACK_ACL_BUFFERS_FULL;
977     }
978 
979     log_debug("l2cap_send_prepared_connectionless handle %u, cid 0x%02x", con_handle, cid);
980 
981     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
982     l2cap_setup_header(acl_buffer, con_handle, 0, cid, len);
983     // send
984     return hci_send_acl_packet_buffer(len+8);
985 }
986 
987 // assumption - only on LE connections
988 int l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len){
989 
990     if (!hci_can_send_acl_packet_now(con_handle)){
991         log_info("l2cap_send cid 0x%02x, cannot send", cid);
992         return BTSTACK_ACL_BUFFERS_FULL;
993     }
994 
995     hci_reserve_packet_buffer();
996     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
997 
998     (void)memcpy(&acl_buffer[8], data, len);
999 
1000     return l2cap_send_prepared_connectionless(con_handle, cid, len);
1001 }
1002 
1003 static void l2cap_emit_can_send_now(btstack_packet_handler_t packet_handler, uint16_t channel) {
1004     log_debug("L2CAP_EVENT_CHANNEL_CAN_SEND_NOW local_cid 0x%x", channel);
1005     uint8_t event[4];
1006     event[0] = L2CAP_EVENT_CAN_SEND_NOW;
1007     event[1] = sizeof(event) - 2;
1008     little_endian_store_16(event, 2, channel);
1009     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1010     packet_handler(HCI_EVENT_PACKET, channel, event, sizeof(event));
1011 }
1012 
1013 #ifdef L2CAP_USES_CHANNELS
1014 static void l2cap_dispatch_to_channel(l2cap_channel_t *channel, uint8_t type, uint8_t * data, uint16_t size){
1015     (* (channel->packet_handler))(type, channel->local_cid, data, size);
1016 }
1017 
1018 static void l2cap_emit_simple_event_with_cid(l2cap_channel_t * channel, uint8_t event_code){
1019     uint8_t event[4];
1020     event[0] = event_code;
1021     event[1] = sizeof(event) - 2;
1022     little_endian_store_16(event, 2, channel->local_cid);
1023     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1024     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1025 }
1026 #endif
1027 
1028 #ifdef ENABLE_CLASSIC
1029 void l2cap_emit_channel_opened(l2cap_channel_t *channel, uint8_t status) {
1030     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",
1031              status, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
1032              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu, channel->flush_timeout);
1033     uint8_t event[26];
1034     event[0] = L2CAP_EVENT_CHANNEL_OPENED;
1035     event[1] = sizeof(event) - 2;
1036     event[2] = status;
1037     reverse_bd_addr(channel->address, &event[3]);
1038     little_endian_store_16(event,  9, channel->con_handle);
1039     little_endian_store_16(event, 11, channel->psm);
1040     little_endian_store_16(event, 13, channel->local_cid);
1041     little_endian_store_16(event, 15, channel->remote_cid);
1042     little_endian_store_16(event, 17, channel->local_mtu);
1043     little_endian_store_16(event, 19, channel->remote_mtu);
1044     little_endian_store_16(event, 21, channel->flush_timeout);
1045     event[23] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
1046 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1047     log_info("ERTM mode %u, fcs enabled %u", channel->mode, channel->fcs_option);
1048     event[24] = channel->mode;
1049     event[25] = channel->fcs_option;
1050 
1051 #else
1052     event[24] = L2CAP_CHANNEL_MODE_BASIC;
1053     event[25] = 0;
1054 #endif
1055     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1056     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1057 }
1058 
1059 static void l2cap_emit_channel_closed(l2cap_channel_t *channel) {
1060     log_info("L2CAP_EVENT_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
1061     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
1062 }
1063 
1064 static void l2cap_emit_incoming_connection(l2cap_channel_t *channel) {
1065     log_info("L2CAP_EVENT_INCOMING_CONNECTION addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x",
1066              bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid);
1067     uint8_t event[16];
1068     event[0] = L2CAP_EVENT_INCOMING_CONNECTION;
1069     event[1] = sizeof(event) - 2;
1070     reverse_bd_addr(channel->address, &event[2]);
1071     little_endian_store_16(event,  8, channel->con_handle);
1072     little_endian_store_16(event, 10, channel->psm);
1073     little_endian_store_16(event, 12, channel->local_cid);
1074     little_endian_store_16(event, 14, channel->remote_cid);
1075     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
1076     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
1077 }
1078 
1079 static void l2cap_handle_channel_open_failed(l2cap_channel_t * channel, uint8_t status){
1080 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1081     // emit ertm buffer released, as it's not needed. if in basic mode, it was either not allocated or already released
1082     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1083         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1084     }
1085 #endif
1086     l2cap_emit_channel_opened(channel, status);
1087 }
1088 
1089 static void l2cap_handle_channel_closed(l2cap_channel_t * channel){
1090 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1091     // emit ertm buffer released, as it's not needed anymore. if in basic mode, it was either not allocated or already released
1092     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1093         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1094     }
1095 #endif
1096     l2cap_emit_channel_closed(channel);
1097 }
1098 #endif
1099 
1100 static l2cap_fixed_channel_t * l2cap_channel_item_by_cid(uint16_t cid){
1101     btstack_linked_list_iterator_t it;
1102     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1103     while (btstack_linked_list_iterator_has_next(&it)){
1104         l2cap_fixed_channel_t * channel = (l2cap_fixed_channel_t*) btstack_linked_list_iterator_next(&it);
1105         if (channel->local_cid == cid) {
1106             return channel;
1107         }
1108     }
1109     return NULL;
1110 }
1111 
1112 // used for fixed channels in LE (ATT/SM) and Classic (Connectionless Channel). CID < 0x04
1113 static l2cap_fixed_channel_t * l2cap_fixed_channel_for_channel_id(uint16_t local_cid){
1114     if (local_cid >= 0x40) return NULL;
1115     return (l2cap_fixed_channel_t*) l2cap_channel_item_by_cid(local_cid);
1116 }
1117 
1118 // used for Classic Channels + LE Data Channels. local_cid >= 0x40
1119 #ifdef L2CAP_USES_CHANNELS
1120 static l2cap_channel_t * l2cap_get_channel_for_local_cid(uint16_t local_cid){
1121     if (local_cid < 0x40) return NULL;
1122     return (l2cap_channel_t*) l2cap_channel_item_by_cid(local_cid);
1123 }
1124 
1125 void l2cap_request_can_send_now_event(uint16_t local_cid){
1126     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1127     if (!channel) return;
1128     channel->waiting_for_can_send_now = 1;
1129 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1130     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1131         l2cap_ertm_notify_channel_can_send(channel);
1132         return;
1133     }
1134 #endif
1135     l2cap_notify_channel_can_send();
1136 }
1137 
1138 int  l2cap_can_send_packet_now(uint16_t local_cid){
1139     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1140     if (!channel) return 0;
1141 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1142     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1143         return l2cap_ertm_can_store_packet_now(channel);
1144     }
1145 #endif
1146     return hci_can_send_acl_packet_now(channel->con_handle);
1147 }
1148 
1149 int  l2cap_can_send_prepared_packet_now(uint16_t local_cid){
1150     l2cap_channel_t *channel = l2cap_get_channel_for_local_cid(local_cid);
1151     if (!channel) return 0;
1152 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1153     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1154         return 0;
1155     }
1156 #endif
1157     return hci_can_send_prepared_acl_packet_now(channel->con_handle);
1158 }
1159 
1160 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid){
1161     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1162     if (channel) {
1163         return channel->remote_mtu;
1164     }
1165     return 0;
1166 }
1167 #endif
1168 
1169 #ifdef L2CAP_USES_CHANNELS
1170 static int l2cap_is_dynamic_channel_type(l2cap_channel_type_t channel_type){
1171     switch (channel_type){
1172         case L2CAP_CHANNEL_TYPE_CLASSIC:
1173         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
1174             return 1;
1175         default:
1176             return 0;
1177     }
1178 }
1179 #endif
1180 
1181 #ifdef ENABLE_CLASSIC
1182 // RTX Timer only exist for dynamic channels
1183 static l2cap_channel_t * l2cap_channel_for_rtx_timer(btstack_timer_source_t * ts){
1184     btstack_linked_list_iterator_t it;
1185     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1186     while (btstack_linked_list_iterator_has_next(&it)){
1187         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1188         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
1189         if (&channel->rtx == ts) {
1190             return channel;
1191         }
1192     }
1193     return NULL;
1194 }
1195 
1196 static void l2cap_rtx_timeout(btstack_timer_source_t * ts){
1197     l2cap_channel_t * channel = l2cap_channel_for_rtx_timer(ts);
1198     if (!channel) return;
1199 
1200     log_info("l2cap_rtx_timeout for local cid 0x%02x", channel->local_cid);
1201 
1202     // "When terminating the channel, it is not necessary to send a L2CAP_DisconnectReq
1203     //  and enter WAIT_DISCONNECT state. Channels can be transitioned directly to the CLOSED state."
1204     // notify client
1205     l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_RTX_TIMEOUT);
1206 
1207     // discard channel
1208     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1209     l2cap_free_channel_entry(channel);
1210 }
1211 
1212 #endif
1213 
1214 #ifdef L2CAP_USES_CHANNELS
1215 static void l2cap_stop_rtx(l2cap_channel_t * channel){
1216     log_info("l2cap_stop_rtx for local cid 0x%02x", channel->local_cid);
1217     btstack_run_loop_remove_timer(&channel->rtx);
1218 }
1219 #endif
1220 
1221 #ifdef ENABLE_CLASSIC
1222 
1223 static void l2cap_start_rtx(l2cap_channel_t * channel){
1224     l2cap_stop_rtx(channel);
1225     log_info("l2cap_start_rtx for local cid 0x%02x", channel->local_cid);
1226     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1227     btstack_run_loop_set_timer(&channel->rtx, L2CAP_RTX_TIMEOUT_MS);
1228     btstack_run_loop_add_timer(&channel->rtx);
1229 }
1230 
1231 static void l2cap_start_ertx(l2cap_channel_t * channel){
1232     log_info("l2cap_start_ertx for local cid 0x%02x", channel->local_cid);
1233     l2cap_stop_rtx(channel);
1234     btstack_run_loop_set_timer_handler(&channel->rtx, l2cap_rtx_timeout);
1235     btstack_run_loop_set_timer(&channel->rtx, L2CAP_ERTX_TIMEOUT_MS);
1236     btstack_run_loop_add_timer(&channel->rtx);
1237 }
1238 
1239 void l2cap_require_security_level_2_for_outgoing_sdp(void){
1240     require_security_level2_for_outgoing_sdp = 1;
1241 }
1242 
1243 static int l2cap_security_level_0_allowed_for_PSM(uint16_t psm){
1244     return (psm == BLUETOOTH_PSM_SDP) && (!require_security_level2_for_outgoing_sdp);
1245 }
1246 
1247 static int l2cap_send_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1248     if (!hci_can_send_acl_packet_now(handle)){
1249         log_info("l2cap_send_signaling_packet, cannot send");
1250         return BTSTACK_ACL_BUFFERS_FULL;
1251     }
1252 
1253     // log_info("l2cap_send_signaling_packet type %u", cmd);
1254     hci_reserve_packet_buffer();
1255     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1256     va_list argptr;
1257     va_start(argptr, identifier);
1258     uint16_t len = l2cap_create_signaling_classic(acl_buffer, handle, cmd, identifier, argptr);
1259     va_end(argptr);
1260     // log_info("l2cap_send_signaling_packet con %u!", handle);
1261     return hci_send_acl_packet_buffer(len);
1262 }
1263 
1264 // assumption - only on Classic connections
1265 // cannot be used for L2CAP ERTM
1266 int l2cap_send_prepared(uint16_t local_cid, uint16_t len){
1267 
1268     if (!hci_is_packet_buffer_reserved()){
1269         log_error("l2cap_send_prepared called without reserving packet first");
1270         return BTSTACK_ACL_BUFFERS_FULL;
1271     }
1272 
1273     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1274     if (!channel) {
1275         log_error("l2cap_send_prepared no channel for cid 0x%02x", local_cid);
1276         return -1;   // TODO: define error
1277     }
1278 
1279     if (!hci_can_send_prepared_acl_packet_now(channel->con_handle)){
1280         log_info("l2cap_send_prepared cid 0x%02x, cannot send", local_cid);
1281         return BTSTACK_ACL_BUFFERS_FULL;
1282     }
1283 
1284     log_debug("l2cap_send_prepared cid 0x%02x, handle %u, 1 credit used", local_cid, channel->con_handle);
1285 
1286     int fcs_size = 0;
1287 
1288 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1289     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->fcs_option){
1290         fcs_size = 2;
1291     }
1292 #endif
1293 
1294     // set non-flushable packet boundary flag if supported on Controller
1295     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1296     uint8_t packet_boundary_flag = hci_non_flushable_packet_boundary_flag_supported() ? 0x00 : 0x02;
1297     l2cap_setup_header(acl_buffer, channel->con_handle, packet_boundary_flag, channel->remote_cid, len + fcs_size);
1298 
1299 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1300     if (fcs_size){
1301         // calculate FCS over l2cap data
1302         uint16_t fcs = crc16_calc(acl_buffer + 4, 4 + len);
1303         log_info("I-Frame: fcs 0x%04x", fcs);
1304         little_endian_store_16(acl_buffer, 8 + len, fcs);
1305     }
1306 #endif
1307 
1308     // send
1309     return hci_send_acl_packet_buffer(len+8+fcs_size);
1310 }
1311 
1312 // assumption - only on Classic connections
1313 int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len){
1314     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1315     if (!channel) {
1316         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
1317         return -1;   // TODO: define error
1318     }
1319 
1320 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1321     // send in ERTM
1322     if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1323         return l2cap_ertm_send(channel, data, len);
1324     }
1325 #endif
1326 
1327     if (len > channel->remote_mtu){
1328         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
1329         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
1330     }
1331 
1332     if (!hci_can_send_acl_packet_now(channel->con_handle)){
1333         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
1334         return BTSTACK_ACL_BUFFERS_FULL;
1335     }
1336 
1337     hci_reserve_packet_buffer();
1338     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1339     (void)memcpy(&acl_buffer[8], data, len);
1340     return l2cap_send_prepared(local_cid, len);
1341 }
1342 
1343 int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len){
1344     return l2cap_send_signaling_packet(con_handle, ECHO_REQUEST, 0x77, len, data);
1345 }
1346 
1347 static inline void channelStateVarSetFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
1348     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var | flag);
1349 }
1350 
1351 static inline void channelStateVarClearFlag(l2cap_channel_t *channel, L2CAP_CHANNEL_STATE_VAR flag){
1352     channel->state_var = (L2CAP_CHANNEL_STATE_VAR) (channel->state_var & ~flag);
1353 }
1354 #endif
1355 
1356 
1357 #ifdef ENABLE_BLE
1358 static int l2cap_send_le_signaling_packet(hci_con_handle_t handle, L2CAP_SIGNALING_COMMANDS cmd, int identifier, ...){
1359 
1360     if (!hci_can_send_acl_packet_now(handle)){
1361         log_info("l2cap_send_le_signaling_packet, cannot send");
1362         return BTSTACK_ACL_BUFFERS_FULL;
1363     }
1364 
1365     // log_info("l2cap_send_le_signaling_packet type %u", cmd);
1366     hci_reserve_packet_buffer();
1367     uint8_t *acl_buffer = hci_get_outgoing_packet_buffer();
1368     va_list argptr;
1369     va_start(argptr, identifier);
1370     uint16_t len = l2cap_create_signaling_le(acl_buffer, handle, cmd, identifier, argptr);
1371     va_end(argptr);
1372     // log_info("l2cap_send_le_signaling_packet con %u!", handle);
1373     return hci_send_acl_packet_buffer(len);
1374 }
1375 #endif
1376 
1377 uint16_t l2cap_max_mtu(void){
1378     return HCI_ACL_PAYLOAD_SIZE - L2CAP_HEADER_SIZE;
1379 }
1380 
1381 #ifdef ENABLE_BLE
1382 uint16_t l2cap_max_le_mtu(void){
1383     if (l2cap_le_custom_max_mtu != 0) return l2cap_le_custom_max_mtu;
1384     return l2cap_max_mtu();
1385 }
1386 
1387 void l2cap_set_max_le_mtu(uint16_t max_mtu){
1388     if (max_mtu < l2cap_max_mtu()){
1389         l2cap_le_custom_max_mtu = max_mtu;
1390     }
1391 }
1392 #endif
1393 
1394 #ifdef ENABLE_CLASSIC
1395 
1396 static uint16_t l2cap_setup_options_mtu(uint8_t * config_options, uint16_t mtu){
1397     config_options[0] = L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT; // MTU
1398     config_options[1] = 2; // len param
1399     little_endian_store_16(config_options, 2, mtu);
1400     return 4;
1401 }
1402 
1403 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1404 static int l2cap_ertm_mode(l2cap_channel_t * channel){
1405     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
1406     return ((connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_DONE)
1407         &&  (connection->l2cap_state.extended_feature_mask & 0x08));
1408 }
1409 #endif
1410 
1411 static uint16_t l2cap_setup_options_request(l2cap_channel_t * channel, uint8_t * config_options){
1412 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1413     // use ERTM options if supported by remote and channel ready to use it
1414     if (l2cap_ertm_mode(channel) && channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1415         return l2cap_setup_options_ertm_request(channel, config_options);
1416     }
1417 #endif
1418     uint16_t mtu = channel->local_mtu;
1419     return l2cap_setup_options_mtu(config_options, mtu);
1420 }
1421 
1422 static uint16_t l2cap_setup_options_mtu_response(l2cap_channel_t * channel, uint8_t * config_options){
1423     uint16_t mtu = btstack_min(channel->local_mtu, channel->remote_mtu);
1424     return l2cap_setup_options_mtu(config_options, mtu);
1425 }
1426 
1427 static uint32_t l2cap_extended_features_mask(void){
1428     // extended features request supported, features: fixed channels, unicast connectionless data reception
1429     uint32_t features = 0x280;
1430 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1431     features |= 0x0028;
1432 #endif
1433     return features;
1434 }
1435 #endif
1436 
1437 // MARK: L2CAP_RUN
1438 // process outstanding signaling tasks
1439 static void l2cap_run(void){
1440 
1441     // log_info("l2cap_run: entered");
1442 
1443     // check pending signaling responses
1444     while (signaling_responses_pending){
1445 
1446         hci_con_handle_t handle = signaling_responses[0].handle;
1447 
1448         if (!hci_can_send_acl_packet_now(handle)) break;
1449 
1450         uint8_t  sig_id        = signaling_responses[0].sig_id;
1451         uint8_t  response_code = signaling_responses[0].code;
1452         uint16_t result        = signaling_responses[0].data;  // CONNECTION_REQUEST, COMMAND_REJECT
1453 #ifdef ENABLE_CLASSIC
1454         uint16_t info_type     = signaling_responses[0].data;  // INFORMATION_REQUEST
1455         uint16_t source_cid    = signaling_responses[0].cid;   // CONNECTION_REQUEST
1456 #endif
1457 
1458         // remove first item before sending (to avoid sending response mutliple times)
1459         signaling_responses_pending--;
1460         int i;
1461         for (i=0; i < signaling_responses_pending; i++){
1462             (void)memcpy(&signaling_responses[i],
1463                          &signaling_responses[i + 1],
1464                          sizeof(l2cap_signaling_response_t));
1465         }
1466 
1467         switch (response_code){
1468 #ifdef ENABLE_CLASSIC
1469             case CONNECTION_REQUEST:
1470                 l2cap_send_signaling_packet(handle, CONNECTION_RESPONSE, sig_id, source_cid, 0, result, 0);
1471                 // also disconnect if result is 0x0003 - security blocked
1472                 if (result == 0x0003){
1473                     hci_disconnect_security_block(handle);
1474                 }
1475                 break;
1476             case ECHO_REQUEST:
1477                 l2cap_send_signaling_packet(handle, ECHO_RESPONSE, sig_id, 0, NULL);
1478                 break;
1479             case INFORMATION_REQUEST:
1480                 switch (info_type){
1481                     case L2CAP_INFO_TYPE_CONNECTIONLESS_MTU: {
1482                             uint16_t connectionless_mtu = hci_max_acl_data_packet_length();
1483                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(connectionless_mtu), &connectionless_mtu);
1484                         }
1485                         break;
1486                     case L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED: {
1487                             uint32_t features = l2cap_extended_features_mask();
1488                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(features), &features);
1489                         }
1490                         break;
1491                     case L2CAP_INFO_TYPE_FIXED_CHANNELS_SUPPORTED: {
1492                             uint8_t map[8];
1493                             memset(map, 0, 8);
1494                             map[0] = 0x06;  // L2CAP Signaling Channel (0x02) + Connectionless reception (0x04)
1495                             l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 0, sizeof(map), &map);
1496                         }
1497                         break;
1498                     default:
1499                         // all other types are not supported
1500                         l2cap_send_signaling_packet(handle, INFORMATION_RESPONSE, sig_id, info_type, 1, 0, NULL);
1501                         break;
1502                 }
1503                 break;
1504             case COMMAND_REJECT:
1505                 l2cap_send_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
1506                 break;
1507 #endif
1508 #ifdef ENABLE_BLE
1509             case LE_CREDIT_BASED_CONNECTION_REQUEST:
1510                 l2cap_send_le_signaling_packet(handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, sig_id, 0, 0, 0, 0, result);
1511                 break;
1512             case COMMAND_REJECT_LE:
1513                 l2cap_send_le_signaling_packet(handle, COMMAND_REJECT, sig_id, result, 0, NULL);
1514                 break;
1515 #endif
1516             default:
1517                 // should not happen
1518                 break;
1519         }
1520     }
1521 
1522 #if defined(ENABLE_CLASSIC) || defined(ENABLE_BLE)
1523     btstack_linked_list_iterator_t it;
1524 #endif
1525 
1526 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1527     // send l2cap information request if neccessary
1528     hci_connections_get_iterator(&it);
1529     while(btstack_linked_list_iterator_has_next(&it)){
1530         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1531         if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST){
1532             if (!hci_can_send_acl_packet_now(connection->con_handle)) break;
1533             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE;
1534             uint8_t sig_id = l2cap_next_sig_id();
1535             uint8_t info_type = L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED;
1536             l2cap_send_signaling_packet(connection->con_handle, INFORMATION_REQUEST, sig_id, info_type);
1537             return;
1538         }
1539     }
1540 #endif
1541 
1542 #ifdef ENABLE_CLASSIC
1543 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1544     uint8_t  config_options[18];
1545 #else
1546     uint8_t  config_options[10];
1547 #endif
1548     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1549     while (btstack_linked_list_iterator_has_next(&it)){
1550 
1551         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1552 
1553         if (channel->channel_type != L2CAP_CHANNEL_TYPE_CLASSIC) continue;
1554 
1555         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1556         switch (channel->state){
1557 
1558             case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1559             case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
1560                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1561                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND) {
1562                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND);
1563                     l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 1, 0);
1564                 }
1565                 break;
1566 
1567             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1568                 if (!hci_can_send_command_packet_now()) break;
1569                 // send connection request - set state first
1570                 channel->state = L2CAP_STATE_WAIT_CONNECTION_COMPLETE;
1571                 // BD_ADDR, Packet_Type, Page_Scan_Repetition_Mode, Reserved, Clock_Offset, Allow_Role_Switch
1572                 (void)memcpy(l2cap_outgoing_classic_addr, channel->address, 6);
1573                 hci_send_cmd(&hci_create_connection, channel->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
1574                 break;
1575 
1576             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
1577                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1578                 channel->state = L2CAP_STATE_INVALID;
1579                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, channel->reason, 0);
1580                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1581                 btstack_linked_list_iterator_remove(&it);
1582                 l2cap_free_channel_entry(channel);
1583                 channel = NULL;
1584                 break;
1585 
1586             case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
1587                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1588                 channel->state = L2CAP_STATE_CONFIG;
1589                 channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1590                 l2cap_send_signaling_packet(channel->con_handle, CONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid, 0, 0);
1591                 break;
1592 
1593             case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
1594                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1595                 // success, start l2cap handshake
1596                 channel->local_sig_id = l2cap_next_sig_id();
1597                 channel->state = L2CAP_STATE_WAIT_CONNECT_RSP;
1598                 l2cap_send_signaling_packet( channel->con_handle, CONNECTION_REQUEST, channel->local_sig_id, channel->psm, channel->local_cid);
1599                 l2cap_start_rtx(channel);
1600                 break;
1601 
1602             case L2CAP_STATE_CONFIG:
1603                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1604 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1605                     // fallback to basic mode if ERTM requested but not not supported by remote
1606                      if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1607                         if (!l2cap_ertm_mode(channel)){
1608                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
1609                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
1610                         }
1611                     }
1612 #endif
1613                 if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP){
1614                     uint16_t flags = 0;
1615                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
1616                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT) {
1617                         flags = 1;
1618                     } else {
1619                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1620                     }
1621                     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID){
1622                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1623                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNKNOWN_OPTIONS, 0, NULL);
1624 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1625                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED){
1626                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
1627                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP);
1628                         uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1629                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS, options_size, &config_options);
1630                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM){
1631                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
1632                         channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1633                         uint16_t options_size = l2cap_setup_options_ertm_response(channel, config_options);
1634                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, options_size, &config_options);
1635 #endif
1636                     } else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU){
1637                         channelStateVarClearFlag(channel,L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
1638                         uint16_t options_size = l2cap_setup_options_mtu_response(channel, config_options);
1639                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, options_size, &config_options);
1640                     } else {
1641                         l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_RESPONSE, channel->remote_sig_id, channel->remote_cid, flags, L2CAP_CONF_RESULT_SUCCESS, 0, NULL);
1642                     }
1643                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
1644                 }
1645                 else if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ){
1646                     channelStateVarClearFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
1647                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ);
1648                     channel->local_sig_id = l2cap_next_sig_id();
1649                     uint16_t options_size = l2cap_setup_options_request(channel, config_options);
1650                     l2cap_send_signaling_packet(channel->con_handle, CONFIGURE_REQUEST, channel->local_sig_id, channel->remote_cid, 0, options_size, &config_options);
1651                     l2cap_start_rtx(channel);
1652                 }
1653                 if (l2cap_channel_ready_for_open(channel)){
1654                     channel->state = L2CAP_STATE_OPEN;
1655                     l2cap_emit_channel_opened(channel, 0);  // success
1656                 }
1657                 break;
1658 
1659             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1660                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1661                 channel->state = L2CAP_STATE_INVALID;
1662                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1663                 // 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 :)
1664                 l2cap_finialize_channel_close(channel);  // -- remove from list
1665                 channel = NULL;
1666                 break;
1667 
1668             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1669                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1670                 channel->local_sig_id = l2cap_next_sig_id();
1671                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1672                 l2cap_send_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1673                 break;
1674             default:
1675                 break;
1676         }
1677 
1678 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1679 
1680         // handle channel finalize on L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE and L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE
1681         if (!channel) continue;
1682 
1683         // ERTM mode
1684         if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
1685 
1686             // check if we can still send
1687             if (channel->con_handle == HCI_CON_HANDLE_INVALID) continue;
1688             if (!hci_can_send_acl_packet_now(channel->con_handle)) continue;
1689 
1690             if (channel->send_supervisor_frame_receiver_ready){
1691                 channel->send_supervisor_frame_receiver_ready = 0;
1692                 log_info("Send S-Frame: RR %u, final %u", channel->req_seq, channel->set_final_bit_after_packet_with_poll_bit_set);
1693                 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);
1694                 channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1695                 l2cap_ertm_send_supervisor_frame(channel, control);
1696                 continue;
1697             }
1698             if (channel->send_supervisor_frame_receiver_ready_poll){
1699                 channel->send_supervisor_frame_receiver_ready_poll = 0;
1700                 log_info("Send S-Frame: RR %u with poll=1 ", channel->req_seq);
1701                 uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY, 1, 0, channel->req_seq);
1702                 l2cap_ertm_send_supervisor_frame(channel, control);
1703                 continue;
1704             }
1705             if (channel->send_supervisor_frame_receiver_not_ready){
1706                 channel->send_supervisor_frame_receiver_not_ready = 0;
1707                 log_info("Send S-Frame: RNR %u", channel->req_seq);
1708                 uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY, 0, 0, channel->req_seq);
1709                 l2cap_ertm_send_supervisor_frame(channel, control);
1710                 continue;
1711             }
1712             if (channel->send_supervisor_frame_reject){
1713                 channel->send_supervisor_frame_reject = 0;
1714                 log_info("Send S-Frame: REJ %u", channel->req_seq);
1715                 uint16_t control = l2cap_encanced_control_field_for_supevisor_frame( L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT, 0, 0, channel->req_seq);
1716                 l2cap_ertm_send_supervisor_frame(channel, control);
1717                 continue;
1718             }
1719             if (channel->send_supervisor_frame_selective_reject){
1720                 channel->send_supervisor_frame_selective_reject = 0;
1721                 log_info("Send S-Frame: SREJ %u", channel->expected_tx_seq);
1722                 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);
1723                 channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1724                 l2cap_ertm_send_supervisor_frame(channel, control);
1725                 continue;
1726             }
1727 
1728             if (channel->srej_active){
1729                 int i;
1730                 for (i=0;i<channel->num_tx_buffers;i++){
1731                     l2cap_ertm_tx_packet_state_t * tx_state = &channel->tx_packets_state[i];
1732                     if (tx_state->retransmission_requested) {
1733                         tx_state->retransmission_requested = 0;
1734                         uint8_t final = channel->set_final_bit_after_packet_with_poll_bit_set;
1735                         channel->set_final_bit_after_packet_with_poll_bit_set = 0;
1736                         l2cap_ertm_send_information_frame(channel, i, final);
1737                         break;
1738                     }
1739                 }
1740                 if (i == channel->num_tx_buffers){
1741                     // no retransmission request found
1742                     channel->srej_active = 0;
1743                 } else {
1744                     // packet was sent
1745                     continue;
1746                 }
1747             }
1748         }
1749 #endif
1750 
1751     }
1752 #endif
1753 
1754 #ifdef ENABLE_LE_DATA_CHANNELS
1755     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1756     while (btstack_linked_list_iterator_has_next(&it)){
1757         uint16_t mps;
1758         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1759 
1760         if (channel->channel_type != L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL) continue;
1761 
1762         // log_info("l2cap_run: channel %p, state %u, var 0x%02x", channel, channel->state, channel->state_var);
1763         switch (channel->state){
1764             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
1765                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1766                 channel->state = L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE;
1767                 // le psm, source cid, mtu, mps, initial credits
1768                 channel->local_sig_id = l2cap_next_sig_id();
1769                 channel->credits_incoming =  channel->new_credits_incoming;
1770                 channel->new_credits_incoming = 0;
1771                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
1772                 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);
1773                 break;
1774             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
1775                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1776                 // TODO: support larger MPS
1777                 channel->state = L2CAP_STATE_OPEN;
1778                 channel->credits_incoming =  channel->new_credits_incoming;
1779                 channel->new_credits_incoming = 0;
1780                 mps = btstack_min(l2cap_max_le_mtu(), channel->local_mtu);
1781                 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);
1782                 // notify client
1783                 l2cap_emit_le_channel_opened(channel, 0);
1784                 break;
1785             case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
1786                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1787                 channel->state = L2CAP_STATE_INVALID;
1788                 l2cap_send_le_signaling_packet(channel->con_handle, LE_CREDIT_BASED_CONNECTION_RESPONSE, channel->remote_sig_id, 0, 0, 0, 0, channel->reason);
1789                 // discard channel - l2cap_finialize_channel_close without sending l2cap close event
1790                 btstack_linked_list_iterator_remove(&it);
1791                 l2cap_free_channel_entry(channel);
1792                 break;
1793             case L2CAP_STATE_OPEN:
1794                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1795 
1796                 // send credits
1797                 if (channel->new_credits_incoming){
1798                     log_info("l2cap: sending %u credits", channel->new_credits_incoming);
1799                     channel->local_sig_id = l2cap_next_sig_id();
1800                     uint16_t new_credits = channel->new_credits_incoming;
1801                     channel->new_credits_incoming = 0;
1802                     channel->credits_incoming += new_credits;
1803                     l2cap_send_le_signaling_packet(channel->con_handle, LE_FLOW_CONTROL_CREDIT, channel->local_sig_id, channel->remote_cid, new_credits);
1804                 }
1805                 break;
1806 
1807             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1808                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1809                 channel->local_sig_id = l2cap_next_sig_id();
1810                 channel->state = L2CAP_STATE_WAIT_DISCONNECT;
1811                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_REQUEST, channel->local_sig_id, channel->remote_cid, channel->local_cid);
1812                 break;
1813             case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1814                 if (!hci_can_send_acl_packet_now(channel->con_handle)) break;
1815                 channel->state = L2CAP_STATE_INVALID;
1816                 l2cap_send_le_signaling_packet( channel->con_handle, DISCONNECTION_RESPONSE, channel->remote_sig_id, channel->local_cid, channel->remote_cid);
1817                 l2cap_le_finialize_channel_close(channel);  // -- remove from list
1818                 break;
1819             default:
1820                 break;
1821         }
1822     }
1823 #endif
1824 
1825 #ifdef ENABLE_BLE
1826     // send l2cap con paramter update if necessary
1827     hci_connections_get_iterator(&it);
1828     while(btstack_linked_list_iterator_has_next(&it)){
1829         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
1830         if ((connection->address_type != BD_ADDR_TYPE_LE_PUBLIC) && (connection->address_type != BD_ADDR_TYPE_LE_RANDOM)) continue;
1831         if (!hci_can_send_acl_packet_now(connection->con_handle)) continue;
1832         switch (connection->le_con_parameter_update_state){
1833             case CON_PARAMETER_UPDATE_SEND_REQUEST:
1834                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1835                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_REQUEST, l2cap_next_sig_id(),
1836                                                connection->le_conn_interval_min, connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout);
1837                 break;
1838             case CON_PARAMETER_UPDATE_SEND_RESPONSE:
1839                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
1840                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 0);
1841                 break;
1842             case CON_PARAMETER_UPDATE_DENY:
1843                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
1844                 l2cap_send_le_signaling_packet(connection->con_handle, CONNECTION_PARAMETER_UPDATE_RESPONSE, connection->le_con_param_update_identifier, 1);
1845                 break;
1846             default:
1847                 break;
1848         }
1849     }
1850 #endif
1851 
1852     // log_info("l2cap_run: exit");
1853 }
1854 
1855 #ifdef ENABLE_CLASSIC
1856 static void l2cap_handle_connection_complete(hci_con_handle_t con_handle, l2cap_channel_t * channel){
1857     if ((channel->state == L2CAP_STATE_WAIT_CONNECTION_COMPLETE) || (channel->state == L2CAP_STATE_WILL_SEND_CREATE_CONNECTION)) {
1858         log_info("connection complete con_handle %04x - for channel %p cid 0x%04x", (int) con_handle, channel, channel->local_cid);
1859         // success, start l2cap handshake
1860         channel->con_handle = con_handle;
1861         // check remote SSP feature first
1862         channel->state = L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES;
1863     }
1864 }
1865 
1866 static void l2cap_ready_to_connect(l2cap_channel_t * channel){
1867 
1868 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1869     // assumption: outgoing connection
1870     hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
1871     if (connection->l2cap_state.information_state == L2CAP_INFORMATION_STATE_IDLE){
1872         connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
1873         channel->state = L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES;
1874         return;
1875     }
1876 #endif
1877 
1878     // fine, go ahead
1879     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
1880 }
1881 
1882 static void l2cap_handle_remote_supported_features_received(l2cap_channel_t * channel){
1883     if (channel->state != L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES) return;
1884 
1885     // we have been waiting for remote supported features, if both support SSP,
1886     log_info("l2cap received remote supported features, sec_level_0_allowed for psm %u = %u", channel->psm, l2cap_security_level_0_allowed_for_PSM(channel->psm));
1887     if (gap_ssp_supported_on_both_sides(channel->con_handle) && !l2cap_security_level_0_allowed_for_PSM(channel->psm)){
1888         // request security level 2
1889         channel->state = L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE;
1890         channel->required_security_level = LEVEL_2;
1891         gap_request_security_level(channel->con_handle, LEVEL_2);
1892         return;
1893     }
1894 
1895     l2cap_ready_to_connect(channel);
1896 }
1897 #endif
1898 
1899 #ifdef L2CAP_USES_CHANNELS
1900 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,
1901     uint16_t psm, uint16_t local_mtu, gap_security_level_t security_level){
1902 
1903     l2cap_channel_t * channel = btstack_memory_l2cap_channel_get();
1904     if (!channel) {
1905         return NULL;
1906     }
1907 
1908     // fill in
1909     channel->packet_handler = packet_handler;
1910     channel->channel_type   = channel_type;
1911     bd_addr_copy(channel->address, address);
1912     channel->address_type = address_type;
1913     channel->psm = psm;
1914     channel->local_mtu  = local_mtu;
1915     channel->remote_mtu = L2CAP_DEFAULT_MTU;
1916     channel->required_security_level = security_level;
1917 
1918     //
1919     channel->local_cid = l2cap_next_local_cid();
1920     channel->con_handle = HCI_CON_HANDLE_INVALID;
1921 
1922     // set initial state
1923     channel->state = L2CAP_STATE_WILL_SEND_CREATE_CONNECTION;
1924     channel->state_var = L2CAP_CHANNEL_STATE_VAR_NONE;
1925     channel->remote_sig_id = L2CAP_SIG_ID_INVALID;
1926     channel->local_sig_id = L2CAP_SIG_ID_INVALID;
1927 
1928     log_info("create channel %p, local_cid 0x%04x", channel, channel->local_cid);
1929 
1930     return channel;
1931 }
1932 
1933 static void l2cap_free_channel_entry(l2cap_channel_t * channel){
1934     log_info("free channel %p, local_cid 0x%04x", channel, channel->local_cid);
1935     // assert all timers are stopped
1936     l2cap_stop_rtx(channel);
1937 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1938     l2cap_ertm_stop_retransmission_timer(channel);
1939     l2cap_ertm_stop_monitor_timer(channel);
1940 #endif
1941     // free  memory
1942     btstack_memory_l2cap_channel_free(channel);
1943 }
1944 #endif
1945 
1946 #ifdef ENABLE_CLASSIC
1947 
1948 /**
1949  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
1950  * @param packet_handler
1951  * @param address
1952  * @param psm
1953  * @param mtu
1954  * @param local_cid
1955  */
1956 
1957 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){
1958     // limit MTU to the size of our outtgoing HCI buffer
1959     uint16_t local_mtu = btstack_min(mtu, l2cap_max_mtu());
1960 
1961     log_info("L2CAP_CREATE_CHANNEL addr %s psm 0x%x mtu %u -> local mtu %u", bd_addr_to_str(address), psm, mtu, local_mtu);
1962 
1963     l2cap_channel_t * channel = l2cap_create_channel_entry(channel_packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, address, BD_ADDR_TYPE_ACL, psm, local_mtu, LEVEL_0);
1964     if (!channel) {
1965         return BTSTACK_MEMORY_ALLOC_FAILED;
1966     }
1967 
1968 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
1969     channel->mode = L2CAP_CHANNEL_MODE_BASIC;
1970 #endif
1971 
1972     // add to connections list
1973     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
1974 
1975     // store local_cid
1976     if (out_local_cid){
1977        *out_local_cid = channel->local_cid;
1978     }
1979 
1980     // check if hci connection is already usable
1981     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(address, BD_ADDR_TYPE_ACL);
1982     if (conn && conn->con_handle != HCI_CON_HANDLE_INVALID){
1983         log_info("l2cap_create_channel, hci connection 0x%04x already exists", conn->con_handle);
1984         l2cap_handle_connection_complete(conn->con_handle, channel);
1985         // check if remote supported fearures are already received
1986         if (conn->bonding_flags & BONDING_RECEIVED_REMOTE_FEATURES) {
1987             l2cap_handle_remote_supported_features_received(channel);
1988         }
1989     }
1990 
1991     l2cap_run();
1992 
1993     return ERROR_CODE_SUCCESS;
1994 }
1995 
1996 void l2cap_disconnect(uint16_t local_cid, uint8_t reason){
1997     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
1998     // find channel for local_cid
1999     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2000     if (channel) {
2001         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2002     }
2003     // process
2004     l2cap_run();
2005 }
2006 
2007 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
2008     // mark all channels before emitting open events as these could trigger new connetion requests to the same device
2009     btstack_linked_list_iterator_t it;
2010     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2011     while (btstack_linked_list_iterator_has_next(&it)){
2012         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2013         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2014         if (bd_addr_cmp( channel->address, address) != 0) continue;
2015         // channel for this address found
2016         switch (channel->state){
2017             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2018             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2019                 channel->state = L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD;
2020                 break;
2021             default:
2022                 break;
2023         }
2024     }
2025     // emit and free marked entries. restart loop to deal with list changes
2026     int done = 0;
2027     while (!done) {
2028         done = 1;
2029         btstack_linked_list_iterator_init(&it, &l2cap_channels);
2030         while (btstack_linked_list_iterator_has_next(&it)){
2031             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2032             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2033             if (channel->state == L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD){
2034                 done = 0;
2035                 // failure, forward error code
2036                 l2cap_handle_channel_open_failed(channel, status);
2037                 // discard channel
2038                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2039                 l2cap_free_channel_entry(channel);
2040                 break;
2041             }
2042         }
2043     }
2044 
2045 }
2046 
2047 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
2048     btstack_linked_list_iterator_t it;
2049     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2050     while (btstack_linked_list_iterator_has_next(&it)){
2051         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2052         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2053         if ( ! bd_addr_cmp( channel->address, address) ){
2054             l2cap_handle_connection_complete(handle, channel);
2055         }
2056     }
2057     // process
2058     l2cap_run();
2059 }
2060 #endif
2061 
2062 static bool l2cap_channel_ready_to_send(l2cap_channel_t * channel){
2063     switch (channel->channel_type){
2064 #ifdef ENABLE_CLASSIC
2065         case L2CAP_CHANNEL_TYPE_CLASSIC:
2066 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2067             // send if we have more data and remote windows isn't full yet
2068             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2069                 if (channel->unacked_frames >= btstack_min(channel->num_stored_tx_frames, channel->remote_tx_window_size)) return false;
2070                 return hci_can_send_acl_classic_packet_now() != 0;
2071             }
2072 #endif
2073             if (!channel->waiting_for_can_send_now) return false;
2074             return (hci_can_send_acl_classic_packet_now() != 0);
2075         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2076             if (!channel->waiting_for_can_send_now) return false;
2077             return hci_can_send_acl_classic_packet_now() != 0;
2078 #endif
2079 #ifdef ENABLE_BLE
2080         case L2CAP_CHANNEL_TYPE_LE_FIXED:
2081             if (!channel->waiting_for_can_send_now) return false;
2082             return hci_can_send_acl_le_packet_now() != 0;
2083 #ifdef ENABLE_LE_DATA_CHANNELS
2084         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
2085             if (channel->send_sdu_buffer == NULL) return false;
2086             if (channel->credits_outgoing == 0) return false;
2087             return hci_can_send_acl_le_packet_now() != 0;
2088 #endif
2089 #endif
2090         default:
2091             return false;
2092     }
2093 }
2094 
2095 static void l2cap_channel_trigger_send(l2cap_channel_t * channel){
2096     switch (channel->channel_type){
2097 #ifdef ENABLE_CLASSIC
2098         case L2CAP_CHANNEL_TYPE_CLASSIC:
2099 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2100             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) {
2101                 l2cap_ertm_channel_send_information_frame(channel);
2102                 return;
2103             }
2104 #endif
2105             channel->waiting_for_can_send_now = 0;
2106             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2107             break;
2108         case L2CAP_CHANNEL_TYPE_CONNECTIONLESS:
2109             channel->waiting_for_can_send_now = 0;
2110             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2111             break;
2112 #endif
2113 #ifdef ENABLE_BLE
2114         case L2CAP_CHANNEL_TYPE_LE_FIXED:
2115             channel->waiting_for_can_send_now = 0;
2116             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
2117             break;
2118 #ifdef ENABLE_LE_DATA_CHANNELS
2119         case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
2120             l2cap_le_send_pdu(channel);
2121             break;
2122 #endif
2123 #endif
2124         default:
2125             break;
2126     }
2127 }
2128 
2129 static void l2cap_notify_channel_can_send(void){
2130     bool done = false;
2131     while (!done){
2132         done = true;
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             bool ready = l2cap_channel_ready_to_send(channel);
2138             if (!ready) continue;
2139 
2140             // requeue channel for fairness
2141             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2142             btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
2143 
2144             // trigger sending
2145             l2cap_channel_trigger_send(channel);
2146 
2147             // exit inner loop as we just broke the iterator, but try again
2148             done = false;
2149             break;
2150         }
2151     }
2152 }
2153 
2154 #ifdef L2CAP_USES_CHANNELS
2155 
2156 static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){
2157     // open cannot fail for for incoming connections
2158     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0;
2159 
2160     // check state
2161     switch (channel->state){
2162         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
2163         case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
2164         case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES:
2165         case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2166         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
2167         case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES:
2168         case L2CAP_STATE_WAIT_CONNECT_RSP:
2169         case L2CAP_STATE_CONFIG:
2170         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
2171         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
2172         case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE:
2173         case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD:
2174             return 1;
2175 
2176         case L2CAP_STATE_OPEN:
2177         case L2CAP_STATE_CLOSED:
2178         case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES:
2179         case L2CAP_STATE_WAIT_DISCONNECT:
2180         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY:
2181         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
2182         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
2183         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2184         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
2185         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
2186         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
2187         case L2CAP_STATE_INVALID:
2188         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2189             return 0;
2190         // no default here, to get a warning about new states
2191     }
2192     // still, the compiler insists on a return value
2193     return 0;
2194 }
2195 #endif
2196 
2197 #ifdef ENABLE_CLASSIC
2198 static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){
2199     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2200         l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2201     } else {
2202         l2cap_handle_channel_closed(channel);
2203     }
2204     l2cap_free_channel_entry(channel);
2205 }
2206 #endif
2207 
2208 #ifdef ENABLE_LE_DATA_CHANNELS
2209 static void l2cap_handle_hci_le_disconnect_event(l2cap_channel_t * channel){
2210     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2211         l2cap_emit_le_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2212     } else {
2213         l2cap_emit_le_channel_closed(channel);
2214     }
2215     l2cap_free_channel_entry(channel);
2216 }
2217 #endif
2218 
2219 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
2220 
2221     UNUSED(packet_type); // ok: registered with hci_event_callback_registration
2222     UNUSED(cid);         // ok: there is no channel
2223     UNUSED(size);        // ok: fixed format events read from HCI buffer
2224 
2225 #ifdef ENABLE_CLASSIC
2226     bd_addr_t address;
2227     int hci_con_used;
2228 #endif
2229 #ifdef L2CAP_USES_CHANNELS
2230     hci_con_handle_t handle;
2231     btstack_linked_list_iterator_t it;
2232 #endif
2233 
2234     switch(hci_event_packet_get_type(packet)){
2235 
2236         // Notify channel packet handler if they can send now
2237         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2238         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
2239         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
2240             l2cap_run();    // try sending signaling packets first
2241             l2cap_notify_channel_can_send();
2242             break;
2243 
2244         case HCI_EVENT_COMMAND_STATUS:
2245 #ifdef ENABLE_CLASSIC
2246             // check command status for create connection for errors
2247             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
2248                 // cache outgoing address and reset
2249                 (void)memcpy(address, l2cap_outgoing_classic_addr, 6);
2250                 memset(l2cap_outgoing_classic_addr, 0, 6);
2251                 // error => outgoing connection failed
2252                 uint8_t status = hci_event_command_status_get_status(packet);
2253                 if (status){
2254                     l2cap_handle_connection_failed_for_addr(address, status);
2255                 }
2256             }
2257 #endif
2258             l2cap_run();    // try sending signaling packets first
2259             break;
2260 
2261 #ifdef ENABLE_CLASSIC
2262         // handle connection complete events
2263         case HCI_EVENT_CONNECTION_COMPLETE:
2264             reverse_bd_addr(&packet[5], address);
2265             if (packet[2] == 0){
2266                 handle = little_endian_read_16(packet, 3);
2267                 l2cap_handle_connection_success_for_addr(address, handle);
2268             } else {
2269                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
2270             }
2271             break;
2272 
2273         // handle successful create connection cancel command
2274         case HCI_EVENT_COMMAND_COMPLETE:
2275             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
2276                 if (packet[5] == 0){
2277                     reverse_bd_addr(&packet[6], address);
2278                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
2279                     l2cap_handle_connection_failed_for_addr(address, 0x16);
2280                 }
2281             }
2282             l2cap_run();    // try sending signaling packets first
2283             break;
2284 #endif
2285 
2286 #ifdef L2CAP_USES_CHANNELS
2287         // handle disconnection complete events
2288         case HCI_EVENT_DISCONNECTION_COMPLETE:
2289             handle = little_endian_read_16(packet, 3);
2290             // send l2cap open failed or closed events for all channels on this handle and free them
2291             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2292             while (btstack_linked_list_iterator_has_next(&it)){
2293                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2294                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2295                 if (channel->con_handle != handle) continue;
2296                 btstack_linked_list_iterator_remove(&it);
2297                 switch(channel->channel_type){
2298 #ifdef ENABLE_CLASSIC
2299                     case L2CAP_CHANNEL_TYPE_CLASSIC:
2300                         l2cap_handle_hci_disconnect_event(channel);
2301                         break;
2302 #endif
2303 #ifdef ENABLE_LE_DATA_CHANNELS
2304                     case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
2305                         l2cap_handle_hci_le_disconnect_event(channel);
2306                         break;
2307 #endif
2308                     default:
2309                         break;
2310                 }
2311             }
2312             break;
2313 #endif
2314 
2315 
2316         // HCI Connection Timeouts
2317 #ifdef ENABLE_CLASSIC
2318         case L2CAP_EVENT_TIMEOUT_CHECK:
2319             handle = little_endian_read_16(packet, 2);
2320             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
2321             if (hci_authentication_active_for_handle(handle)) break;
2322             hci_con_used = 0;
2323             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2324             while (btstack_linked_list_iterator_has_next(&it)){
2325                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2326                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2327                 if (channel->con_handle != handle) continue;
2328                 hci_con_used = 1;
2329                 break;
2330             }
2331             if (hci_con_used) break;
2332             if (!hci_can_send_command_packet_now()) break;
2333             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
2334             break;
2335 
2336         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2337             handle = little_endian_read_16(packet, 3);
2338             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2339             while (btstack_linked_list_iterator_has_next(&it)){
2340                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2341                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2342                 if (channel->con_handle != handle) continue;
2343                 log_info("remote supported features, channel %p, cid %04x - state %u", channel, channel->local_cid, channel->state);
2344                 l2cap_handle_remote_supported_features_received(channel);
2345             }
2346             break;
2347 
2348         case GAP_EVENT_SECURITY_LEVEL:
2349             handle = little_endian_read_16(packet, 2);
2350             log_info("l2cap - security level update for handle 0x%04x", handle);
2351             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2352             while (btstack_linked_list_iterator_has_next(&it)){
2353                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2354                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2355                 if (channel->con_handle != handle) continue;
2356 
2357                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
2358                 gap_security_level_t required_level = channel->required_security_level;
2359 
2360                 log_info("channel %p, cid %04x - state %u: actual %u >= required %u?", channel, channel->local_cid, channel->state, actual_level, required_level);
2361 
2362                 switch (channel->state){
2363                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2364                         if (actual_level >= required_level){
2365 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2366                             // we need to know if ERTM is supported before sending a config response
2367                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
2368                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2369                             channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
2370 #else
2371                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2372                             l2cap_emit_incoming_connection(channel);
2373 #endif
2374                         } else {
2375                             channel->reason = 0x0003; // security block
2376                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2377                         }
2378                         break;
2379 
2380                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2381                         if (actual_level >= required_level){
2382                             l2cap_ready_to_connect(channel);
2383                         } else {
2384                             // disconnnect, authentication not good enough
2385                             hci_disconnect_security_block(handle);
2386                         }
2387                         break;
2388 
2389                     default:
2390                         break;
2391                 }
2392             }
2393             break;
2394 #endif
2395 
2396         default:
2397             break;
2398     }
2399 
2400     l2cap_run();
2401 }
2402 
2403 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t cid, uint16_t data){
2404     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused."
2405     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
2406         signaling_responses[signaling_responses_pending].handle = handle;
2407         signaling_responses[signaling_responses_pending].code = code;
2408         signaling_responses[signaling_responses_pending].sig_id = sig_id;
2409         signaling_responses[signaling_responses_pending].cid = cid;
2410         signaling_responses[signaling_responses_pending].data = data;
2411         signaling_responses_pending++;
2412         l2cap_run();
2413     }
2414 }
2415 
2416 #ifdef ENABLE_CLASSIC
2417 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
2418     channel->remote_sig_id = identifier;
2419     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
2420     l2cap_run();
2421 }
2422 
2423 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
2424 
2425     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
2426     l2cap_service_t *service = l2cap_get_service(psm);
2427     if (!service) {
2428         // 0x0002 PSM not supported
2429         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2430         return;
2431     }
2432 
2433     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
2434     if (!hci_connection) {
2435         //
2436         log_error("no hci_connection for handle %u", handle);
2437         return;
2438     }
2439 
2440     // alloc structure
2441     // log_info("l2cap_handle_connection_request register channel");
2442     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, hci_connection->address, BD_ADDR_TYPE_ACL,
2443     psm, service->mtu, service->required_security_level);
2444     if (!channel){
2445         // 0x0004 No resources available
2446         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2447         return;
2448     }
2449 
2450     channel->con_handle = handle;
2451     channel->remote_cid = source_cid;
2452     channel->remote_sig_id = sig_id;
2453 
2454     // limit local mtu to max acl packet length - l2cap header
2455     if (channel->local_mtu > l2cap_max_mtu()) {
2456         channel->local_mtu = l2cap_max_mtu();
2457     }
2458 
2459     // set initial state
2460     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
2461     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
2462 
2463     // add to connections list
2464     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
2465 
2466     // assert security requirements
2467     gap_request_security_level(handle, channel->required_security_level);
2468 }
2469 
2470 void l2cap_accept_connection(uint16_t local_cid){
2471     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
2472     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2473     if (!channel) {
2474         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
2475         return;
2476     }
2477 
2478 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2479     // configure L2CAP Basic mode
2480     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
2481 #endif
2482 
2483     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
2484 
2485     // process
2486     l2cap_run();
2487 }
2488 
2489 void l2cap_decline_connection(uint16_t local_cid){
2490     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
2491     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
2492     if (!channel) {
2493         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
2494         return;
2495     }
2496     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2497     channel->reason = 0x04; // no resources available
2498     l2cap_run();
2499 }
2500 
2501 // @pre command len is valid, see check in l2cap_signaling_handler_channel
2502 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
2503 
2504 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2505     uint8_t use_fcs = 1;
2506 #endif
2507 
2508     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2509 
2510     uint16_t flags = little_endian_read_16(command, 6);
2511     if (flags & 1) {
2512         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
2513     }
2514 
2515     // accept the other's configuration options
2516     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2517     uint16_t pos     = 8;
2518     while (pos < end_pos){
2519         uint8_t option_hint = command[pos] >> 7;
2520         uint8_t option_type = command[pos] & 0x7f;
2521         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
2522         pos++;
2523         uint8_t length = command[pos++];
2524         // MTU { type(8): 1, len(8):2, MTU(16) }
2525         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) && (length == 2)){
2526             channel->remote_mtu = little_endian_read_16(command, pos);
2527             log_info("Remote MTU %u", channel->remote_mtu);
2528             if (channel->remote_mtu > l2cap_max_mtu()){
2529                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
2530                 channel->remote_mtu = l2cap_max_mtu();
2531             }
2532             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
2533         }
2534         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
2535         if ((option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT) && (length == 2)){
2536             channel->flush_timeout = little_endian_read_16(command, pos);
2537             log_info("Flush timeout: %u ms", channel->flush_timeout);
2538         }
2539 
2540 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2541         // Retransmission and Flow Control Option
2542         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2543             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
2544             switch(channel->mode){
2545                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2546                     // Store remote config
2547                     channel->remote_tx_window_size = command[pos+1];
2548                     channel->remote_max_transmit   = command[pos+2];
2549                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
2550                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
2551                     channel->remote_mps = little_endian_read_16(command, pos + 7);
2552                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
2553                         channel->remote_tx_window_size,
2554                         channel->remote_max_transmit,
2555                         channel->remote_retransmission_timeout_ms,
2556                         channel->remote_monitor_timeout_ms,
2557                         channel->remote_mps);
2558                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
2559                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
2560                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2561                     } else {
2562                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2563                     }
2564                     break;
2565                 case L2CAP_CHANNEL_MODE_BASIC:
2566                     switch (mode){
2567                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2568                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
2569                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
2570                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2571                             }
2572                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
2573                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
2574                             break;
2575                         default: // case L2CAP_CHANNEL_MODE_BASIC:
2576                             // TODO store and evaluate configuration
2577                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM);
2578                             break;
2579                     }
2580                     break;
2581                 default:
2582                     break;
2583             }
2584         }
2585         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
2586             use_fcs = command[pos];
2587         }
2588 #endif
2589         // check for unknown options
2590         if ((option_hint == 0) && ((option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT) || (option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE))){
2591             log_info("l2cap cid %u, unknown options", channel->local_cid);
2592             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
2593         }
2594         pos += length;
2595     }
2596 
2597 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2598         // "FCS" has precedence over "No FCS"
2599         uint8_t update = channel->fcs_option || use_fcs;
2600         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
2601         channel->fcs_option = update;
2602         // If ERTM mandatory, but remote didn't send Retransmission and Flowcontrol options -> disconnect
2603         if (((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_ERTM) == 0) & (channel->ertm_mandatory)){
2604             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2605         }
2606 #endif
2607 }
2608 
2609 // @pre command len is valid, see check in l2cap_signaling_handler_channel
2610 static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
2611     log_info("l2cap_signaling_handle_configure_response");
2612 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2613     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2614     uint16_t pos     = 10;
2615     while (pos < end_pos){
2616         uint8_t option_hint = command[pos] >> 7;
2617         uint8_t option_type = command[pos] & 0x7f;
2618         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
2619         pos++;
2620         uint8_t length = command[pos++];
2621 
2622         // Retransmission and Flow Control Option
2623         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2624             switch (channel->mode){
2625                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2626                     if (channel->ertm_mandatory){
2627                         // ??
2628                     } else {
2629                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
2630                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2631                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
2632                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2633                         }
2634                     }
2635                     break;
2636                 case L2CAP_CHANNEL_MODE_BASIC:
2637                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2638                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
2639                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2640                     }
2641                     break;
2642                 default:
2643                     break;
2644             }
2645         }
2646 
2647         // check for unknown options
2648         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
2649             log_info("l2cap cid %u, unknown options", channel->local_cid);
2650             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
2651         }
2652 
2653         pos += length;
2654     }
2655 #else
2656     UNUSED(channel);  // ok: no code
2657     UNUSED(result);   // ok: no code
2658     UNUSED(command);  // ok: no code
2659 #endif
2660 }
2661 
2662 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
2663     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
2664     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
2665     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
2666     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
2667     if (channel->state == L2CAP_STATE_OPEN) return 0;
2668     return 1;
2669 }
2670 
2671 
2672 // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
2673 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
2674 
2675     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2676     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2677     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2678     uint16_t result = 0;
2679 
2680     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
2681 
2682     // handle DISCONNECT REQUESTS seperately
2683     if (code == DISCONNECTION_REQUEST){
2684         switch (channel->state){
2685             case L2CAP_STATE_CONFIG:
2686             case L2CAP_STATE_OPEN:
2687             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2688             case L2CAP_STATE_WAIT_DISCONNECT:
2689                 l2cap_handle_disconnect_request(channel, identifier);
2690                 break;
2691 
2692             default:
2693                 // ignore in other states
2694                 break;
2695         }
2696         return;
2697     }
2698 
2699     // @STATEMACHINE(l2cap)
2700     switch (channel->state) {
2701 
2702         case L2CAP_STATE_WAIT_CONNECT_RSP:
2703             switch (code){
2704                 case CONNECTION_RESPONSE:
2705                     if (cmd_len < 8){
2706                         // command imcomplete
2707                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2708                         break;
2709                     }
2710                     l2cap_stop_rtx(channel);
2711                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2712                     switch (result) {
2713                         case 0:
2714                             // successful connection
2715                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2716                             channel->state = L2CAP_STATE_CONFIG;
2717                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2718                             break;
2719                         case 1:
2720                             // connection pending. get some coffee, but start the ERTX
2721                             l2cap_start_ertx(channel);
2722                             break;
2723                         default:
2724                             // channel closed
2725                             channel->state = L2CAP_STATE_CLOSED;
2726                             // map l2cap connection response result to BTstack status enumeration
2727                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
2728 
2729                             // drop link key if security block
2730                             if ((L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result) == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
2731                                 gap_drop_link_key_for_bd_addr(channel->address);
2732                             }
2733 
2734                             // discard channel
2735                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2736                             l2cap_free_channel_entry(channel);
2737                             break;
2738                     }
2739                     break;
2740 
2741                 default:
2742                     //@TODO: implement other signaling packets
2743                     break;
2744             }
2745             break;
2746 
2747         case L2CAP_STATE_CONFIG:
2748             switch (code) {
2749                 case CONFIGURE_REQUEST:
2750                     if (cmd_len < 4){
2751                         // command incomplete
2752                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2753                         break;
2754                     }
2755                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
2756                     l2cap_signaling_handle_configure_request(channel, command);
2757                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
2758                         // only done if continuation not set
2759                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
2760                     }
2761                     break;
2762                 case CONFIGURE_RESPONSE:
2763                     if (cmd_len < 6){
2764                         // command incomplete
2765                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2766                         break;
2767                     }
2768                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2769                     l2cap_stop_rtx(channel);
2770                     l2cap_signaling_handle_configure_response(channel, result, command);
2771                     switch (result){
2772                         case 0: // success
2773                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
2774                             break;
2775                         case 4: // pending
2776                             l2cap_start_ertx(channel);
2777                             break;
2778                         default:
2779 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2780                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
2781                                 // remote does not offer ertm but it's required
2782                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2783                                 break;
2784                             }
2785 #endif
2786                             // retry on negative result
2787                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2788                             break;
2789                     }
2790                     break;
2791                 default:
2792                     break;
2793             }
2794             if (l2cap_channel_ready_for_open(channel)){
2795 
2796 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2797                 // assert that packet can be stored in fragment buffers in ertm
2798                 if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
2799                     uint16_t effective_mps = btstack_min(channel->remote_mps, channel->local_mps);
2800                     uint16_t usable_mtu = channel->num_tx_buffers == 1 ? effective_mps : channel->num_tx_buffers * effective_mps - 2;
2801                     if (usable_mtu < channel->remote_mtu){
2802                         log_info("Remote MTU %u > max storable ERTM packet, only using MTU = %u", channel->remote_mtu, usable_mtu);
2803                         channel->remote_mtu = usable_mtu;
2804                     }
2805                 }
2806 #endif
2807                 // for open:
2808                 channel->state = L2CAP_STATE_OPEN;
2809                 l2cap_emit_channel_opened(channel, 0);
2810             }
2811             break;
2812 
2813         case L2CAP_STATE_WAIT_DISCONNECT:
2814             switch (code) {
2815                 case DISCONNECTION_RESPONSE:
2816                     l2cap_finialize_channel_close(channel);
2817                     break;
2818                 default:
2819                     //@TODO: implement other signaling packets
2820                     break;
2821             }
2822             break;
2823 
2824         case L2CAP_STATE_CLOSED:
2825             // @TODO handle incoming requests
2826             break;
2827 
2828         case L2CAP_STATE_OPEN:
2829             //@TODO: implement other signaling packets, e.g. re-configure
2830             break;
2831         default:
2832             break;
2833     }
2834     // log_info("new state %u", channel->state);
2835 }
2836 
2837 
2838 // @pre command len is valid, see check in l2cap_acl_classic_handler
2839 static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
2840 
2841     btstack_linked_list_iterator_t it;
2842 
2843     // get code, signalind identifier and command len
2844     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2845     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2846     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2847 
2848     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
2849     if ((code < 1) || (code == ECHO_RESPONSE) || (code > INFORMATION_RESPONSE)){
2850         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2851         return;
2852     }
2853 
2854     // general commands without an assigned channel
2855     switch(code) {
2856 
2857         case CONNECTION_REQUEST:
2858             if (cmd_len == 4){
2859                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2860                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
2861                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
2862             } else {
2863                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2864             }
2865             return;
2866 
2867         case ECHO_REQUEST:
2868             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
2869             return;
2870 
2871         case INFORMATION_REQUEST:
2872             if (cmd_len == 2) {
2873                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2874                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
2875             } else {
2876                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2877             }
2878             return;
2879 
2880 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2881         case INFORMATION_RESPONSE: {
2882             hci_connection_t * connection = hci_connection_for_handle(handle);
2883             if (!connection) return;
2884             if (connection->l2cap_state.information_state != L2CAP_INFORMATION_STATE_W4_EXTENDED_FEATURE_RESPONSE) return;
2885 
2886             // get extended features from response if valid
2887             connection->l2cap_state.extended_feature_mask = 0;
2888             if (cmd_len >= 6) {
2889                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2890                 uint16_t result    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
2891                 if (result == 0 && info_type == L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) {
2892                     connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2893                 }
2894             }
2895             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
2896             log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
2897 
2898             // trigger connection request
2899             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2900             while (btstack_linked_list_iterator_has_next(&it)){
2901                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2902                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2903                 if (channel->con_handle != handle) continue;
2904 
2905                 // incoming connection: ask user for channel configuration, esp. if ertm will be mandatory
2906                 if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
2907                     channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2908                     l2cap_emit_incoming_connection(channel);
2909                     continue;
2910                 }
2911 
2912                 // outgoing connection
2913                 if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
2914 
2915                     // if ERTM was requested, but is not listed in extended feature mask:
2916                     if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2917 
2918                         if (channel->ertm_mandatory){
2919                             // bail if ERTM is mandatory
2920                             channel->state = L2CAP_STATE_CLOSED;
2921                             // map l2cap connection response result to BTstack status enumeration
2922                             l2cap_handle_channel_open_failed(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
2923                             // discard channel
2924                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2925                             l2cap_free_channel_entry(channel);
2926                             continue;
2927 
2928                         } else {
2929                             // fallback to Basic mode
2930                             l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_ERTM_BUFFER_RELEASED);
2931                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2932                         }
2933                     }
2934 
2935                     // respond to connection request
2936                     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
2937                     continue;
2938                 }
2939             }
2940             return;
2941         }
2942 #endif
2943 
2944         default:
2945             break;
2946     }
2947 
2948     // Get potential destination CID
2949     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2950 
2951     // Find channel for this sig_id and connection handle
2952     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2953     while (btstack_linked_list_iterator_has_next(&it)){
2954         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2955         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2956         if (channel->con_handle != handle) continue;
2957         if (code & 1) {
2958             // match odd commands (responses) by previous signaling identifier
2959             if (channel->local_sig_id == sig_id) {
2960                 l2cap_signaling_handler_channel(channel, command);
2961                 break;
2962             }
2963         } else {
2964             // match even commands (requests) by local channel id
2965             if (channel->local_cid == dest_cid) {
2966                 l2cap_signaling_handler_channel(channel, command);
2967                 break;
2968             }
2969         }
2970     }
2971 }
2972 #endif
2973 
2974 #ifdef ENABLE_BLE
2975 
2976 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
2977     uint8_t event[6];
2978     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
2979     event[1] = 4;
2980     little_endian_store_16(event, 2, con_handle);
2981     little_endian_store_16(event, 4, result);
2982     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2983     if (!l2cap_event_packet_handler) return;
2984     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
2985 }
2986 
2987 // @returns valid
2988 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
2989     hci_connection_t * connection;
2990     uint16_t result;
2991     uint8_t  event[12];
2992 
2993 #ifdef ENABLE_LE_DATA_CHANNELS
2994     btstack_linked_list_iterator_t it;
2995     l2cap_channel_t * channel;
2996     uint16_t local_cid;
2997     uint16_t le_psm;
2998     uint16_t new_credits;
2999     uint16_t credits_before;
3000     l2cap_service_t * service;
3001     uint16_t source_cid;
3002 #endif
3003 
3004     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
3005     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3006     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
3007 
3008     switch (code){
3009 
3010         case CONNECTION_PARAMETER_UPDATE_REQUEST:
3011             // check size
3012             if (len < 8) return 0;
3013             connection = hci_connection_for_handle(handle);
3014             if (connection){
3015                 if (connection->role != HCI_ROLE_MASTER){
3016                     // reject command without notifying upper layer when not in master role
3017                     return 0;
3018                 }
3019                 le_connection_parameter_range_t existing_range;
3020                 gap_get_connection_parameter_range(&existing_range);
3021                 uint16_t le_conn_interval_min   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
3022                 uint16_t le_conn_interval_max   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
3023                 uint16_t le_conn_latency        = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
3024                 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
3025 
3026                 int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
3027                 if (update_parameter){
3028                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
3029                     connection->le_conn_interval_min = le_conn_interval_min;
3030                     connection->le_conn_interval_max = le_conn_interval_max;
3031                     connection->le_conn_latency = le_conn_latency;
3032                     connection->le_supervision_timeout = le_supervision_timeout;
3033                 } else {
3034                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
3035                 }
3036                 connection->le_con_param_update_identifier = sig_id;
3037             }
3038 
3039             if (!l2cap_event_packet_handler) break;
3040 
3041             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
3042             event[1] = 8;
3043             little_endian_store_16(event, 2, handle);
3044             (void)memcpy(&event[4], &command[4], 8);
3045             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3046             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
3047             break;
3048 
3049         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
3050             // check size
3051             if (len < 2) return 0;
3052             result = little_endian_read_16(command, 4);
3053             l2cap_emit_connection_parameter_update_response(handle, result);
3054             break;
3055 
3056 #ifdef ENABLE_LE_DATA_CHANNELS
3057 
3058         case COMMAND_REJECT:
3059             // Find channel for this sig_id and connection handle
3060             channel = NULL;
3061             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3062             while (btstack_linked_list_iterator_has_next(&it)){
3063                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3064                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
3065                 if (a_channel->con_handle   != handle) continue;
3066                 if (a_channel->local_sig_id != sig_id) continue;
3067                 channel = a_channel;
3068                 break;
3069             }
3070             if (!channel) break;
3071 
3072             // if received while waiting for le connection response, assume legacy device
3073             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
3074                 channel->state = L2CAP_STATE_CLOSED;
3075                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
3076                 l2cap_emit_le_channel_opened(channel, 0x0002);
3077 
3078                 // discard channel
3079                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3080                 l2cap_free_channel_entry(channel);
3081                 break;
3082             }
3083             break;
3084 
3085         case LE_CREDIT_BASED_CONNECTION_REQUEST:
3086             // check size
3087             if (len < 10) return 0;
3088 
3089             // get hci connection, bail if not found (must not happen)
3090             connection = hci_connection_for_handle(handle);
3091             if (!connection) return 0;
3092 
3093             // check if service registered
3094             le_psm  = little_endian_read_16(command, 4);
3095             service = l2cap_le_get_service(le_psm);
3096             source_cid = little_endian_read_16(command, 6);
3097 
3098             if (service){
3099                 if (source_cid < 0x40){
3100                     // 0x0009 Connection refused - Invalid Source CID
3101                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
3102                     return 1;
3103                 }
3104 
3105                 // go through list of channels for this ACL connection and check if we get a match
3106                 btstack_linked_list_iterator_init(&it, &l2cap_channels);
3107                 while (btstack_linked_list_iterator_has_next(&it)){
3108                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3109                     if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
3110                     if (a_channel->con_handle != handle) continue;
3111                     if (a_channel->remote_cid != source_cid) continue;
3112                     // 0x000a Connection refused - Source CID already allocated
3113                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
3114                     return 1;
3115                 }
3116 
3117                 // security: check encryption
3118                 if (service->required_security_level >= LEVEL_2){
3119                     if (gap_encryption_key_size(handle) == 0){
3120                         // 0x0008 Connection refused - insufficient encryption
3121                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
3122                         return 1;
3123                     }
3124                     // anything less than 16 byte key size is insufficient
3125                     if (gap_encryption_key_size(handle) < 16){
3126                         // 0x0007 Connection refused – insufficient encryption key size
3127                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
3128                         return 1;
3129                     }
3130                 }
3131 
3132                 // security: check authencation
3133                 if (service->required_security_level >= LEVEL_3){
3134                     if (!gap_authenticated(handle)){
3135                         // 0x0005 Connection refused – insufficient authentication
3136                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
3137                         return 1;
3138                     }
3139                 }
3140 
3141                 // security: check authorization
3142                 if (service->required_security_level >= LEVEL_4){
3143                     if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
3144                         // 0x0006 Connection refused – insufficient authorization
3145                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
3146                         return 1;
3147                     }
3148                 }
3149 
3150                 // allocate channel
3151                 channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL, connection->address,
3152                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
3153                 if (!channel){
3154                     // 0x0004 Connection refused – no resources available
3155                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
3156                     return 1;
3157                 }
3158 
3159                 channel->con_handle = handle;
3160                 channel->remote_cid = source_cid;
3161                 channel->remote_sig_id = sig_id;
3162                 channel->remote_mtu = little_endian_read_16(command, 8);
3163                 channel->remote_mps = little_endian_read_16(command, 10);
3164                 channel->credits_outgoing = little_endian_read_16(command, 12);
3165 
3166                 // set initial state
3167                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
3168                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
3169 
3170                 // add to connections list
3171                 btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
3172 
3173                 // post connection request event
3174                 l2cap_emit_le_incoming_connection(channel);
3175 
3176             } else {
3177                 // Connection refused – LE_PSM not supported
3178                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
3179             }
3180             break;
3181 
3182         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
3183             // check size
3184             if (len < 10) return 0;
3185 
3186             // Find channel for this sig_id and connection handle
3187             channel = NULL;
3188             btstack_linked_list_iterator_init(&it, &l2cap_channels);
3189             while (btstack_linked_list_iterator_has_next(&it)){
3190                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
3191                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
3192                 if (a_channel->con_handle   != handle) continue;
3193                 if (a_channel->local_sig_id != sig_id) continue;
3194                 channel = a_channel;
3195                 break;
3196             }
3197             if (!channel) break;
3198 
3199             // cid + 0
3200             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
3201             if (result){
3202                 channel->state = L2CAP_STATE_CLOSED;
3203                 // map l2cap connection response result to BTstack status enumeration
3204                 l2cap_emit_le_channel_opened(channel, result);
3205 
3206                 // discard channel
3207                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3208                 l2cap_free_channel_entry(channel);
3209                 break;
3210             }
3211 
3212             // success
3213             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3214             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3215             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
3216             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
3217             channel->state = L2CAP_STATE_OPEN;
3218             l2cap_emit_le_channel_opened(channel, result);
3219             break;
3220 
3221         case LE_FLOW_CONTROL_CREDIT:
3222             // check size
3223             if (len < 4) return 0;
3224 
3225             // find channel
3226             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3227             channel = l2cap_get_channel_for_local_cid(local_cid);
3228             if (!channel) {
3229                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
3230                 break;
3231             }
3232             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3233             credits_before = channel->credits_outgoing;
3234             channel->credits_outgoing += new_credits;
3235             // check for credit overrun
3236             if (credits_before > channel->credits_outgoing){
3237                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
3238                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3239                 break;
3240             }
3241             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
3242             break;
3243 
3244         case DISCONNECTION_REQUEST:
3245 
3246             // check size
3247             if (len < 4) return 0;
3248 
3249             // find channel
3250             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3251             channel = l2cap_get_channel_for_local_cid(local_cid);
3252             if (!channel) {
3253                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
3254                 break;
3255             }
3256             channel->remote_sig_id = sig_id;
3257             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
3258             break;
3259 
3260 #endif
3261 
3262         case DISCONNECTION_RESPONSE:
3263             break;
3264 
3265         default:
3266             // command unknown -> reject command
3267             return 0;
3268     }
3269     return 1;
3270 }
3271 #endif
3272 
3273 static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3274 #ifdef ENABLE_CLASSIC
3275     l2cap_channel_t * l2cap_channel;
3276     l2cap_fixed_channel_t * l2cap_fixed_channel;
3277 
3278     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3279     switch (channel_id) {
3280 
3281         case L2CAP_CID_SIGNALING: {
3282             uint32_t command_offset = 8;
3283             while ((command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET) < size) {
3284                 // assert signaling command is fully inside packet
3285                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3286                 uint32_t next_command_offset = command_offset + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
3287                 if (next_command_offset > size){
3288                     log_error("l2cap signaling command len invalid -> drop");
3289                     break;
3290                 }
3291                 // handle signaling command
3292                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
3293                 // go to next command
3294                 command_offset = next_command_offset;
3295             }
3296             break;
3297         }
3298         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
3299             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL);
3300             if (!l2cap_fixed_channel) break;
3301             if (!l2cap_fixed_channel->packet_handler) break;
3302             (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3303             break;
3304 
3305         default:
3306             // Find channel for this channel_id and connection handle
3307             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
3308             if (l2cap_channel) {
3309 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3310                 if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3311 
3312                     int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
3313 
3314                     // assert control + FCS fields are inside
3315                     if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) break;
3316 
3317                     if (l2cap_channel->fcs_option){
3318                         // verify FCS (required if one side requested it)
3319                         uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
3320                         uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
3321 
3322 #ifdef L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL
3323                         // simulate fcs error
3324                         static int counter = 0;
3325                         if (++counter == L2CAP_ERTM_SIMULATE_FCS_ERROR_INTERVAL) {
3326                             log_info("Simulate fcs error");
3327                             fcs_calculated++;
3328                             counter = 0;
3329                         }
3330 #endif
3331 
3332                         if (fcs_calculated == fcs_packet){
3333                             log_info("Packet FCS 0x%04x verified", fcs_packet);
3334                         } else {
3335                             log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
3336                             // ERTM State Machine in Bluetooth Spec does not handle 'I-Frame with invalid FCS'
3337                             break;
3338                         }
3339                     }
3340 
3341                     // switch on packet type
3342                     uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3343                     uint8_t  req_seq = (control >> 8) & 0x3f;
3344                     int final = (control >> 7) & 0x01;
3345                     if (control & 1){
3346                         // S-Frame
3347                         int poll  = (control >> 4) & 0x01;
3348                         l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
3349                         log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
3350                         l2cap_ertm_tx_packet_state_t * tx_state;
3351                         switch (s){
3352                             case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
3353                                 log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
3354                                 l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3355                                 if (poll && final){
3356                                     // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
3357                                     log_error("P=F=1 in S-Frame");
3358                                     break;
3359                                 }
3360                                 if (poll){
3361                                     // check if we did request selective retransmission before <==> we have stored SDU segments
3362                                     int i;
3363                                     int num_stored_out_of_order_packets = 0;
3364                                     for (i=0;i<l2cap_channel->num_rx_buffers;i++){
3365                                         int index = l2cap_channel->rx_store_index + i;
3366                                         if (index >= l2cap_channel->num_rx_buffers){
3367                                             index -= l2cap_channel->num_rx_buffers;
3368                                         }
3369                                         l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3370                                         if (!rx_state->valid) continue;
3371                                         num_stored_out_of_order_packets++;
3372                                     }
3373                                     if (num_stored_out_of_order_packets){
3374                                         l2cap_channel->send_supervisor_frame_selective_reject = 1;
3375                                     } else {
3376                                         l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
3377                                     }
3378                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
3379                                 }
3380                                 if (final){
3381                                     // Stop-MonitorTimer
3382                                     l2cap_ertm_stop_monitor_timer(l2cap_channel);
3383                                     // If UnackedFrames > 0 then Start-RetransTimer
3384                                     if (l2cap_channel->unacked_frames){
3385                                         l2cap_ertm_start_retransmission_timer(l2cap_channel);
3386                                     }
3387                                     // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3388                                     l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
3389                                 }
3390                                 break;
3391                             case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
3392                                 log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
3393                                 l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3394                                 // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
3395                                 l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
3396                                 break;
3397                             case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
3398                                 log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
3399                                 break;
3400                             case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
3401                                 log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
3402                                 if (poll){
3403                                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3404                                 }
3405                                 // find requested i-frame
3406                                 tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
3407                                 if (tx_state){
3408                                     log_info("Retransmission for tx_seq %u requested", req_seq);
3409                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
3410                                     tx_state->retransmission_requested = 1;
3411                                     l2cap_channel->srej_active = 1;
3412                                 }
3413                                 break;
3414                             default:
3415                                 break;
3416                         }
3417                         break;
3418                     } else {
3419                         // I-Frame
3420                         // get control
3421                         l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
3422                         uint8_t tx_seq = (control >> 1) & 0x3f;
3423                         log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
3424                         log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
3425                         log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
3426                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3427                         if (final){
3428                             // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3429                             l2cap_ertm_retransmit_unacknowleded_frames(l2cap_channel);
3430                         }
3431 
3432                         // get SDU
3433                         const uint8_t * payload_data = &packet[COMPLETE_L2CAP_HEADER+2];
3434                         uint16_t        payload_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
3435 
3436                         // assert SDU size is smaller or equal to our buffers
3437                         uint16_t max_payload_size = 0;
3438                         switch (sar){
3439                             case L2CAP_SEGMENTATION_AND_REASSEMBLY_UNSEGMENTED_L2CAP_SDU:
3440                             case L2CAP_SEGMENTATION_AND_REASSEMBLY_START_OF_L2CAP_SDU:
3441                                 // SDU Length + MPS
3442                                 max_payload_size = l2cap_channel->local_mps + 2;
3443                                 break;
3444                             case L2CAP_SEGMENTATION_AND_REASSEMBLY_CONTINUATION_OF_L2CAP_SDU:
3445                             case L2CAP_SEGMENTATION_AND_REASSEMBLY_END_OF_L2CAP_SDU:
3446                                 max_payload_size = l2cap_channel->local_mps;
3447                                 break;
3448                         }
3449                         if (payload_len > max_payload_size){
3450                             log_info("payload len %u > max payload %u -> drop packet", payload_len, max_payload_size);
3451                             break;
3452                         }
3453 
3454                         // check ordering
3455                         if (l2cap_channel->expected_tx_seq == tx_seq){
3456                             log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
3457                             l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3458                             l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3459 
3460                             // process SDU
3461                             l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, payload_data, payload_len);
3462 
3463                             // process stored segments
3464                             while (true){
3465                                 int index = l2cap_channel->rx_store_index;
3466                                 l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3467                                 if (!rx_state->valid) break;
3468 
3469                                 log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
3470                                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3471                                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3472 
3473                                 rx_state->valid = 0;
3474                                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
3475 
3476                                 // update rx store index
3477                                 index++;
3478                                 if (index >= l2cap_channel->num_rx_buffers){
3479                                     index = 0;
3480                                 }
3481                                 l2cap_channel->rx_store_index = index;
3482                             }
3483 
3484                             //
3485                             l2cap_channel->send_supervisor_frame_receiver_ready = 1;
3486 
3487                         } else {
3488                             int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
3489                             if (delta < 2){
3490                                 // store segment
3491                                 l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, payload_data, payload_len);
3492 
3493                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
3494                                 l2cap_channel->send_supervisor_frame_selective_reject = 1;
3495                             } else {
3496                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
3497                                 l2cap_channel->send_supervisor_frame_reject = 1;
3498                             }
3499                         }
3500                     }
3501                     break;
3502                 }
3503 #endif
3504                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3505             }
3506             break;
3507     }
3508 #else
3509     UNUSED(handle); // ok: no code
3510     UNUSED(packet); // ok: no code
3511     UNUSED(size);   // ok: no code
3512 #endif
3513 }
3514 
3515 static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3516 #ifdef ENABLE_BLE
3517 
3518     l2cap_fixed_channel_t * l2cap_fixed_channel;
3519 
3520 #ifdef ENABLE_LE_DATA_CHANNELS
3521     l2cap_channel_t * l2cap_channel;
3522 #endif
3523     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3524     switch (channel_id) {
3525 
3526         case L2CAP_CID_SIGNALING_LE: {
3527             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
3528             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
3529             if ((COMPLETE_L2CAP_HEADER + 4 + len) > size) break;
3530             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
3531             if (!valid){
3532                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3533             }
3534             break;
3535         }
3536 
3537         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
3538             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL);
3539             if (!l2cap_fixed_channel) break;
3540             if (!l2cap_fixed_channel->packet_handler) break;
3541             (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3542             break;
3543 
3544         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
3545             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
3546             if (!l2cap_fixed_channel) break;
3547             if (!l2cap_fixed_channel->packet_handler) break;
3548             (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3549             break;
3550 
3551         default:
3552 
3553 #ifdef ENABLE_LE_DATA_CHANNELS
3554             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
3555             if (l2cap_channel) {
3556                 // credit counting
3557                 if (l2cap_channel->credits_incoming == 0){
3558                     log_error("LE Data Channel packet received but no incoming credits");
3559                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3560                     break;
3561                 }
3562                 l2cap_channel->credits_incoming--;
3563 
3564                 // automatic credits
3565                 if ((l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK) && l2cap_channel->automatic_credits){
3566                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
3567                 }
3568 
3569                 // first fragment
3570                 uint16_t pos = 0;
3571                 if (!l2cap_channel->receive_sdu_len){
3572                     uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3573                     if(sdu_len > l2cap_channel->local_mtu) break;   // SDU would be larger than our buffer
3574                     l2cap_channel->receive_sdu_len = sdu_len;
3575                     l2cap_channel->receive_sdu_pos = 0;
3576                     pos  += 2;
3577                     size -= 2;
3578                 }
3579                 uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
3580                 uint16_t remaining_space = l2cap_channel->local_mtu - l2cap_channel->receive_sdu_pos;
3581                 if (fragment_size > remaining_space) break;         // SDU would cause buffer overrun
3582                 (void)memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos],
3583                              &packet[COMPLETE_L2CAP_HEADER + pos],
3584                              fragment_size);
3585                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
3586                 // done?
3587                 log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
3588                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
3589                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
3590                     l2cap_channel->receive_sdu_len = 0;
3591                 }
3592             } else {
3593                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
3594             }
3595 #endif
3596             break;
3597     }
3598 #else
3599     UNUSED(handle); // ok: no code
3600     UNUSED(packet); // ok: no code
3601     UNUSED(size);   // ok: no code
3602 #endif
3603 }
3604 
3605 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
3606     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
3607     UNUSED(channel);        // ok: there is no channel
3608 
3609     // Assert full L2CAP header present
3610     if (size < COMPLETE_L2CAP_HEADER) return;
3611 
3612     // Dispatch to Classic or LE handler (SCO packets are not dispatched to L2CAP)
3613     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
3614     hci_connection_t *conn = hci_connection_for_handle(handle);
3615     if (!conn) return;
3616     if (conn->address_type == BD_ADDR_TYPE_ACL){
3617         l2cap_acl_classic_handler(handle, packet, size);
3618     } else {
3619         l2cap_acl_le_handler(handle, packet, size);
3620     }
3621 
3622     l2cap_run();
3623 }
3624 
3625 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
3626 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
3627     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
3628     if (!channel) return;
3629     channel->packet_handler = the_packet_handler;
3630 }
3631 
3632 #ifdef ENABLE_CLASSIC
3633 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
3634 void l2cap_finialize_channel_close(l2cap_channel_t * channel){
3635     channel->state = L2CAP_STATE_CLOSED;
3636     l2cap_handle_channel_closed(channel);
3637     // discard channel
3638     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3639     l2cap_free_channel_entry(channel);
3640 }
3641 #endif
3642 
3643 #ifdef L2CAP_USES_CHANNELS
3644 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3645     btstack_linked_list_iterator_t it;
3646     btstack_linked_list_iterator_init(&it, services);
3647     while (btstack_linked_list_iterator_has_next(&it)){
3648         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
3649         if ( service->psm == psm){
3650             return service;
3651         };
3652     }
3653     return NULL;
3654 }
3655 #endif
3656 
3657 #ifdef ENABLE_CLASSIC
3658 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
3659     return l2cap_get_service_internal(&l2cap_services, psm);
3660 }
3661 
3662 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
3663 
3664     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
3665 
3666     // check for alread registered psm
3667     l2cap_service_t *service = l2cap_get_service(psm);
3668     if (service) {
3669         log_error("l2cap_register_service: PSM %u already registered", psm);
3670         return L2CAP_SERVICE_ALREADY_REGISTERED;
3671     }
3672 
3673     // alloc structure
3674     service = btstack_memory_l2cap_service_get();
3675     if (!service) {
3676         log_error("l2cap_register_service: no memory for l2cap_service_t");
3677         return BTSTACK_MEMORY_ALLOC_FAILED;
3678     }
3679 
3680     // fill in
3681     service->psm = psm;
3682     service->mtu = mtu;
3683     service->packet_handler = service_packet_handler;
3684     service->required_security_level = security_level;
3685 
3686     // add to services list
3687     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
3688 
3689     // enable page scan
3690     gap_connectable_control(1);
3691 
3692     return ERROR_CODE_SUCCESS;
3693 }
3694 
3695 uint8_t l2cap_unregister_service(uint16_t psm){
3696 
3697     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
3698 
3699     l2cap_service_t *service = l2cap_get_service(psm);
3700     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3701     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
3702     btstack_memory_l2cap_service_free(service);
3703 
3704     // disable page scan when no services registered
3705     if (btstack_linked_list_empty(&l2cap_services)) {
3706         gap_connectable_control(0);
3707     }
3708     return ERROR_CODE_SUCCESS;
3709 }
3710 #endif
3711 
3712 
3713 #ifdef ENABLE_LE_DATA_CHANNELS
3714 
3715 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
3716     if (!channel->waiting_for_can_send_now) return;
3717     if (channel->send_sdu_buffer) return;
3718     channel->waiting_for_can_send_now = 0;
3719     log_debug("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
3720     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
3721 }
3722 
3723 // 1BH2222
3724 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
3725     log_info("L2CAP_EVENT_LE_INCOMING_CONNECTION addr_type %u, addr %s handle 0x%x psm 0x%x local_cid 0x%x remote_cid 0x%x, remote_mtu %u",
3726              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
3727     uint8_t event[19];
3728     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
3729     event[1] = sizeof(event) - 2;
3730     event[2] = channel->address_type;
3731     reverse_bd_addr(channel->address, &event[3]);
3732     little_endian_store_16(event,  9, channel->con_handle);
3733     little_endian_store_16(event, 11, channel->psm);
3734     little_endian_store_16(event, 13, channel->local_cid);
3735     little_endian_store_16(event, 15, channel->remote_cid);
3736     little_endian_store_16(event, 17, channel->remote_mtu);
3737     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3738     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3739 }
3740 // 11BH22222
3741 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
3742     log_info("L2CAP_EVENT_LE_CHANNEL_OPENED 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",
3743              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
3744              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
3745     uint8_t event[23];
3746     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
3747     event[1] = sizeof(event) - 2;
3748     event[2] = status;
3749     event[3] = channel->address_type;
3750     reverse_bd_addr(channel->address, &event[4]);
3751     little_endian_store_16(event, 10, channel->con_handle);
3752     event[12] = (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) ? 1 : 0;
3753     little_endian_store_16(event, 13, channel->psm);
3754     little_endian_store_16(event, 15, channel->local_cid);
3755     little_endian_store_16(event, 17, channel->remote_cid);
3756     little_endian_store_16(event, 19, channel->local_mtu);
3757     little_endian_store_16(event, 21, channel->remote_mtu);
3758     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3759     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3760 }
3761 // 2
3762 static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel){
3763     log_info("L2CAP_EVENT_LE_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
3764     uint8_t event[4];
3765     event[0] = L2CAP_EVENT_LE_CHANNEL_CLOSED;
3766     event[1] = sizeof(event) - 2;
3767     little_endian_store_16(event, 2, channel->local_cid);
3768     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3769     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3770 }
3771 
3772 static void l2cap_le_send_pdu(l2cap_channel_t *channel){
3773     btstack_assert(channel != NULL);
3774     btstack_assert(channel->send_pdu_buffer != NULL);
3775     btstack_assert(channel->credits_outgoing > 0);
3776 
3777     // send part of SDU
3778     hci_reserve_packet_buffer();
3779     uint8_t * acl_buffer = hci_get_outgoing_packet_buffer();
3780     uint8_t * l2cap_payload = acl_buffer + 8;
3781     uint16_t pos = 0;
3782     if (!channel->send_sdu_pos){
3783         // store SDU len
3784         channel->send_sdu_pos += 2;
3785         little_endian_store_16(l2cap_payload, pos, channel->send_sdu_len);
3786         pos += 2;
3787     }
3788     uint16_t payload_size = btstack_min(channel->send_sdu_len + 2 - channel->send_sdu_pos, channel->remote_mps - pos);
3789     log_info("len %u, pos %u => payload %u, credits %u", channel->send_sdu_len, channel->send_sdu_pos, payload_size, channel->credits_outgoing);
3790     (void)memcpy(&l2cap_payload[pos],
3791                  &channel->send_sdu_buffer[channel->send_sdu_pos - 2],
3792                  payload_size); // -2 for virtual SDU len
3793     pos += payload_size;
3794     channel->send_sdu_pos += payload_size;
3795     l2cap_setup_header(acl_buffer, channel->con_handle, 0, channel->remote_cid, pos);
3796 
3797     channel->credits_outgoing--;
3798 
3799     hci_send_acl_packet_buffer(8 + pos);
3800 
3801     if (channel->send_sdu_pos >= (channel->send_sdu_len + 2)){
3802         channel->send_sdu_buffer = NULL;
3803         // send done event
3804         l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_PACKET_SENT);
3805         // inform about can send now
3806         l2cap_le_notify_channel_can_send(channel);
3807     }
3808 }
3809 
3810 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
3811 void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
3812     channel->state = L2CAP_STATE_CLOSED;
3813     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
3814     // discard channel
3815     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3816     l2cap_free_channel_entry(channel);
3817 }
3818 
3819 static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
3820     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
3821 }
3822 
3823 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
3824 
3825     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
3826 
3827     // check for alread registered psm
3828     l2cap_service_t *service = l2cap_le_get_service(psm);
3829     if (service) {
3830         return L2CAP_SERVICE_ALREADY_REGISTERED;
3831     }
3832 
3833     // alloc structure
3834     service = btstack_memory_l2cap_service_get();
3835     if (!service) {
3836         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
3837         return BTSTACK_MEMORY_ALLOC_FAILED;
3838     }
3839 
3840     // fill in
3841     service->psm = psm;
3842     service->mtu = 0;
3843     service->packet_handler = packet_handler;
3844     service->required_security_level = security_level;
3845 
3846     // add to services list
3847     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
3848 
3849     // done
3850     return ERROR_CODE_SUCCESS;
3851 }
3852 
3853 uint8_t l2cap_le_unregister_service(uint16_t psm) {
3854     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
3855     l2cap_service_t *service = l2cap_le_get_service(psm);
3856     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3857 
3858     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
3859     btstack_memory_l2cap_service_free(service);
3860     return ERROR_CODE_SUCCESS;
3861 }
3862 
3863 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
3864     // get channel
3865     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3866     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3867 
3868     // validate state
3869     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3870         return ERROR_CODE_COMMAND_DISALLOWED;
3871     }
3872 
3873     // set state accept connection
3874     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
3875     channel->receive_sdu_buffer = receive_sdu_buffer;
3876     channel->local_mtu = mtu;
3877     channel->new_credits_incoming = initial_credits;
3878     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
3879 
3880     // test
3881     // channel->new_credits_incoming = 1;
3882 
3883     // go
3884     l2cap_run();
3885     return ERROR_CODE_SUCCESS;
3886 }
3887 
3888 /**
3889  * @brief Deny incoming LE Data Channel connection due to resource constraints
3890  * @param local_cid             L2CAP LE Data Channel Identifier
3891  */
3892 
3893 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
3894     // get channel
3895     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3896     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3897 
3898     // validate state
3899     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3900         return ERROR_CODE_COMMAND_DISALLOWED;
3901     }
3902 
3903     // set state decline connection
3904     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
3905     channel->reason = 0x04; // no resources available
3906     l2cap_run();
3907     return ERROR_CODE_SUCCESS;
3908 }
3909 
3910 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
3911     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
3912     uint16_t * out_local_cid) {
3913 
3914     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
3915 
3916 
3917     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3918     if (!connection) {
3919         log_error("no hci_connection for handle 0x%04x", con_handle);
3920         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3921     }
3922 
3923     l2cap_channel_t * channel = l2cap_create_channel_entry(packet_handler, L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL, connection->address, connection->address_type, psm, mtu, security_level);
3924     if (!channel) {
3925         return BTSTACK_MEMORY_ALLOC_FAILED;
3926     }
3927     log_info("l2cap_le_create_channel %p", channel);
3928 
3929     // store local_cid
3930     if (out_local_cid){
3931        *out_local_cid = channel->local_cid;
3932     }
3933 
3934     // provide buffer
3935     channel->con_handle = con_handle;
3936     channel->receive_sdu_buffer = receive_sdu_buffer;
3937     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
3938     channel->new_credits_incoming = initial_credits;
3939     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
3940 
3941     // add to connections list
3942     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
3943 
3944     // go
3945     l2cap_run();
3946     return ERROR_CODE_SUCCESS;
3947 }
3948 
3949 /**
3950  * @brief Provide credtis for LE Data Channel
3951  * @param local_cid             L2CAP LE Data Channel Identifier
3952  * @param credits               Number additional credits for peer
3953  */
3954 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
3955 
3956     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3957     if (!channel) {
3958         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
3959         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3960     }
3961 
3962     // check state
3963     if (channel->state != L2CAP_STATE_OPEN){
3964         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
3965     }
3966 
3967     // assert incoming credits + credits <= 0xffff
3968     uint32_t total_credits = channel->credits_incoming;
3969     total_credits += channel->new_credits_incoming;
3970     total_credits += credits;
3971     if (total_credits > 0xffff){
3972         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
3973             channel->new_credits_incoming, credits);
3974     }
3975 
3976     // set credits_granted
3977     channel->new_credits_incoming += credits;
3978 
3979     // go
3980     l2cap_run();
3981     return ERROR_CODE_SUCCESS;
3982 }
3983 
3984 /**
3985  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
3986  * @param local_cid             L2CAP LE Data Channel Identifier
3987  */
3988 int l2cap_le_can_send_now(uint16_t local_cid){
3989     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3990     if (!channel) {
3991         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
3992         return 0;
3993     }
3994 
3995     // check state
3996     if (channel->state != L2CAP_STATE_OPEN) return 0;
3997 
3998     // check queue
3999     if (channel->send_sdu_buffer) return 0;
4000 
4001     // fine, go ahead
4002     return 1;
4003 }
4004 
4005 /**
4006  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
4007  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
4008  *       so packet handler should be ready to handle it
4009  * @param local_cid             L2CAP LE Data Channel Identifier
4010  */
4011 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
4012     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4013     if (!channel) {
4014         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
4015         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4016     }
4017     channel->waiting_for_can_send_now = 1;
4018     l2cap_le_notify_channel_can_send(channel);
4019     return ERROR_CODE_SUCCESS;
4020 }
4021 
4022 /**
4023  * @brief Send data via LE Data Channel
4024  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
4025  * @param local_cid             L2CAP LE Data Channel Identifier
4026  * @param data                  data to send
4027  * @param size                  data size
4028  */
4029 uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
4030 
4031     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4032     if (!channel) {
4033         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4034         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4035     }
4036 
4037     if (len > channel->remote_mtu){
4038         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
4039         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
4040     }
4041 
4042     if (channel->send_sdu_buffer){
4043         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
4044         return BTSTACK_ACL_BUFFERS_FULL;
4045     }
4046 
4047     channel->send_sdu_buffer = data;
4048     channel->send_sdu_len    = len;
4049     channel->send_sdu_pos    = 0;
4050 
4051     l2cap_notify_channel_can_send();
4052     return ERROR_CODE_SUCCESS;
4053 }
4054 
4055 /**
4056  * @brief Disconnect from LE Data Channel
4057  * @param local_cid             L2CAP LE Data Channel Identifier
4058  */
4059 uint8_t l2cap_le_disconnect(uint16_t local_cid)
4060 {
4061     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
4062     if (!channel) {
4063         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
4064         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
4065     }
4066 
4067     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
4068     l2cap_run();
4069     return ERROR_CODE_SUCCESS;
4070 }
4071 
4072 #endif
4073