xref: /btstack/src/l2cap.c (revision 6420389d1a158883e8ea2b4bc8a58cdca363bf96)
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 l2cap_disconnect(uint16_t local_cid, uint8_t reason){
1859     log_info("L2CAP_DISCONNECT local_cid 0x%x reason 0x%x", local_cid, reason);
1860     // find channel for local_cid
1861     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
1862     if (channel) {
1863         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
1864     }
1865     // process
1866     l2cap_run();
1867 }
1868 
1869 static void l2cap_handle_connection_failed_for_addr(bd_addr_t address, uint8_t status){
1870     // mark all channels before emitting open events as these could trigger new connetion requests to the same device
1871     btstack_linked_list_iterator_t it;
1872     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1873     while (btstack_linked_list_iterator_has_next(&it)){
1874         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1875         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
1876         if (bd_addr_cmp( channel->address, address) != 0) continue;
1877         // channel for this address found
1878         switch (channel->state){
1879             case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
1880             case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1881                 channel->state = L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD;
1882                 break;
1883             default:
1884                 break;
1885         }
1886     }
1887     // emit and free marked entries. restart loop to deal with list changes
1888     int done = 0;
1889     while (!done) {
1890         done = 1;
1891         btstack_linked_list_iterator_init(&it, &l2cap_channels);
1892         while (btstack_linked_list_iterator_has_next(&it)){
1893             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1894             if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
1895             if (channel->state == L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD){
1896                 done = 0;
1897                 // failure, forward error code
1898                 l2cap_emit_channel_opened(channel, status);
1899                 // discard channel
1900                 l2cap_stop_rtx(channel);
1901                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1902                 btstack_memory_l2cap_channel_free(channel);
1903                 break;
1904             }
1905         }
1906     }
1907 
1908 }
1909 
1910 static void l2cap_handle_connection_success_for_addr(bd_addr_t address, hci_con_handle_t handle){
1911     btstack_linked_list_iterator_t it;
1912     btstack_linked_list_iterator_init(&it, &l2cap_channels);
1913     while (btstack_linked_list_iterator_has_next(&it)){
1914         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1915         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
1916         if ( ! bd_addr_cmp( channel->address, address) ){
1917             l2cap_handle_connection_complete(handle, channel);
1918         }
1919     }
1920     // process
1921     l2cap_run();
1922 }
1923 #endif
1924 
1925 static void l2cap_notify_channel_can_send(void){
1926     int done = 0;
1927     while (!done){
1928         done = 1;
1929         btstack_linked_list_iterator_t it;
1930         btstack_linked_list_iterator_init(&it, &l2cap_channels);
1931         while (btstack_linked_list_iterator_has_next(&it)){
1932             l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
1933             if (!channel->waiting_for_can_send_now) continue;
1934             int can_send = 0;
1935             if (l2cap_is_le_channel_type(channel->channel_type)){
1936 #ifdef ENABLE_BLE
1937                 can_send = hci_can_send_acl_le_packet_now();
1938 #endif
1939             } else {
1940 #ifdef ENABLE_CLASSIC
1941                 can_send = hci_can_send_acl_classic_packet_now();
1942 #endif
1943             }
1944             if (!can_send) continue;
1945             // requeue for fairness
1946             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
1947             btstack_linked_list_add_tail(&l2cap_channels, (btstack_linked_item_t *) channel);
1948             // emit can send
1949             channel->waiting_for_can_send_now = 0;
1950             l2cap_emit_can_send_now(channel->packet_handler, channel->local_cid);
1951             // exit inner loop as we just broke the iterator, but try again
1952             done = 0;
1953             break;
1954         }
1955     }
1956 }
1957 
1958 #ifdef L2CAP_USES_CHANNELS
1959 
1960 static int l2cap_send_open_failed_on_hci_disconnect(l2cap_channel_t * channel){
1961     // open cannot fail for for incoming connections
1962     if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING) return 0;
1963 
1964     // check state
1965     switch (channel->state){
1966         case L2CAP_STATE_WILL_SEND_CREATE_CONNECTION:
1967         case L2CAP_STATE_WAIT_CONNECTION_COMPLETE:
1968         case L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES:
1969         case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
1970         case L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT:
1971         case L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES:
1972         case L2CAP_STATE_WAIT_CONNECT_RSP:
1973         case L2CAP_STATE_CONFIG:
1974         case L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST:
1975         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST:
1976         case L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE:
1977         case L2CAP_STATE_EMIT_OPEN_FAILED_AND_DISCARD:
1978             return 1;
1979 
1980         case L2CAP_STATE_OPEN:
1981         case L2CAP_STATE_CLOSED:
1982         case L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES:
1983         case L2CAP_STATE_WAIT_DISCONNECT:
1984         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY:
1985         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE:
1986         case L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT:
1987         case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
1988         case L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE:
1989         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE:
1990         case L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT:
1991         case L2CAP_STATE_INVALID:
1992         case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
1993             return 0;
1994         // no default here, to get a warning about new states
1995     }
1996     // still, the compiler insists on a return value
1997     return 0;
1998 }
1999 #endif
2000 
2001 #ifdef ENABLE_CLASSIC
2002 static void l2cap_handle_hci_disconnect_event(l2cap_channel_t * channel){
2003     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2004         l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2005     } else {
2006         l2cap_emit_channel_closed(channel);
2007     }
2008     btstack_memory_l2cap_channel_free(channel);
2009 }
2010 #endif
2011 
2012 #ifdef ENABLE_LE_DATA_CHANNELS
2013 static void l2cap_handle_hci_le_disconnect_event(l2cap_channel_t * channel){
2014     if (l2cap_send_open_failed_on_hci_disconnect(channel)){
2015         l2cap_emit_le_channel_opened(channel, L2CAP_CONNECTION_BASEBAND_DISCONNECT);
2016     } else {
2017         l2cap_emit_le_channel_closed(channel);
2018     }
2019     btstack_memory_l2cap_channel_free(channel);
2020 }
2021 #endif
2022 
2023 static void l2cap_hci_event_handler(uint8_t packet_type, uint16_t cid, uint8_t *packet, uint16_t size){
2024 
2025     UNUSED(packet_type); // ok: registered with hci_event_callback_registration
2026     UNUSED(cid);         // ok: there is no channel
2027     UNUSED(size);        // ok: fixed format events read from HCI buffer
2028 
2029 #ifdef ENABLE_CLASSIC
2030     bd_addr_t address;
2031     int hci_con_used;
2032 #endif
2033 #ifdef L2CAP_USES_CHANNELS
2034     hci_con_handle_t handle;
2035     btstack_linked_list_iterator_t it;
2036 #endif
2037 
2038     switch(hci_event_packet_get_type(packet)){
2039 
2040         // Notify channel packet handler if they can send now
2041         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2042         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
2043         case BTSTACK_EVENT_NR_CONNECTIONS_CHANGED:
2044             l2cap_run();    // try sending signaling packets first
2045             l2cap_notify_channel_can_send();
2046             break;
2047 
2048         case HCI_EVENT_COMMAND_STATUS:
2049 #ifdef ENABLE_CLASSIC
2050             // check command status for create connection for errors
2051             if (HCI_EVENT_IS_COMMAND_STATUS(packet, hci_create_connection)){
2052                 // cache outgoing address and reset
2053                 memcpy(address, l2cap_outgoing_classic_addr, 6);
2054                 memset(l2cap_outgoing_classic_addr, 0, 6);
2055                 // error => outgoing connection failed
2056                 uint8_t status = hci_event_command_status_get_status(packet);
2057                 if (status){
2058                     l2cap_handle_connection_failed_for_addr(address, status);
2059                 }
2060             }
2061 #endif
2062             l2cap_run();    // try sending signaling packets first
2063             break;
2064 
2065 #ifdef ENABLE_CLASSIC
2066         // handle connection complete events
2067         case HCI_EVENT_CONNECTION_COMPLETE:
2068             reverse_bd_addr(&packet[5], address);
2069             if (packet[2] == 0){
2070                 handle = little_endian_read_16(packet, 3);
2071                 l2cap_handle_connection_success_for_addr(address, handle);
2072             } else {
2073                 l2cap_handle_connection_failed_for_addr(address, packet[2]);
2074             }
2075             break;
2076 
2077         // handle successful create connection cancel command
2078         case HCI_EVENT_COMMAND_COMPLETE:
2079             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_create_connection_cancel)) {
2080                 if (packet[5] == 0){
2081                     reverse_bd_addr(&packet[6], address);
2082                     // CONNECTION TERMINATED BY LOCAL HOST (0X16)
2083                     l2cap_handle_connection_failed_for_addr(address, 0x16);
2084                 }
2085             }
2086             l2cap_run();    // try sending signaling packets first
2087             break;
2088 #endif
2089 
2090 #ifdef L2CAP_USES_CHANNELS
2091         // handle disconnection complete events
2092         case HCI_EVENT_DISCONNECTION_COMPLETE:
2093             handle = little_endian_read_16(packet, 3);
2094             // send l2cap open failed or closed events for all channels on this handle and free them
2095             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2096             while (btstack_linked_list_iterator_has_next(&it)){
2097                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2098                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2099                 if (channel->con_handle != handle) continue;
2100                 btstack_linked_list_iterator_remove(&it);
2101                 switch(channel->channel_type){
2102 #ifdef ENABLE_CLASSIC
2103                     case L2CAP_CHANNEL_TYPE_CLASSIC:
2104                         l2cap_stop_rtx(channel);
2105                         l2cap_handle_hci_disconnect_event(channel);
2106                         break;
2107 #endif
2108 #ifdef ENABLE_LE_DATA_CHANNELS
2109                     case L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL:
2110                         l2cap_handle_hci_le_disconnect_event(channel);
2111                         break;
2112 #endif
2113                     default:
2114                         break;
2115                 }
2116             }
2117             break;
2118 #endif
2119 
2120 
2121         // HCI Connection Timeouts
2122 #ifdef ENABLE_CLASSIC
2123         case L2CAP_EVENT_TIMEOUT_CHECK:
2124             handle = little_endian_read_16(packet, 2);
2125             if (gap_get_connection_type(handle) != GAP_CONNECTION_ACL) break;
2126             if (hci_authentication_active_for_handle(handle)) break;
2127             hci_con_used = 0;
2128             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2129             while (btstack_linked_list_iterator_has_next(&it)){
2130                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2131                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2132                 if (channel->con_handle != handle) continue;
2133                 hci_con_used = 1;
2134                 break;
2135             }
2136             if (hci_con_used) break;
2137             if (!hci_can_send_command_packet_now()) break;
2138             hci_send_cmd(&hci_disconnect, handle, 0x13); // remote closed connection
2139             break;
2140 
2141         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2142             handle = little_endian_read_16(packet, 3);
2143             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2144             while (btstack_linked_list_iterator_has_next(&it)){
2145                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2146                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2147                 if (channel->con_handle != handle) continue;
2148                 l2cap_handle_remote_supported_features_received(channel);
2149                 break;
2150             }
2151             break;
2152 
2153         case GAP_EVENT_SECURITY_LEVEL:
2154             handle = little_endian_read_16(packet, 2);
2155             log_info("l2cap - security level update");
2156             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2157             while (btstack_linked_list_iterator_has_next(&it)){
2158                 l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2159                 if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2160                 if (channel->con_handle != handle) continue;
2161 
2162                 gap_security_level_t actual_level = (gap_security_level_t) packet[4];
2163                 gap_security_level_t required_level = channel->required_security_level;
2164 
2165                 log_info("channel state %u: actual %u >= required %u?", channel->state, actual_level, required_level);
2166 
2167                 switch (channel->state){
2168                     case L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE:
2169                         if (actual_level >= required_level){
2170 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2171                             // we need to know if ERTM is supported before sending a config response
2172                             hci_connection_t * connection = hci_connection_for_handle(channel->con_handle);
2173                             connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_W2_SEND_EXTENDED_FEATURE_REQUEST;
2174                             channel->state = L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES;
2175 #else
2176                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2177                             l2cap_emit_incoming_connection(channel);
2178 #endif
2179                         } else {
2180                             channel->reason = 0x0003; // security block
2181                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2182                         }
2183                         break;
2184 
2185                     case L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE:
2186                         if (actual_level >= required_level){
2187                             l2cap_ready_to_connect(channel);
2188                         } else {
2189                             // disconnnect, authentication not good enough
2190                             hci_disconnect_security_block(handle);
2191                         }
2192                         break;
2193 
2194                     default:
2195                         break;
2196                 }
2197             }
2198             break;
2199 #endif
2200 
2201         default:
2202             break;
2203     }
2204 
2205     l2cap_run();
2206 }
2207 
2208 static void l2cap_register_signaling_response(hci_con_handle_t handle, uint8_t code, uint8_t sig_id, uint16_t cid, uint16_t data){
2209     // Vol 3, Part A, 4.3: "The DCID and SCID fields shall be ignored when the result field indi- cates the connection was refused."
2210     if (signaling_responses_pending < NR_PENDING_SIGNALING_RESPONSES) {
2211         signaling_responses[signaling_responses_pending].handle = handle;
2212         signaling_responses[signaling_responses_pending].code = code;
2213         signaling_responses[signaling_responses_pending].sig_id = sig_id;
2214         signaling_responses[signaling_responses_pending].cid = cid;
2215         signaling_responses[signaling_responses_pending].data = data;
2216         signaling_responses_pending++;
2217         l2cap_run();
2218     }
2219 }
2220 
2221 #ifdef ENABLE_CLASSIC
2222 static void l2cap_handle_disconnect_request(l2cap_channel_t *channel, uint16_t identifier){
2223     channel->remote_sig_id = identifier;
2224     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
2225     l2cap_run();
2226 }
2227 
2228 static void l2cap_handle_connection_request(hci_con_handle_t handle, uint8_t sig_id, uint16_t psm, uint16_t source_cid){
2229 
2230     // log_info("l2cap_handle_connection_request for handle %u, psm %u cid 0x%02x", handle, psm, source_cid);
2231     l2cap_service_t *service = l2cap_get_service(psm);
2232     if (!service) {
2233         // 0x0002 PSM not supported
2234         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2235         return;
2236     }
2237 
2238     hci_connection_t * hci_connection = hci_connection_for_handle( handle );
2239     if (!hci_connection) {
2240         //
2241         log_error("no hci_connection for handle %u", handle);
2242         return;
2243     }
2244 
2245     // alloc structure
2246     // log_info("l2cap_handle_connection_request register channel");
2247     l2cap_channel_t * channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_CLASSIC, hci_connection->address, BD_ADDR_TYPE_CLASSIC,
2248     psm, service->mtu, service->required_security_level);
2249     if (!channel){
2250         // 0x0004 No resources available
2251         l2cap_register_signaling_response(handle, CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2252         return;
2253     }
2254 
2255     channel->con_handle = handle;
2256     channel->remote_cid = source_cid;
2257     channel->remote_sig_id = sig_id;
2258 
2259     // limit local mtu to max acl packet length - l2cap header
2260     if (channel->local_mtu > l2cap_max_mtu()) {
2261         channel->local_mtu = l2cap_max_mtu();
2262     }
2263 
2264     // set initial state
2265     channel->state =      L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE;
2266     channel->state_var  = (L2CAP_CHANNEL_STATE_VAR) (L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND | L2CAP_CHANNEL_STATE_VAR_INCOMING);
2267 
2268     // add to connections list
2269     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
2270 
2271     // assert security requirements
2272     gap_request_security_level(handle, channel->required_security_level);
2273 }
2274 
2275 void l2cap_accept_connection(uint16_t local_cid){
2276     log_info("L2CAP_ACCEPT_CONNECTION local_cid 0x%x", local_cid);
2277     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
2278     if (!channel) {
2279         log_error("l2cap_accept_connection called but local_cid 0x%x not found", local_cid);
2280         return;
2281     }
2282 
2283 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2284     // configure L2CAP Basic mode
2285     channel->mode  = L2CAP_CHANNEL_MODE_BASIC;
2286 #endif
2287 
2288     channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT;
2289 
2290     // process
2291     l2cap_run();
2292 }
2293 
2294 void l2cap_decline_connection(uint16_t local_cid){
2295     log_info("L2CAP_DECLINE_CONNECTION local_cid 0x%x", local_cid);
2296     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid( local_cid);
2297     if (!channel) {
2298         log_error( "l2cap_decline_connection called but local_cid 0x%x not found", local_cid);
2299         return;
2300     }
2301     channel->state  = L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE;
2302     channel->reason = 0x04; // no resources available
2303     l2cap_run();
2304 }
2305 
2306 // @pre command len is valid, see check in l2cap_signaling_handler_channel
2307 static void l2cap_signaling_handle_configure_request(l2cap_channel_t *channel, uint8_t *command){
2308 
2309 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2310     uint8_t use_fcs = 1;
2311 #endif
2312 
2313     channel->remote_sig_id = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2314 
2315     uint16_t flags = little_endian_read_16(command, 6);
2316     if (flags & 1) {
2317         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT);
2318     }
2319 
2320     // accept the other's configuration options
2321     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2322     uint16_t pos     = 8;
2323     while (pos < end_pos){
2324         uint8_t option_hint = command[pos] >> 7;
2325         uint8_t option_type = command[pos] & 0x7f;
2326         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
2327         pos++;
2328         uint8_t length = command[pos++];
2329         // MTU { type(8): 1, len(8):2, MTU(16) }
2330         if (option_type == L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT && length == 2){
2331             channel->remote_mtu = little_endian_read_16(command, pos);
2332             log_info("Remote MTU %u", channel->remote_mtu);
2333             if (channel->remote_mtu > l2cap_max_mtu()){
2334                 log_info("Remote MTU %u larger than outgoing buffer, only using MTU = %u", channel->remote_mtu, l2cap_max_mtu());
2335                 channel->remote_mtu = l2cap_max_mtu();
2336             }
2337             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
2338         }
2339         // Flush timeout { type(8):2, len(8): 2, Flush Timeout(16)}
2340         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FLUSH_TIMEOUT && length == 2){
2341             channel->flush_timeout = little_endian_read_16(command, pos);
2342             log_info("Flush timeout: %u ms", channel->flush_timeout);
2343         }
2344 
2345 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2346         // Retransmission and Flow Control Option
2347         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2348             l2cap_channel_mode_t mode = (l2cap_channel_mode_t) command[pos];
2349             switch(channel->mode){
2350                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2351                     // Store remote config
2352                     channel->remote_tx_window_size = command[pos+1];
2353                     channel->remote_max_transmit   = command[pos+2];
2354                     channel->remote_retransmission_timeout_ms = little_endian_read_16(command, pos + 3);
2355                     channel->remote_monitor_timeout_ms = little_endian_read_16(command, pos + 5);
2356                     channel->remote_mps = little_endian_read_16(command, pos + 7);
2357                     log_info("FC&C config: tx window: %u, max transmit %u, retrans timeout %u, monitor timeout %u, mps %u",
2358                         channel->remote_tx_window_size,
2359                         channel->remote_max_transmit,
2360                         channel->remote_retransmission_timeout_ms,
2361                         channel->remote_monitor_timeout_ms,
2362                         channel->remote_mps);
2363                     // If ERTM mandatory, but remote doens't offer ERTM -> disconnect
2364                     if (channel->ertm_mandatory && mode != L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
2365                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2366                     } else {
2367                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
2368                     }
2369                     break;
2370                 case L2CAP_CHANNEL_MODE_BASIC:
2371                     switch (mode){
2372                         case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2373                             // remote asks for ERTM, but we want basic mode. disconnect if this happens a second time
2374                             if (channel->state_var & L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED){
2375                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2376                             }
2377                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED);
2378                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED);
2379                             break;
2380                         default: // case L2CAP_CHANNEL_MODE_BASIC:
2381                             // TODO store and evaluate configuration
2382                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU);
2383                             break;
2384                     }
2385                     break;
2386                 default:
2387                     break;
2388             }
2389         }
2390         if (option_type == L2CAP_CONFIG_OPTION_TYPE_FRAME_CHECK_SEQUENCE && length == 1){
2391             use_fcs = command[pos];
2392         }
2393 #endif
2394         // check for unknown options
2395         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
2396             log_info("l2cap cid %u, unknown options", channel->local_cid);
2397             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
2398         }
2399         pos += length;
2400     }
2401 
2402 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2403         // "FCS" has precedence over "No FCS"
2404         uint8_t update = channel->fcs_option || use_fcs;
2405         log_info("local fcs: %u, remote fcs: %u -> %u", channel->fcs_option, use_fcs, update);
2406         channel->fcs_option = update;
2407 #endif
2408 }
2409 
2410 // @pre command len is valid, see check in l2cap_signaling_handler_channel
2411 static void l2cap_signaling_handle_configure_response(l2cap_channel_t *channel, uint8_t result, uint8_t *command){
2412     log_info("l2cap_signaling_handle_configure_response");
2413 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2414     uint16_t end_pos = 4 + little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2415     uint16_t pos     = 10;
2416     while (pos < end_pos){
2417         uint8_t option_hint = command[pos] >> 7;
2418         uint8_t option_type = command[pos] & 0x7f;
2419         // log_info("l2cap cid %u, hint %u, type %u", channel->local_cid, option_hint, option_type);
2420         pos++;
2421         uint8_t length = command[pos++];
2422 
2423         // Retransmission and Flow Control Option
2424         if (option_type == L2CAP_CONFIG_OPTION_TYPE_RETRANSMISSION_AND_FLOW_CONTROL && length == 9){
2425             switch (channel->mode){
2426                 case L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION:
2427                     if (channel->ertm_mandatory){
2428                         // ??
2429                     } else {
2430                         // On 'Reject - Unacceptable Parameters' to our optional ERTM request, fall back to BASIC mode
2431                         if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2432                             channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2433                         }
2434                     }
2435                     break;
2436                 case L2CAP_CHANNEL_MODE_BASIC:
2437                     if (result == L2CAP_CONF_RESULT_UNACCEPTABLE_PARAMETERS){
2438                         // On 'Reject - Unacceptable Parameters' to our Basic mode request, disconnect
2439                         channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2440                     }
2441                     break;
2442                 default:
2443                     break;
2444             }
2445         }
2446 
2447         // check for unknown options
2448         if (option_hint == 0 && (option_type < L2CAP_CONFIG_OPTION_TYPE_MAX_TRANSMISSION_UNIT || option_type > L2CAP_CONFIG_OPTION_TYPE_EXTENDED_WINDOW_SIZE)){
2449             log_info("l2cap cid %u, unknown options", channel->local_cid);
2450             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID);
2451         }
2452 
2453         pos += length;
2454     }
2455 #else
2456     UNUSED(channel);  // ok: no code
2457     UNUSED(result);   // ok: no code
2458     UNUSED(command);  // ok: no code
2459 #endif
2460 }
2461 
2462 static int l2cap_channel_ready_for_open(l2cap_channel_t *channel){
2463     // log_info("l2cap_channel_ready_for_open 0x%02x", channel->state_var);
2464     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP) == 0) return 0;
2465     if ((channel->state_var & L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP) == 0) return 0;
2466     // addition check that fixes re-entrance issue causing l2cap event channel opened twice
2467     if (channel->state == L2CAP_STATE_OPEN) return 0;
2468     return 1;
2469 }
2470 
2471 
2472 // @pre command len is valid, see check in l2cap_signaling_handler_dispatch
2473 static void l2cap_signaling_handler_channel(l2cap_channel_t *channel, uint8_t *command){
2474 
2475     uint8_t  code       = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2476     uint8_t  identifier = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2477     uint16_t cmd_len    = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2478     uint16_t result = 0;
2479 
2480     log_info("L2CAP signaling handler code %u, state %u", code, channel->state);
2481 
2482     // handle DISCONNECT REQUESTS seperately
2483     if (code == DISCONNECTION_REQUEST){
2484         switch (channel->state){
2485             case L2CAP_STATE_CONFIG:
2486             case L2CAP_STATE_OPEN:
2487             case L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST:
2488             case L2CAP_STATE_WAIT_DISCONNECT:
2489                 l2cap_handle_disconnect_request(channel, identifier);
2490                 break;
2491 
2492             default:
2493                 // ignore in other states
2494                 break;
2495         }
2496         return;
2497     }
2498 
2499     // @STATEMACHINE(l2cap)
2500     switch (channel->state) {
2501 
2502         case L2CAP_STATE_WAIT_CONNECT_RSP:
2503             switch (code){
2504                 case CONNECTION_RESPONSE:
2505                     if (cmd_len < 8){
2506                         // command imcomplete
2507                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2508                         break;
2509                     }
2510                     l2cap_stop_rtx(channel);
2511                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2512                     switch (result) {
2513                         case 0:
2514                             // successful connection
2515                             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2516                             channel->state = L2CAP_STATE_CONFIG;
2517                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2518                             break;
2519                         case 1:
2520                             // connection pending. get some coffee, but start the ERTX
2521                             l2cap_start_ertx(channel);
2522                             break;
2523                         default:
2524                             // channel closed
2525                             channel->state = L2CAP_STATE_CLOSED;
2526                             // map l2cap connection response result to BTstack status enumeration
2527                             l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result);
2528 
2529                             // drop link key if security block
2530                             if (L2CAP_CONNECTION_RESPONSE_RESULT_SUCCESSFUL + result == L2CAP_CONNECTION_RESPONSE_RESULT_REFUSED_SECURITY){
2531                                 gap_drop_link_key_for_bd_addr(channel->address);
2532                             }
2533 
2534                             // discard channel
2535                             btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2536                             btstack_memory_l2cap_channel_free(channel);
2537                             break;
2538                     }
2539                     break;
2540 
2541                 default:
2542                     //@TODO: implement other signaling packets
2543                     break;
2544             }
2545             break;
2546 
2547         case L2CAP_STATE_CONFIG:
2548             switch (code) {
2549                 case CONFIGURE_REQUEST:
2550                     if (cmd_len < 4){
2551                         // command incomplete
2552                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2553                         break;
2554                     }
2555                     channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP);
2556                     l2cap_signaling_handle_configure_request(channel, command);
2557                     if (!(channel->state_var & L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT)){
2558                         // only done if continuation not set
2559                         channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ);
2560                     }
2561                     break;
2562                 case CONFIGURE_RESPONSE:
2563                     if (cmd_len < 6){
2564                         // command incomplete
2565                         l2cap_register_signaling_response(channel->con_handle, COMMAND_REJECT, identifier, 0, L2CAP_REJ_CMD_UNKNOWN);
2566                         break;
2567                     }
2568                     result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2569                     l2cap_stop_rtx(channel);
2570                     l2cap_signaling_handle_configure_response(channel, result, command);
2571                     switch (result){
2572                         case 0: // success
2573                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP);
2574                             break;
2575                         case 4: // pending
2576                             l2cap_start_ertx(channel);
2577                             break;
2578                         default:
2579 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2580                             if (channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION && channel->ertm_mandatory){
2581                                 // remote does not offer ertm but it's required
2582                                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
2583                                 break;
2584                             }
2585 #endif
2586                             // retry on negative result
2587                             channelStateVarSetFlag(channel, L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ);
2588                             break;
2589                     }
2590                     break;
2591                 default:
2592                     break;
2593             }
2594             if (l2cap_channel_ready_for_open(channel)){
2595                 // for open:
2596                 channel->state = L2CAP_STATE_OPEN;
2597                 l2cap_emit_channel_opened(channel, 0);
2598             }
2599             break;
2600 
2601         case L2CAP_STATE_WAIT_DISCONNECT:
2602             switch (code) {
2603                 case DISCONNECTION_RESPONSE:
2604                     l2cap_finialize_channel_close(channel);
2605                     break;
2606                 default:
2607                     //@TODO: implement other signaling packets
2608                     break;
2609             }
2610             break;
2611 
2612         case L2CAP_STATE_CLOSED:
2613             // @TODO handle incoming requests
2614             break;
2615 
2616         case L2CAP_STATE_OPEN:
2617             //@TODO: implement other signaling packets, e.g. re-configure
2618             break;
2619         default:
2620             break;
2621     }
2622     // log_info("new state %u", channel->state);
2623 }
2624 
2625 
2626 // @pre command len is valid, see check in l2cap_acl_classic_handler
2627 static void l2cap_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command){
2628 
2629     btstack_linked_list_iterator_t it;
2630 
2631     // get code, signalind identifier and command len
2632     uint8_t code     = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2633     uint8_t sig_id   = command[L2CAP_SIGNALING_COMMAND_SIGID_OFFSET];
2634     uint16_t cmd_len = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2635 
2636     // not for a particular channel, and not CONNECTION_REQUEST, ECHO_[REQUEST|RESPONSE], INFORMATION_RESPONSE
2637     if (code < 1 || code == ECHO_RESPONSE || code > INFORMATION_RESPONSE){
2638         l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2639         return;
2640     }
2641 
2642     // general commands without an assigned channel
2643     switch(code) {
2644 
2645         case CONNECTION_REQUEST:
2646             if (cmd_len == 4){
2647                 uint16_t psm =        little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2648                 uint16_t source_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
2649                 l2cap_handle_connection_request(handle, sig_id, psm, source_cid);
2650             } else {
2651                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2652             }
2653             return;
2654 
2655         case ECHO_REQUEST:
2656             l2cap_register_signaling_response(handle, code, sig_id, 0, 0);
2657             return;
2658 
2659         case INFORMATION_REQUEST:
2660             if (cmd_len == 2) {
2661                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2662                 l2cap_register_signaling_response(handle, code, sig_id, 0, info_type);
2663             } else {
2664                 l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2665             }
2666             return;
2667 
2668 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
2669         case INFORMATION_RESPONSE: {
2670             hci_connection_t * connection = hci_connection_for_handle(handle);
2671             if (!connection) return;
2672             if (cmd_len >= 4) {
2673                 uint16_t info_type = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2674                 uint16_t result =  little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
2675                 if (result != 0) return;
2676                 if (info_type != L2CAP_INFO_TYPE_EXTENDED_FEATURES_SUPPORTED) return;
2677                 if (cmd_len >= 6) {
2678                     connection->l2cap_state.information_state = L2CAP_INFORMATION_STATE_DONE;
2679                     connection->l2cap_state.extended_feature_mask = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2680                     log_info("extended features mask 0x%02x", connection->l2cap_state.extended_feature_mask);
2681                     // trigger connection request
2682                     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2683                     while (btstack_linked_list_iterator_has_next(&it)){
2684                         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2685                         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2686                         if (channel->con_handle != handle) continue;
2687                         // bail if ERTM was requested but is not supported
2688                         if ((channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION) && ((connection->l2cap_state.extended_feature_mask & 0x08) == 0)){
2689                             if (channel->ertm_mandatory){
2690                                 // channel closed
2691                                 channel->state = L2CAP_STATE_CLOSED;
2692                                 // map l2cap connection response result to BTstack status enumeration
2693                                 l2cap_emit_channel_opened(channel, L2CAP_CONNECTION_RESPONSE_RESULT_ERTM_NOT_SUPPORTED);
2694                                 // discard channel
2695                                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2696                                 btstack_memory_l2cap_channel_free(channel);
2697                                 continue;
2698                             } else {
2699                                 // fallback to Basic mode
2700                                 channel->mode = L2CAP_CHANNEL_MODE_BASIC;
2701                             }
2702                         }
2703                         // start connecting
2704                         if (channel->state == L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES){
2705                             channel->state = L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST;
2706                         }
2707                         // respond to connection request
2708                         if (channel->state == L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES){
2709                             channel->state = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2710                             l2cap_emit_incoming_connection(channel);
2711                         }
2712                     }
2713                     return; // cmd len valid
2714                 }
2715             }
2716             l2cap_register_signaling_response(handle, COMMAND_REJECT, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
2717             return;
2718         }
2719 #endif
2720 
2721         default:
2722             break;
2723     }
2724 
2725     // Get potential destination CID
2726     uint16_t dest_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2727 
2728     // Find channel for this sig_id and connection handle
2729     btstack_linked_list_iterator_init(&it, &l2cap_channels);
2730     while (btstack_linked_list_iterator_has_next(&it)){
2731         l2cap_channel_t * channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2732         if (!l2cap_is_dynamic_channel_type(channel->channel_type)) continue;
2733         if (channel->con_handle != handle) continue;
2734         if (code & 1) {
2735             // match odd commands (responses) by previous signaling identifier
2736             if (channel->local_sig_id == sig_id) {
2737                 l2cap_signaling_handler_channel(channel, command);
2738                 break;
2739             }
2740         } else {
2741             // match even commands (requests) by local channel id
2742             if (channel->local_cid == dest_cid) {
2743                 l2cap_signaling_handler_channel(channel, command);
2744                 break;
2745             }
2746         }
2747     }
2748 }
2749 #endif
2750 
2751 #ifdef ENABLE_BLE
2752 
2753 static void l2cap_emit_connection_parameter_update_response(hci_con_handle_t con_handle, uint16_t result){
2754     uint8_t event[6];
2755     event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_RESPONSE;
2756     event[1] = 4;
2757     little_endian_store_16(event, 2, con_handle);
2758     little_endian_store_16(event, 4, result);
2759     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2760     if (!l2cap_event_packet_handler) return;
2761     (*l2cap_event_packet_handler)(HCI_EVENT_PACKET, 0, event, sizeof(event));
2762 }
2763 
2764 // @returns valid
2765 static int l2cap_le_signaling_handler_dispatch(hci_con_handle_t handle, uint8_t * command, uint8_t sig_id){
2766     hci_connection_t * connection;
2767     uint16_t result;
2768     uint8_t  event[12];
2769 
2770 #ifdef ENABLE_LE_DATA_CHANNELS
2771     btstack_linked_list_iterator_t it;
2772     l2cap_channel_t * channel;
2773     uint16_t local_cid;
2774     uint16_t le_psm;
2775     uint16_t new_credits;
2776     uint16_t credits_before;
2777     l2cap_service_t * service;
2778     uint16_t source_cid;
2779 #endif
2780 
2781     uint8_t code   = command[L2CAP_SIGNALING_COMMAND_CODE_OFFSET];
2782     uint16_t len   = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
2783     log_info("l2cap_le_signaling_handler_dispatch: command 0x%02x, sig id %u, len %u", code, sig_id, len);
2784 
2785     switch (code){
2786 
2787         case CONNECTION_PARAMETER_UPDATE_REQUEST:
2788             // check size
2789             if (len < 8) return 0;
2790             connection = hci_connection_for_handle(handle);
2791             if (connection){
2792                 if (connection->role != HCI_ROLE_MASTER){
2793                     // reject command without notifying upper layer when not in master role
2794                     return 0;
2795                 }
2796                 le_connection_parameter_range_t existing_range;
2797                 gap_get_connection_parameter_range(&existing_range);
2798                 uint16_t le_conn_interval_min   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET);
2799                 uint16_t le_conn_interval_max   = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+2);
2800                 uint16_t le_conn_latency        = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+4);
2801                 uint16_t le_supervision_timeout = little_endian_read_16(command,L2CAP_SIGNALING_COMMAND_DATA_OFFSET+6);
2802 
2803                 int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
2804                 if (update_parameter){
2805                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_RESPONSE;
2806                     connection->le_conn_interval_min = le_conn_interval_min;
2807                     connection->le_conn_interval_max = le_conn_interval_max;
2808                     connection->le_conn_latency = le_conn_latency;
2809                     connection->le_supervision_timeout = le_supervision_timeout;
2810                 } else {
2811                     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
2812                 }
2813                 connection->le_con_param_update_identifier = sig_id;
2814             }
2815 
2816             if (!l2cap_event_packet_handler) break;
2817 
2818             event[0] = L2CAP_EVENT_CONNECTION_PARAMETER_UPDATE_REQUEST;
2819             event[1] = 8;
2820             little_endian_store_16(event, 2, handle);
2821             memcpy(&event[4], &command[4], 8);
2822             hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2823             (*l2cap_event_packet_handler)( HCI_EVENT_PACKET, 0, event, sizeof(event));
2824             break;
2825 
2826         case CONNECTION_PARAMETER_UPDATE_RESPONSE:
2827             // check size
2828             if (len < 2) return 0;
2829             result = little_endian_read_16(command, 4);
2830             l2cap_emit_connection_parameter_update_response(handle, result);
2831             break;
2832 
2833 #ifdef ENABLE_LE_DATA_CHANNELS
2834 
2835         case COMMAND_REJECT:
2836             // Find channel for this sig_id and connection handle
2837             channel = NULL;
2838             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2839             while (btstack_linked_list_iterator_has_next(&it)){
2840                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2841                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
2842                 if (a_channel->con_handle   != handle) continue;
2843                 if (a_channel->local_sig_id != sig_id) continue;
2844                 channel = a_channel;
2845                 break;
2846             }
2847             if (!channel) break;
2848 
2849             // if received while waiting for le connection response, assume legacy device
2850             if (channel->state == L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE){
2851                 channel->state = L2CAP_STATE_CLOSED;
2852                 // no official value for this, use: Connection refused – LE_PSM not supported - 0x0002
2853                 l2cap_emit_le_channel_opened(channel, 0x0002);
2854 
2855                 // discard channel
2856                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2857                 btstack_memory_l2cap_channel_free(channel);
2858                 break;
2859             }
2860             break;
2861 
2862         case LE_CREDIT_BASED_CONNECTION_REQUEST:
2863             // check size
2864             if (len < 10) return 0;
2865 
2866             // get hci connection, bail if not found (must not happen)
2867             connection = hci_connection_for_handle(handle);
2868             if (!connection) return 0;
2869 
2870             // check if service registered
2871             le_psm  = little_endian_read_16(command, 4);
2872             service = l2cap_le_get_service(le_psm);
2873             source_cid = little_endian_read_16(command, 6);
2874 
2875             if (service){
2876                 if (source_cid < 0x40){
2877                     // 0x0009 Connection refused - Invalid Source CID
2878                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0009);
2879                     return 1;
2880                 }
2881 
2882                 // go through list of channels for this ACL connection and check if we get a match
2883                 btstack_linked_list_iterator_init(&it, &l2cap_channels);
2884                 while (btstack_linked_list_iterator_has_next(&it)){
2885                     l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2886                     if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
2887                     if (a_channel->con_handle != handle) continue;
2888                     if (a_channel->remote_cid != source_cid) continue;
2889                     // 0x000a Connection refused - Source CID already allocated
2890                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x000a);
2891                     return 1;
2892                 }
2893 
2894                 // security: check encryption
2895                 if (service->required_security_level >= LEVEL_2){
2896                     if (gap_encryption_key_size(handle) == 0){
2897                         // 0x0008 Connection refused - insufficient encryption
2898                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0008);
2899                         return 1;
2900                     }
2901                     // anything less than 16 byte key size is insufficient
2902                     if (gap_encryption_key_size(handle) < 16){
2903                         // 0x0007 Connection refused – insufficient encryption key size
2904                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0007);
2905                         return 1;
2906                     }
2907                 }
2908 
2909                 // security: check authencation
2910                 if (service->required_security_level >= LEVEL_3){
2911                     if (!gap_authenticated(handle)){
2912                         // 0x0005 Connection refused – insufficient authentication
2913                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0005);
2914                         return 1;
2915                     }
2916                 }
2917 
2918                 // security: check authorization
2919                 if (service->required_security_level >= LEVEL_4){
2920                     if (gap_authorization_state(handle) != AUTHORIZATION_GRANTED){
2921                         // 0x0006 Connection refused – insufficient authorization
2922                         l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0006);
2923                         return 1;
2924                     }
2925                 }
2926 
2927                 // allocate channel
2928                 channel = l2cap_create_channel_entry(service->packet_handler, L2CAP_CHANNEL_TYPE_LE_DATA_CHANNEL, connection->address,
2929                     BD_ADDR_TYPE_LE_RANDOM, le_psm, service->mtu, service->required_security_level);
2930                 if (!channel){
2931                     // 0x0004 Connection refused – no resources available
2932                     l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0004);
2933                     return 1;
2934                 }
2935 
2936                 channel->con_handle = handle;
2937                 channel->remote_cid = source_cid;
2938                 channel->remote_sig_id = sig_id;
2939                 channel->remote_mtu = little_endian_read_16(command, 8);
2940                 channel->remote_mps = little_endian_read_16(command, 10);
2941                 channel->credits_outgoing = little_endian_read_16(command, 12);
2942 
2943                 // set initial state
2944                 channel->state      = L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT;
2945                 channel->state_var |= L2CAP_CHANNEL_STATE_VAR_INCOMING;
2946 
2947                 // add to connections list
2948                 btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
2949 
2950                 // post connection request event
2951                 l2cap_emit_le_incoming_connection(channel);
2952 
2953             } else {
2954                 // Connection refused – LE_PSM not supported
2955                 l2cap_register_signaling_response(handle, LE_CREDIT_BASED_CONNECTION_REQUEST, sig_id, source_cid, 0x0002);
2956             }
2957             break;
2958 
2959         case LE_CREDIT_BASED_CONNECTION_RESPONSE:
2960             // check size
2961             if (len < 10) return 0;
2962 
2963             // Find channel for this sig_id and connection handle
2964             channel = NULL;
2965             btstack_linked_list_iterator_init(&it, &l2cap_channels);
2966             while (btstack_linked_list_iterator_has_next(&it)){
2967                 l2cap_channel_t * a_channel = (l2cap_channel_t *) btstack_linked_list_iterator_next(&it);
2968                 if (!l2cap_is_dynamic_channel_type(a_channel->channel_type)) continue;
2969                 if (a_channel->con_handle   != handle) continue;
2970                 if (a_channel->local_sig_id != sig_id) continue;
2971                 channel = a_channel;
2972                 break;
2973             }
2974             if (!channel) break;
2975 
2976             // cid + 0
2977             result = little_endian_read_16 (command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET+8);
2978             if (result){
2979                 channel->state = L2CAP_STATE_CLOSED;
2980                 // map l2cap connection response result to BTstack status enumeration
2981                 l2cap_emit_le_channel_opened(channel, result);
2982 
2983                 // discard channel
2984                 btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
2985                 btstack_memory_l2cap_channel_free(channel);
2986                 break;
2987             }
2988 
2989             // success
2990             channel->remote_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
2991             channel->remote_mtu = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
2992             channel->remote_mps = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 4);
2993             channel->credits_outgoing = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 6);
2994             channel->state = L2CAP_STATE_OPEN;
2995             l2cap_emit_le_channel_opened(channel, result);
2996             break;
2997 
2998         case LE_FLOW_CONTROL_CREDIT:
2999             // check size
3000             if (len < 4) return 0;
3001 
3002             // find channel
3003             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3004             channel = l2cap_get_channel_for_local_cid(local_cid);
3005             if (!channel) {
3006                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
3007                 break;
3008             }
3009             new_credits = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 2);
3010             credits_before = channel->credits_outgoing;
3011             channel->credits_outgoing += new_credits;
3012             // check for credit overrun
3013             if (credits_before > channel->credits_outgoing){
3014                 log_error("l2cap: new credits caused overrrun for cid 0x%02x, disconnecting", local_cid);
3015                 channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3016                 break;
3017             }
3018             log_info("l2cap: %u credits for 0x%02x, now %u", new_credits, local_cid, channel->credits_outgoing);
3019             break;
3020 
3021         case DISCONNECTION_REQUEST:
3022 
3023             // check size
3024             if (len < 4) return 0;
3025 
3026             // find channel
3027             local_cid = little_endian_read_16(command, L2CAP_SIGNALING_COMMAND_DATA_OFFSET + 0);
3028             channel = l2cap_get_channel_for_local_cid(local_cid);
3029             if (!channel) {
3030                 log_error("l2cap: no channel for cid 0x%02x", local_cid);
3031                 break;
3032             }
3033             channel->remote_sig_id = sig_id;
3034             channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE;
3035             break;
3036 
3037 #endif
3038 
3039         case DISCONNECTION_RESPONSE:
3040             break;
3041 
3042         default:
3043             // command unknown -> reject command
3044             return 0;
3045     }
3046     return 1;
3047 }
3048 #endif
3049 
3050 static void l2cap_acl_classic_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3051 #ifdef ENABLE_CLASSIC
3052     l2cap_channel_t * l2cap_channel;
3053     l2cap_fixed_channel_t * l2cap_fixed_channel;
3054 
3055     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3056     switch (channel_id) {
3057 
3058         case L2CAP_CID_SIGNALING: {
3059             uint16_t command_offset = 8;
3060             while (command_offset < size) {
3061                 // assert signaling command is fully inside packet
3062                 uint16_t data_len = little_endian_read_16(packet, command_offset + L2CAP_SIGNALING_COMMAND_LENGTH_OFFSET);
3063                 uint32_t next_command_offset = ((uint32_t) command_offset) + L2CAP_SIGNALING_COMMAND_DATA_OFFSET + data_len;
3064                 if (next_command_offset > size){
3065                     log_error("l2cap signaling command len invalid -> drop");
3066                     break;
3067                 }
3068                 // handle signaling command
3069                 l2cap_signaling_handler_dispatch(handle, &packet[command_offset]);
3070                 // go to next command
3071                 command_offset = (uint16_t) next_command_offset;
3072             }
3073             break;
3074         }
3075         case L2CAP_CID_CONNECTIONLESS_CHANNEL:
3076             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_CONNECTIONLESS_CHANNEL);
3077             if (!l2cap_fixed_channel) break;
3078             if (!l2cap_fixed_channel->packet_handler) break;
3079             (*l2cap_fixed_channel->packet_handler)(UCD_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3080             break;
3081 
3082         default:
3083             // Find channel for this channel_id and connection handle
3084             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
3085             if (l2cap_channel) {
3086 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
3087                 if (l2cap_channel->mode == L2CAP_CHANNEL_MODE_ENHANCED_RETRANSMISSION){
3088 
3089                     int fcs_size = l2cap_channel->fcs_option ? 2 : 0;
3090 
3091                     // assert control + FCS fields are inside
3092                     if (size < COMPLETE_L2CAP_HEADER+2+fcs_size) break;
3093 
3094                     if (l2cap_channel->fcs_option){
3095                         // verify FCS (required if one side requested it)
3096                         uint16_t fcs_calculated = crc16_calc(&packet[4], size - (4+2));
3097                         uint16_t fcs_packet     = little_endian_read_16(packet, size-2);
3098                         if (fcs_calculated == fcs_packet){
3099                             log_info("Packet FCS 0x%04x verified", fcs_packet);
3100                         } else {
3101                             log_error("FCS mismatch! Packet 0x%04x, calculated 0x%04x", fcs_packet, fcs_calculated);
3102                             // TODO: trigger retransmission or something like that
3103                             break;
3104                         }
3105                     }
3106 
3107                     // switch on packet type
3108                     uint16_t control = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3109                     uint8_t  req_seq = (control >> 8) & 0x3f;
3110                     int final = (control >> 7) & 0x01;
3111                     if (control & 1){
3112                         // S-Frame
3113                         int poll  = (control >> 4) & 0x01;
3114                         l2cap_supervisory_function_t s = (l2cap_supervisory_function_t) ((control >> 2) & 0x03);
3115                         log_info("Control: 0x%04x => Supervisory function %u, ReqSeq %02u", control, (int) s, req_seq);
3116                         l2cap_ertm_tx_packet_state_t * tx_state;
3117                         switch (s){
3118                             case L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY:
3119                                 log_info("L2CAP_SUPERVISORY_FUNCTION_RR_RECEIVER_READY");
3120                                 l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3121                                 if (poll && final){
3122                                     // S-frames shall not be transmitted with both the F-bit and the P-bit set to 1 at the same time.
3123                                     log_error("P=F=1 in S-Frame");
3124                                     break;
3125                                 }
3126                                 if (poll){
3127                                     // check if we did request selective retransmission before <==> we have stored SDU segments
3128                                     int i;
3129                                     int num_stored_out_of_order_packets = 0;
3130                                     for (i=0;i<l2cap_channel->num_rx_buffers;i++){
3131                                         int index = l2cap_channel->rx_store_index + i;
3132                                         if (index >= l2cap_channel->num_rx_buffers){
3133                                             index -= l2cap_channel->num_rx_buffers;
3134                                         }
3135                                         l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3136                                         if (!rx_state->valid) continue;
3137                                         num_stored_out_of_order_packets++;
3138                                     }
3139                                     if (num_stored_out_of_order_packets){
3140                                         l2cap_channel->send_supervisor_frame_selective_reject = 1;
3141                                     } else {
3142                                         l2cap_channel->send_supervisor_frame_receiver_ready   = 1;
3143                                     }
3144                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = 1;
3145                                 }
3146                                 if (final){
3147                                     // Stop-MonitorTimer
3148                                     l2cap_ertm_stop_monitor_timer(l2cap_channel);
3149                                     // If UnackedFrames > 0 then Start-RetransTimer
3150                                     if (l2cap_channel->unacked_frames){
3151                                         l2cap_ertm_start_retransmission_timer(l2cap_channel);
3152                                     }
3153 
3154                                     // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3155                                     l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
3156                                 }
3157                                 break;
3158                             case L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT:
3159                                 log_info("L2CAP_SUPERVISORY_FUNCTION_REJ_REJECT");
3160                                 l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3161                                 // restart transmittion from last unacknowledted packet (earlier packets already freed in l2cap_ertm_process_req_seq)
3162                                 l2cap_channel->unacked_frames = 0;
3163                                 l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
3164                                 break;
3165                             case L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY:
3166                                 log_error("L2CAP_SUPERVISORY_FUNCTION_RNR_RECEIVER_NOT_READY");
3167                                 break;
3168                             case L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT:
3169                                 log_info("L2CAP_SUPERVISORY_FUNCTION_SREJ_SELECTIVE_REJECT");
3170                                 if (poll){
3171                                     l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3172                                 }
3173                                 // find requested i-frame
3174                                 tx_state = l2cap_ertm_get_tx_state(l2cap_channel, req_seq);
3175                                 if (tx_state){
3176                                     log_info("Retransmission for tx_seq %u requested", req_seq);
3177                                     l2cap_channel->set_final_bit_after_packet_with_poll_bit_set = poll;
3178                                     tx_state->retransmission_requested = 1;
3179                                     l2cap_channel->srej_active = 1;
3180                                 }
3181                                 break;
3182                             default:
3183                                 break;
3184                         }
3185                         break;
3186                     } else {
3187                         // I-Frame
3188                         // get control
3189                         l2cap_segmentation_and_reassembly_t sar = (l2cap_segmentation_and_reassembly_t) (control >> 14);
3190                         uint8_t tx_seq = (control >> 1) & 0x3f;
3191                         log_info("Control: 0x%04x => SAR %u, ReqSeq %02u, R?, TxSeq %02u", control, (int) sar, req_seq, tx_seq);
3192                         log_info("SAR: pos %u", l2cap_channel->reassembly_pos);
3193                         log_info("State: expected_tx_seq %02u, req_seq %02u", l2cap_channel->expected_tx_seq, l2cap_channel->req_seq);
3194                         l2cap_ertm_process_req_seq(l2cap_channel, req_seq);
3195                         if (final){
3196                             // final bit set <- response to RR with poll bit set. All not acknowledged packets need to be retransmitted
3197                             l2cap_channel->tx_send_index = l2cap_channel->tx_read_index;
3198                         }
3199 
3200                         // get SDU
3201                         const uint8_t * sdu_data = &packet[COMPLETE_L2CAP_HEADER+2];
3202                         uint16_t        sdu_len  = size-(COMPLETE_L2CAP_HEADER+2+fcs_size);
3203 
3204                         // assert SDU size is smaller or equal to our buffers
3205                         if (sdu_len > l2cap_channel->local_mps) break;
3206 
3207                         // check ordering
3208                         if (l2cap_channel->expected_tx_seq == tx_seq){
3209                             log_info("Received expected frame with TxSeq == ExpectedTxSeq == %02u", tx_seq);
3210                             l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3211                             l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3212 
3213                             // process SDU
3214                             l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, sar, sdu_data, sdu_len);
3215 
3216                             // process stored segments
3217                             while (1){
3218                                 int index = l2cap_channel->rx_store_index;
3219                                 l2cap_ertm_rx_packet_state_t * rx_state = &l2cap_channel->rx_packets_state[index];
3220                                 if (!rx_state->valid) break;
3221 
3222                                 log_info("Processing stored frame with TxSeq == ExpectedTxSeq == %02u", l2cap_channel->expected_tx_seq);
3223                                 l2cap_channel->expected_tx_seq = l2cap_next_ertm_seq_nr(l2cap_channel->expected_tx_seq);
3224                                 l2cap_channel->req_seq         = l2cap_channel->expected_tx_seq;
3225 
3226                                 rx_state->valid = 0;
3227                                 l2cap_ertm_handle_in_sequence_sdu(l2cap_channel, rx_state->sar, &l2cap_channel->rx_packets_data[index], rx_state->len);
3228 
3229                                 // update rx store index
3230                                 index++;
3231                                 if (index >= l2cap_channel->num_rx_buffers){
3232                                     index = 0;
3233                                 }
3234                                 l2cap_channel->rx_store_index = index;
3235                             }
3236 
3237                             //
3238                             l2cap_channel->send_supervisor_frame_receiver_ready = 1;
3239 
3240                         } else {
3241                             int delta = (tx_seq - l2cap_channel->expected_tx_seq) & 0x3f;
3242                             if (delta < 2){
3243                                 // store segment
3244                                 l2cap_ertm_handle_out_of_sequence_sdu(l2cap_channel, sar, delta, sdu_data, sdu_len);
3245 
3246                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-SREJ", tx_seq, l2cap_channel->expected_tx_seq);
3247                                 l2cap_channel->send_supervisor_frame_selective_reject = 1;
3248                             } else {
3249                                 log_info("Received unexpected frame TxSeq %u but expected %u -> send S-REJ", tx_seq, l2cap_channel->expected_tx_seq);
3250                                 l2cap_channel->send_supervisor_frame_reject = 1;
3251                             }
3252                         }
3253                     }
3254                     break;
3255                 }
3256 #endif
3257                 l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3258             }
3259             break;
3260     }
3261 #else
3262     UNUSED(handle); // ok: no code
3263     UNUSED(packet); // ok: no code
3264     UNUSED(size);   // ok: no code
3265 #endif
3266 }
3267 
3268 static void l2cap_acl_le_handler(hci_con_handle_t handle, uint8_t *packet, uint16_t size){
3269 #ifdef ENABLE_BLE
3270 
3271     l2cap_fixed_channel_t * l2cap_fixed_channel;
3272 
3273 #ifdef ENABLE_LE_DATA_CHANNELS
3274     l2cap_channel_t * l2cap_channel;
3275 #endif
3276     uint16_t channel_id = READ_L2CAP_CHANNEL_ID(packet);
3277     switch (channel_id) {
3278 
3279         case L2CAP_CID_SIGNALING_LE: {
3280             uint16_t sig_id = packet[COMPLETE_L2CAP_HEADER + 1];
3281             uint16_t len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER + 2);
3282             if (COMPLETE_L2CAP_HEADER + 4 + len > size) break;
3283             int      valid  = l2cap_le_signaling_handler_dispatch(handle, &packet[COMPLETE_L2CAP_HEADER], sig_id);
3284             if (!valid){
3285                 l2cap_register_signaling_response(handle, COMMAND_REJECT_LE, sig_id, 0, L2CAP_REJ_CMD_UNKNOWN);
3286             }
3287             break;
3288         }
3289 
3290         case L2CAP_CID_ATTRIBUTE_PROTOCOL:
3291             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_ATTRIBUTE_PROTOCOL);
3292             if (!l2cap_fixed_channel) break;
3293             if (!l2cap_fixed_channel->packet_handler) break;
3294             (*l2cap_fixed_channel->packet_handler)(ATT_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3295             break;
3296 
3297         case L2CAP_CID_SECURITY_MANAGER_PROTOCOL:
3298             l2cap_fixed_channel = l2cap_fixed_channel_for_channel_id(L2CAP_CID_SECURITY_MANAGER_PROTOCOL);
3299             if (!l2cap_fixed_channel) break;
3300             if (!l2cap_fixed_channel->packet_handler) break;
3301             (*l2cap_fixed_channel->packet_handler)(SM_DATA_PACKET, handle, &packet[COMPLETE_L2CAP_HEADER], size-COMPLETE_L2CAP_HEADER);
3302             break;
3303 
3304         default:
3305 
3306 #ifdef ENABLE_LE_DATA_CHANNELS
3307             l2cap_channel = l2cap_get_channel_for_local_cid(channel_id);
3308             if (l2cap_channel) {
3309                 // credit counting
3310                 if (l2cap_channel->credits_incoming == 0){
3311                     log_error("LE Data Channel packet received but no incoming credits");
3312                     l2cap_channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3313                     break;
3314                 }
3315                 l2cap_channel->credits_incoming--;
3316 
3317                 // automatic credits
3318                 if (l2cap_channel->credits_incoming < L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_WATERMARK && l2cap_channel->automatic_credits){
3319                     l2cap_channel->new_credits_incoming = L2CAP_LE_DATA_CHANNELS_AUTOMATIC_CREDITS_INCREMENT;
3320                 }
3321 
3322                 // first fragment
3323                 uint16_t pos = 0;
3324                 if (!l2cap_channel->receive_sdu_len){
3325                     uint16_t sdu_len = little_endian_read_16(packet, COMPLETE_L2CAP_HEADER);
3326                     if(sdu_len > l2cap_channel->local_mtu) break;   // SDU would be larger than our buffer
3327                     l2cap_channel->receive_sdu_len = sdu_len;
3328                     l2cap_channel->receive_sdu_pos = 0;
3329                     pos  += 2;
3330                     size -= 2;
3331                 }
3332                 uint16_t fragment_size   = size-COMPLETE_L2CAP_HEADER;
3333                 uint16_t remaining_space = l2cap_channel->local_mtu - l2cap_channel->receive_sdu_pos;
3334                 if (fragment_size > remaining_space) break;         // SDU would cause buffer overrun
3335                 memcpy(&l2cap_channel->receive_sdu_buffer[l2cap_channel->receive_sdu_pos], &packet[COMPLETE_L2CAP_HEADER+pos], fragment_size);
3336                 l2cap_channel->receive_sdu_pos += size - COMPLETE_L2CAP_HEADER;
3337                 // done?
3338                 log_debug("le packet pos %u, len %u", l2cap_channel->receive_sdu_pos, l2cap_channel->receive_sdu_len);
3339                 if (l2cap_channel->receive_sdu_pos >= l2cap_channel->receive_sdu_len){
3340                     l2cap_dispatch_to_channel(l2cap_channel, L2CAP_DATA_PACKET, l2cap_channel->receive_sdu_buffer, l2cap_channel->receive_sdu_len);
3341                     l2cap_channel->receive_sdu_len = 0;
3342                 }
3343             } else {
3344                 log_error("LE Data Channel packet received but no channel found for cid 0x%02x", channel_id);
3345             }
3346 #endif
3347             break;
3348     }
3349 #else
3350     UNUSED(handle); // ok: no code
3351     UNUSED(packet); // ok: no code
3352     UNUSED(size);   // ok: no code
3353 #endif
3354 }
3355 
3356 static void l2cap_acl_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
3357     UNUSED(packet_type);    // ok: registered with hci_register_acl_packet_handler
3358     UNUSED(channel);        // ok: there is no channel
3359 
3360     // Assert full L2CAP header present
3361     if (size < COMPLETE_L2CAP_HEADER) return;
3362 
3363     // Dispatch to Classic or LE handler
3364     hci_con_handle_t handle = READ_ACL_CONNECTION_HANDLE(packet);
3365     hci_connection_t *conn = hci_connection_for_handle(handle);
3366     if (!conn) return;
3367     if (conn->address_type == BD_ADDR_TYPE_CLASSIC){
3368         l2cap_acl_classic_handler(handle, packet, size);
3369     } else {
3370         l2cap_acl_le_handler(handle, packet, size);
3371     }
3372 
3373     l2cap_run();
3374 }
3375 
3376 // Bluetooth 4.0 - allows to register handler for Attribute Protocol and Security Manager Protocol
3377 void l2cap_register_fixed_channel(btstack_packet_handler_t the_packet_handler, uint16_t channel_id) {
3378     l2cap_fixed_channel_t * channel = l2cap_fixed_channel_for_channel_id(channel_id);
3379     if (!channel) return;
3380     channel->packet_handler = the_packet_handler;
3381 }
3382 
3383 #ifdef ENABLE_CLASSIC
3384 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
3385 void l2cap_finialize_channel_close(l2cap_channel_t * channel){
3386     channel->state = L2CAP_STATE_CLOSED;
3387     l2cap_emit_channel_closed(channel);
3388     // discard channel
3389     l2cap_stop_rtx(channel);
3390     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3391     btstack_memory_l2cap_channel_free(channel);
3392 }
3393 #endif
3394 
3395 #ifdef L2CAP_USES_CHANNELS
3396 static l2cap_service_t * l2cap_get_service_internal(btstack_linked_list_t * services, uint16_t psm){
3397     btstack_linked_list_iterator_t it;
3398     btstack_linked_list_iterator_init(&it, services);
3399     while (btstack_linked_list_iterator_has_next(&it)){
3400         l2cap_service_t * service = (l2cap_service_t *) btstack_linked_list_iterator_next(&it);
3401         if ( service->psm == psm){
3402             return service;
3403         };
3404     }
3405     return NULL;
3406 }
3407 #endif
3408 
3409 #ifdef ENABLE_CLASSIC
3410 static inline l2cap_service_t * l2cap_get_service(uint16_t psm){
3411     return l2cap_get_service_internal(&l2cap_services, psm);
3412 }
3413 
3414 uint8_t l2cap_register_service(btstack_packet_handler_t service_packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level){
3415 
3416     log_info("L2CAP_REGISTER_SERVICE psm 0x%x mtu %u", psm, mtu);
3417 
3418     // check for alread registered psm
3419     l2cap_service_t *service = l2cap_get_service(psm);
3420     if (service) {
3421         log_error("l2cap_register_service: PSM %u already registered", psm);
3422         return L2CAP_SERVICE_ALREADY_REGISTERED;
3423     }
3424 
3425     // alloc structure
3426     service = btstack_memory_l2cap_service_get();
3427     if (!service) {
3428         log_error("l2cap_register_service: no memory for l2cap_service_t");
3429         return BTSTACK_MEMORY_ALLOC_FAILED;
3430     }
3431 
3432     // fill in
3433     service->psm = psm;
3434     service->mtu = mtu;
3435     service->packet_handler = service_packet_handler;
3436     service->required_security_level = security_level;
3437 
3438     // add to services list
3439     btstack_linked_list_add(&l2cap_services, (btstack_linked_item_t *) service);
3440 
3441     // enable page scan
3442     gap_connectable_control(1);
3443 
3444     return 0;
3445 }
3446 
3447 uint8_t l2cap_unregister_service(uint16_t psm){
3448 
3449     log_info("L2CAP_UNREGISTER_SERVICE psm 0x%x", psm);
3450 
3451     l2cap_service_t *service = l2cap_get_service(psm);
3452     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3453     btstack_linked_list_remove(&l2cap_services, (btstack_linked_item_t *) service);
3454     btstack_memory_l2cap_service_free(service);
3455 
3456     // disable page scan when no services registered
3457     if (btstack_linked_list_empty(&l2cap_services)) {
3458         gap_connectable_control(0);
3459     }
3460     return 0;
3461 }
3462 #endif
3463 
3464 
3465 #ifdef ENABLE_LE_DATA_CHANNELS
3466 
3467 static void l2cap_le_notify_channel_can_send(l2cap_channel_t *channel){
3468     if (!channel->waiting_for_can_send_now) return;
3469     if (channel->send_sdu_buffer) return;
3470     channel->waiting_for_can_send_now = 0;
3471     log_debug("L2CAP_EVENT_CHANNEL_LE_CAN_SEND_NOW local_cid 0x%x", channel->local_cid);
3472     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_LE_CAN_SEND_NOW);
3473 }
3474 
3475 // 1BH2222
3476 static void l2cap_emit_le_incoming_connection(l2cap_channel_t *channel) {
3477     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",
3478              channel->address_type, bd_addr_to_str(channel->address), channel->con_handle,  channel->psm, channel->local_cid, channel->remote_cid, channel->remote_mtu);
3479     uint8_t event[19];
3480     event[0] = L2CAP_EVENT_LE_INCOMING_CONNECTION;
3481     event[1] = sizeof(event) - 2;
3482     event[2] = channel->address_type;
3483     reverse_bd_addr(channel->address, &event[3]);
3484     little_endian_store_16(event,  9, channel->con_handle);
3485     little_endian_store_16(event, 11, channel->psm);
3486     little_endian_store_16(event, 13, channel->local_cid);
3487     little_endian_store_16(event, 15, channel->remote_cid);
3488     little_endian_store_16(event, 17, channel->remote_mtu);
3489     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3490     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3491 }
3492 // 11BH22222
3493 static void l2cap_emit_le_channel_opened(l2cap_channel_t *channel, uint8_t status) {
3494     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",
3495              status, channel->address_type, bd_addr_to_str(channel->address), channel->con_handle, channel->psm,
3496              channel->local_cid, channel->remote_cid, channel->local_mtu, channel->remote_mtu);
3497     uint8_t event[23];
3498     event[0] = L2CAP_EVENT_LE_CHANNEL_OPENED;
3499     event[1] = sizeof(event) - 2;
3500     event[2] = status;
3501     event[3] = channel->address_type;
3502     reverse_bd_addr(channel->address, &event[4]);
3503     little_endian_store_16(event, 10, channel->con_handle);
3504     event[12] = channel->state_var & L2CAP_CHANNEL_STATE_VAR_INCOMING ? 1 : 0;
3505     little_endian_store_16(event, 13, channel->psm);
3506     little_endian_store_16(event, 15, channel->local_cid);
3507     little_endian_store_16(event, 17, channel->remote_cid);
3508     little_endian_store_16(event, 19, channel->local_mtu);
3509     little_endian_store_16(event, 21, channel->remote_mtu);
3510     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3511     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3512 }
3513 // 2
3514 static void l2cap_emit_le_channel_closed(l2cap_channel_t * channel){
3515     log_info("L2CAP_EVENT_LE_CHANNEL_CLOSED local_cid 0x%x", channel->local_cid);
3516     uint8_t event[4];
3517     event[0] = L2CAP_EVENT_LE_CHANNEL_CLOSED;
3518     event[1] = sizeof(event) - 2;
3519     little_endian_store_16(event, 2, channel->local_cid);
3520     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
3521     l2cap_dispatch_to_channel(channel, HCI_EVENT_PACKET, event, sizeof(event));
3522 }
3523 
3524 // finalize closed channel - l2cap_handle_disconnect_request & DISCONNECTION_RESPONSE
3525 void l2cap_le_finialize_channel_close(l2cap_channel_t * channel){
3526     channel->state = L2CAP_STATE_CLOSED;
3527     l2cap_emit_simple_event_with_cid(channel, L2CAP_EVENT_CHANNEL_CLOSED);
3528     // discard channel
3529     btstack_linked_list_remove(&l2cap_channels, (btstack_linked_item_t *) channel);
3530     btstack_memory_l2cap_channel_free(channel);
3531 }
3532 
3533 static inline l2cap_service_t * l2cap_le_get_service(uint16_t le_psm){
3534     return l2cap_get_service_internal(&l2cap_le_services, le_psm);
3535 }
3536 
3537 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level){
3538 
3539     log_info("L2CAP_LE_REGISTER_SERVICE psm 0x%x", psm);
3540 
3541     // check for alread registered psm
3542     l2cap_service_t *service = l2cap_le_get_service(psm);
3543     if (service) {
3544         return L2CAP_SERVICE_ALREADY_REGISTERED;
3545     }
3546 
3547     // alloc structure
3548     service = btstack_memory_l2cap_service_get();
3549     if (!service) {
3550         log_error("l2cap_register_service_internal: no memory for l2cap_service_t");
3551         return BTSTACK_MEMORY_ALLOC_FAILED;
3552     }
3553 
3554     // fill in
3555     service->psm = psm;
3556     service->mtu = 0;
3557     service->packet_handler = packet_handler;
3558     service->required_security_level = security_level;
3559 
3560     // add to services list
3561     btstack_linked_list_add(&l2cap_le_services, (btstack_linked_item_t *) service);
3562 
3563     // done
3564     return 0;
3565 }
3566 
3567 uint8_t l2cap_le_unregister_service(uint16_t psm) {
3568     log_info("L2CAP_LE_UNREGISTER_SERVICE psm 0x%x", psm);
3569     l2cap_service_t *service = l2cap_le_get_service(psm);
3570     if (!service) return L2CAP_SERVICE_DOES_NOT_EXIST;
3571 
3572     btstack_linked_list_remove(&l2cap_le_services, (btstack_linked_item_t *) service);
3573     btstack_memory_l2cap_service_free(service);
3574     return 0;
3575 }
3576 
3577 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits){
3578     // get channel
3579     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3580     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3581 
3582     // validate state
3583     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3584         return ERROR_CODE_COMMAND_DISALLOWED;
3585     }
3586 
3587     // set state accept connection
3588     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT;
3589     channel->receive_sdu_buffer = receive_sdu_buffer;
3590     channel->local_mtu = mtu;
3591     channel->new_credits_incoming = initial_credits;
3592     channel->automatic_credits  = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
3593 
3594     // test
3595     // channel->new_credits_incoming = 1;
3596 
3597     // go
3598     l2cap_run();
3599     return 0;
3600 }
3601 
3602 /**
3603  * @brief Deny incoming LE Data Channel connection due to resource constraints
3604  * @param local_cid             L2CAP LE Data Channel Identifier
3605  */
3606 
3607 uint8_t l2cap_le_decline_connection(uint16_t local_cid){
3608     // get channel
3609     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3610     if (!channel) return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3611 
3612     // validate state
3613     if (channel->state != L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT){
3614         return ERROR_CODE_COMMAND_DISALLOWED;
3615     }
3616 
3617     // set state decline connection
3618     channel->state  = L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE;
3619     channel->reason = 0x04; // no resources available
3620     l2cap_run();
3621     return 0;
3622 }
3623 
3624 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
3625     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
3626     uint16_t * out_local_cid) {
3627 
3628     log_info("L2CAP_LE_CREATE_CHANNEL handle 0x%04x psm 0x%x mtu %u", con_handle, psm, mtu);
3629 
3630 
3631     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3632     if (!connection) {
3633         log_error("no hci_connection for handle 0x%04x", con_handle);
3634         return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3635     }
3636 
3637     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);
3638     if (!channel) {
3639         return BTSTACK_MEMORY_ALLOC_FAILED;
3640     }
3641     log_info("l2cap_le_create_channel %p", channel);
3642 
3643     // store local_cid
3644     if (out_local_cid){
3645        *out_local_cid = channel->local_cid;
3646     }
3647 
3648     // provide buffer
3649     channel->con_handle = con_handle;
3650     channel->receive_sdu_buffer = receive_sdu_buffer;
3651     channel->state = L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST;
3652     channel->new_credits_incoming = initial_credits;
3653     channel->automatic_credits    = initial_credits == L2CAP_LE_AUTOMATIC_CREDITS;
3654 
3655     // add to connections list
3656     btstack_linked_list_add(&l2cap_channels, (btstack_linked_item_t *) channel);
3657 
3658     // go
3659     l2cap_run();
3660     return 0;
3661 }
3662 
3663 /**
3664  * @brief Provide credtis for LE Data Channel
3665  * @param local_cid             L2CAP LE Data Channel Identifier
3666  * @param credits               Number additional credits for peer
3667  */
3668 uint8_t l2cap_le_provide_credits(uint16_t local_cid, uint16_t credits){
3669 
3670     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3671     if (!channel) {
3672         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
3673         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3674     }
3675 
3676     // check state
3677     if (channel->state != L2CAP_STATE_OPEN){
3678         log_error("l2cap_le_provide_credits but channel 0x%02x not open yet", local_cid);
3679     }
3680 
3681     // assert incoming credits + credits <= 0xffff
3682     uint32_t total_credits = channel->credits_incoming;
3683     total_credits += channel->new_credits_incoming;
3684     total_credits += credits;
3685     if (total_credits > 0xffff){
3686         log_error("l2cap_le_provide_credits overrun: current %u, scheduled %u, additional %u", channel->credits_incoming,
3687             channel->new_credits_incoming, credits);
3688     }
3689 
3690     // set credits_granted
3691     channel->new_credits_incoming += credits;
3692 
3693     // go
3694     l2cap_run();
3695     return 0;
3696 }
3697 
3698 /**
3699  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
3700  * @param local_cid             L2CAP LE Data Channel Identifier
3701  */
3702 int l2cap_le_can_send_now(uint16_t local_cid){
3703     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3704     if (!channel) {
3705         log_error("l2cap_le_provide_credits no channel for cid 0x%02x", local_cid);
3706         return 0;
3707     }
3708 
3709     // check state
3710     if (channel->state != L2CAP_STATE_OPEN) return 0;
3711 
3712     // check queue
3713     if (channel->send_sdu_buffer) return 0;
3714 
3715     // fine, go ahead
3716     return 1;
3717 }
3718 
3719 /**
3720  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
3721  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
3722  *       so packet handler should be ready to handle it
3723  * @param local_cid             L2CAP LE Data Channel Identifier
3724  */
3725 uint8_t l2cap_le_request_can_send_now_event(uint16_t local_cid){
3726     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3727     if (!channel) {
3728         log_error("l2cap_le_request_can_send_now_event no channel for cid 0x%02x", local_cid);
3729         return 0;
3730     }
3731     channel->waiting_for_can_send_now = 1;
3732     l2cap_le_notify_channel_can_send(channel);
3733     return 0;
3734 }
3735 
3736 /**
3737  * @brief Send data via LE Data Channel
3738  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
3739  * @param local_cid             L2CAP LE Data Channel Identifier
3740  * @param data                  data to send
3741  * @param size                  data size
3742  */
3743 uint8_t l2cap_le_send_data(uint16_t local_cid, uint8_t * data, uint16_t len){
3744 
3745     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3746     if (!channel) {
3747         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
3748         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3749     }
3750 
3751     if (len > channel->remote_mtu){
3752         log_error("l2cap_send cid 0x%02x, data length exceeds remote MTU.", local_cid);
3753         return L2CAP_DATA_LEN_EXCEEDS_REMOTE_MTU;
3754     }
3755 
3756     if (channel->send_sdu_buffer){
3757         log_info("l2cap_send cid 0x%02x, cannot send", local_cid);
3758         return BTSTACK_ACL_BUFFERS_FULL;
3759     }
3760 
3761     channel->send_sdu_buffer = data;
3762     channel->send_sdu_len    = len;
3763     channel->send_sdu_pos    = 0;
3764 
3765     l2cap_run();
3766     return 0;
3767 }
3768 
3769 /**
3770  * @brief Disconnect from LE Data Channel
3771  * @param local_cid             L2CAP LE Data Channel Identifier
3772  */
3773 uint8_t l2cap_le_disconnect(uint16_t local_cid)
3774 {
3775     l2cap_channel_t * channel = l2cap_get_channel_for_local_cid(local_cid);
3776     if (!channel) {
3777         log_error("l2cap_send no channel for cid 0x%02x", local_cid);
3778         return L2CAP_LOCAL_CID_DOES_NOT_EXIST;
3779     }
3780 
3781     channel->state = L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST;
3782     l2cap_run();
3783     return 0;
3784 }
3785 
3786 #endif
3787