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