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