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