xref: /btstack/src/hci.c (revision b55748bb3b8c227b9b69928fb007ca067294e3b5)
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 /*
39  *  hci.c
40  *
41  *  Created by Matthias Ringwald on 4/29/09.
42  *
43  */
44 
45 #include "btstack_config.h"
46 
47 
48 #ifdef ENABLE_CLASSIC
49 #ifdef HAVE_EMBEDDED_TICK
50 #include "btstack_run_loop_embedded.h"
51 #endif
52 #endif
53 
54 #ifdef HAVE_PLATFORM_IPHONE_OS
55 #include "../port/ios/src/btstack_control_iphone.h"
56 #endif
57 
58 #ifdef ENABLE_BLE
59 #include "gap.h"
60 #endif
61 
62 #include <stdarg.h>
63 #include <string.h>
64 #include <stdio.h>
65 #include <inttypes.h>
66 
67 #include "btstack_debug.h"
68 #include "btstack_event.h"
69 #include "btstack_linked_list.h"
70 #include "btstack_memory.h"
71 #include "gap.h"
72 #include "hci.h"
73 #include "hci_cmd.h"
74 #include "hci_dump.h"
75 
76 
77 #define HCI_CONNECTION_TIMEOUT_MS 10000
78 #define HCI_RESET_RESEND_TIMEOUT_MS 200
79 
80 // prototypes
81 #ifdef ENABLE_CLASSIC
82 static void hci_update_scan_enable(void);
83 static void hci_emit_discoverable_enabled(uint8_t enabled);
84 static int  hci_local_ssp_activated(void);
85 static int  hci_remote_ssp_supported(hci_con_handle_t con_handle);
86 static void hci_notify_if_sco_can_send_now(void);
87 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status);
88 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
89 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level);
90 static void hci_connection_timeout_handler(btstack_timer_source_t *timer);
91 static void hci_connection_timestamp(hci_connection_t *connection);
92 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn);
93 #endif
94 static int  hci_power_control_on(void);
95 static void hci_power_control_off(void);
96 static void hci_state_reset(void);
97 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason);
98 static void hci_emit_nr_connections_changed(void);
99 static void hci_emit_hci_open_failed(void);
100 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status);
101 static void hci_emit_event(uint8_t * event, uint16_t size, int dump);
102 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size);
103 static void hci_run(void);
104 static int  hci_is_le_connection(hci_connection_t * connection);
105 static int  hci_number_free_acl_slots_for_connection_type( bd_addr_type_t address_type);
106 
107 #ifdef ENABLE_BLE
108 #ifdef ENABLE_LE_CENTRAL
109 // called from test/ble_client/advertising_data_parser.c
110 void le_handle_advertisement_report(uint8_t *packet, int size);
111 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address);
112 #endif
113 #endif
114 
115 // the STACK is here
116 #ifndef HAVE_MALLOC
117 static hci_stack_t   hci_stack_static;
118 #endif
119 static hci_stack_t * hci_stack = NULL;
120 
121 #ifdef ENABLE_CLASSIC
122 // test helper
123 static uint8_t disable_l2cap_timeouts = 0;
124 #endif
125 
126 /**
127  * create connection for given address
128  *
129  * @return connection OR NULL, if no memory left
130  */
131 static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
132     log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type);
133     hci_connection_t * conn = btstack_memory_hci_connection_get();
134     if (!conn) return NULL;
135     memset(conn, 0, sizeof(hci_connection_t));
136     bd_addr_copy(conn->address, addr);
137     conn->address_type = addr_type;
138     conn->con_handle = 0xffff;
139     conn->authentication_flags = AUTH_FLAGS_NONE;
140     conn->bonding_flags = 0;
141     conn->requested_security_level = LEVEL_0;
142 #ifdef ENABLE_CLASSIC
143     btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler);
144     btstack_run_loop_set_timer_context(&conn->timeout, conn);
145     hci_connection_timestamp(conn);
146 #endif
147     conn->acl_recombination_length = 0;
148     conn->acl_recombination_pos = 0;
149     conn->num_acl_packets_sent = 0;
150     conn->num_sco_packets_sent = 0;
151     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
152     btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn);
153     return conn;
154 }
155 
156 
157 /**
158  * get le connection parameter range
159 *
160  * @return le connection parameter range struct
161  */
162 void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){
163     *range = hci_stack->le_connection_parameter_range;
164 }
165 
166 /**
167  * set le connection parameter range
168  *
169  */
170 
171 void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){
172     hci_stack->le_connection_parameter_range = *range;
173 }
174 
175 /**
176  * get hci connections iterator
177  *
178  * @return hci connections iterator
179  */
180 
181 void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){
182     btstack_linked_list_iterator_init(it, &hci_stack->connections);
183 }
184 
185 /**
186  * get connection for a given handle
187  *
188  * @return connection OR NULL, if not found
189  */
190 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
191     btstack_linked_list_iterator_t it;
192     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
193     while (btstack_linked_list_iterator_has_next(&it)){
194         hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
195         if ( item->con_handle == con_handle ) {
196             return item;
197         }
198     }
199     return NULL;
200 }
201 
202 /**
203  * get connection for given address
204  *
205  * @return connection OR NULL, if not found
206  */
207 hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t  addr, bd_addr_type_t addr_type){
208     btstack_linked_list_iterator_t it;
209     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
210     while (btstack_linked_list_iterator_has_next(&it)){
211         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
212         if (connection->address_type != addr_type)  continue;
213         if (memcmp(addr, connection->address, 6) != 0) continue;
214         return connection;
215     }
216     return NULL;
217 }
218 
219 
220 #ifdef ENABLE_CLASSIC
221 
222 #ifdef ENABLE_SCO_OVER_HCI
223 static int hci_number_sco_connections(void){
224     int connections = 0;
225     btstack_linked_list_iterator_t it;
226     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
227     while (btstack_linked_list_iterator_has_next(&it)){
228         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
229         if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
230         connections++;
231     }
232     return connections;
233 }
234 #endif
235 
236 static void hci_connection_timeout_handler(btstack_timer_source_t *timer){
237     hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer);
238 #ifdef HAVE_EMBEDDED_TICK
239     if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
240         // connections might be timed out
241         hci_emit_l2cap_check_timeout(connection);
242     }
243 #else
244     if (btstack_run_loop_get_time_ms() > connection->timestamp + HCI_CONNECTION_TIMEOUT_MS){
245         // connections might be timed out
246         hci_emit_l2cap_check_timeout(connection);
247     }
248 #endif
249 }
250 
251 static void hci_connection_timestamp(hci_connection_t *connection){
252 #ifdef HAVE_EMBEDDED_TICK
253     connection->timestamp = btstack_run_loop_embedded_get_ticks();
254 #else
255     connection->timestamp = btstack_run_loop_get_time_ms();
256 #endif
257 }
258 
259 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
260     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
261 }
262 
263 
264 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
265     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
266 }
267 
268 /**
269  * add authentication flags and reset timer
270  * @note: assumes classic connection
271  * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets
272  */
273 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
274     bd_addr_t addr;
275     reverse_bd_addr(bd_addr, addr);
276     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
277     if (conn) {
278         connectionSetAuthenticationFlags(conn, flags);
279         hci_connection_timestamp(conn);
280     }
281 }
282 
283 int  hci_authentication_active_for_handle(hci_con_handle_t handle){
284     hci_connection_t * conn = hci_connection_for_handle(handle);
285     if (!conn) return 0;
286     if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
287     if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
288     return 0;
289 }
290 
291 void gap_drop_link_key_for_bd_addr(bd_addr_t addr){
292     if (!hci_stack->link_key_db) return;
293     log_info("gap_drop_link_key_for_bd_addr: %s", bd_addr_to_str(addr));
294     hci_stack->link_key_db->delete_link_key(addr);
295 }
296 
297 void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){
298     if (!hci_stack->link_key_db) return;
299     log_info("gap_store_link_key_for_bd_addr: %s, type %u", bd_addr_to_str(addr), type);
300     hci_stack->link_key_db->put_link_key(addr, link_key, type);
301 }
302 #endif
303 
304 static int hci_is_le_connection(hci_connection_t * connection){
305     return  connection->address_type == BD_ADDR_TYPE_LE_PUBLIC ||
306     connection->address_type == BD_ADDR_TYPE_LE_RANDOM;
307 }
308 
309 /**
310  * count connections
311  */
312 static int nr_hci_connections(void){
313     int count = 0;
314     btstack_linked_item_t *it;
315     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next, count++);
316     return count;
317 }
318 
319 static int hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){
320 
321     unsigned int num_packets_sent_classic = 0;
322     unsigned int num_packets_sent_le = 0;
323 
324     btstack_linked_item_t *it;
325     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
326         hci_connection_t * connection = (hci_connection_t *) it;
327         if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
328             num_packets_sent_classic += connection->num_acl_packets_sent;
329         } else {
330             num_packets_sent_le += connection->num_acl_packets_sent;
331         }
332     }
333     log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num);
334     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
335     int free_slots_le = 0;
336 
337     if (free_slots_classic < 0){
338         log_error("hci_number_free_acl_slots: outgoing classic packets (%u) > total classic packets (%u)", num_packets_sent_classic, hci_stack->acl_packets_total_num);
339         return 0;
340     }
341 
342     if (hci_stack->le_acl_packets_total_num){
343         // if we have LE slots, they are used
344         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
345         if (free_slots_le < 0){
346             log_error("hci_number_free_acl_slots: outgoing le packets (%u) > total le packets (%u)", num_packets_sent_le, hci_stack->le_acl_packets_total_num);
347             return 0;
348         }
349     } else {
350         // otherwise, classic slots are used for LE, too
351         free_slots_classic -= num_packets_sent_le;
352         if (free_slots_classic < 0){
353             log_error("hci_number_free_acl_slots: outgoing classic + le packets (%u + %u) > total packets (%u)", num_packets_sent_classic, num_packets_sent_le, hci_stack->acl_packets_total_num);
354             return 0;
355         }
356     }
357 
358     switch (address_type){
359         case BD_ADDR_TYPE_UNKNOWN:
360             log_error("hci_number_free_acl_slots: unknown address type");
361             return 0;
362 
363         case BD_ADDR_TYPE_CLASSIC:
364             return free_slots_classic;
365 
366         default:
367            if (hci_stack->le_acl_packets_total_num){
368                return free_slots_le;
369            }
370            return free_slots_classic;
371     }
372 }
373 
374 int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
375     // get connection type
376     hci_connection_t * connection = hci_connection_for_handle(con_handle);
377     if (!connection){
378         log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
379         return 0;
380     }
381     return hci_number_free_acl_slots_for_connection_type(connection->address_type);
382 }
383 
384 #ifdef ENABLE_CLASSIC
385 static int hci_number_free_sco_slots(void){
386     unsigned int num_sco_packets_sent  = 0;
387     btstack_linked_item_t *it;
388     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
389         hci_connection_t * connection = (hci_connection_t *) it;
390         num_sco_packets_sent += connection->num_sco_packets_sent;
391     }
392     if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
393         log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num);
394         return 0;
395     }
396     // log_info("hci_number_free_sco_slots u", handle, num_sco_packets_sent);
397     return hci_stack->sco_packets_total_num - num_sco_packets_sent;
398 }
399 #endif
400 
401 // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
402 int hci_can_send_command_packet_now(void){
403     if (hci_stack->hci_packet_buffer_reserved) return 0;
404 
405     // check for async hci transport implementations
406     if (hci_stack->hci_transport->can_send_packet_now){
407         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
408             return 0;
409         }
410     }
411 
412     return hci_stack->num_cmd_packets > 0;
413 }
414 
415 static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){
416     // check for async hci transport implementations
417     if (!hci_stack->hci_transport->can_send_packet_now) return 1;
418     return hci_stack->hci_transport->can_send_packet_now(packet_type);
419 }
420 
421 static int hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){
422     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
423     return hci_number_free_acl_slots_for_connection_type(address_type) > 0;
424 }
425 
426 int hci_can_send_acl_le_packet_now(void){
427     if (hci_stack->hci_packet_buffer_reserved) return 0;
428     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC);
429 }
430 
431 int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
432     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
433     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
434 }
435 
436 int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
437     if (hci_stack->hci_packet_buffer_reserved) return 0;
438     return hci_can_send_prepared_acl_packet_now(con_handle);
439 }
440 
441 #ifdef ENABLE_CLASSIC
442 int hci_can_send_acl_classic_packet_now(void){
443     if (hci_stack->hci_packet_buffer_reserved) return 0;
444     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_CLASSIC);
445 }
446 
447 int hci_can_send_prepared_sco_packet_now(void){
448     if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return 0;
449     if (!hci_stack->synchronous_flow_control_enabled) return 1;
450     return hci_number_free_sco_slots() > 0;
451 }
452 
453 int hci_can_send_sco_packet_now(void){
454     if (hci_stack->hci_packet_buffer_reserved) return 0;
455     return hci_can_send_prepared_sco_packet_now();
456 }
457 
458 void hci_request_sco_can_send_now_event(void){
459     hci_stack->sco_waiting_for_can_send_now = 1;
460     hci_notify_if_sco_can_send_now();
461 }
462 #endif
463 
464 // used for internal checks in l2cap.c
465 int hci_is_packet_buffer_reserved(void){
466     return hci_stack->hci_packet_buffer_reserved;
467 }
468 
469 // reserves outgoing packet buffer. @returns 1 if successful
470 int hci_reserve_packet_buffer(void){
471     if (hci_stack->hci_packet_buffer_reserved) {
472         log_error("hci_reserve_packet_buffer called but buffer already reserved");
473         return 0;
474     }
475     hci_stack->hci_packet_buffer_reserved = 1;
476     return 1;
477 }
478 
479 void hci_release_packet_buffer(void){
480     hci_stack->hci_packet_buffer_reserved = 0;
481 }
482 
483 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
484 static int hci_transport_synchronous(void){
485     return hci_stack->hci_transport->can_send_packet_now == NULL;
486 }
487 
488 static int hci_send_acl_packet_fragments(hci_connection_t *connection){
489 
490     // log_info("hci_send_acl_packet_fragments  %u/%u (con 0x%04x)", hci_stack->acl_fragmentation_pos, hci_stack->acl_fragmentation_total_size, connection->con_handle);
491 
492     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
493     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
494     if (hci_is_le_connection(connection) && hci_stack->le_data_packets_length > 0){
495         max_acl_data_packet_length = hci_stack->le_data_packets_length;
496     }
497 
498     // testing: reduce buffer to minimum
499     // max_acl_data_packet_length = 52;
500 
501     log_debug("hci_send_acl_packet_fragments entered");
502 
503     int err;
504     // multiple packets could be send on a synchronous HCI transport
505     while (1){
506 
507         log_debug("hci_send_acl_packet_fragments loop entered");
508 
509         // get current data
510         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4;
511         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
512         int more_fragments = 0;
513 
514         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
515         if (current_acl_data_packet_length > max_acl_data_packet_length){
516             more_fragments = 1;
517             current_acl_data_packet_length = max_acl_data_packet_length;
518         }
519 
520         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
521         if (acl_header_pos > 0){
522             uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
523             handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12);
524             little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
525         }
526 
527         // update header len
528         little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length);
529 
530         // count packet
531         connection->num_acl_packets_sent++;
532         log_debug("hci_send_acl_packet_fragments loop before send (more fragments %d)", more_fragments);
533 
534         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
535         if (more_fragments){
536             // update start of next fragment to send
537             hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
538         } else {
539             // done
540             hci_stack->acl_fragmentation_pos = 0;
541             hci_stack->acl_fragmentation_total_size = 0;
542         }
543 
544         // send packet
545         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
546         const int size = current_acl_data_packet_length + 4;
547         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
548         err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
549 
550         log_debug("hci_send_acl_packet_fragments loop after send (more fragments %d)", more_fragments);
551 
552         // done yet?
553         if (!more_fragments) break;
554 
555         // can send more?
556         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
557     }
558 
559     log_debug("hci_send_acl_packet_fragments loop over");
560 
561     // release buffer now for synchronous transport
562     if (hci_transport_synchronous()){
563         hci_release_packet_buffer();
564         // notify upper stack that it might be possible to send again
565         uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
566         hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
567     }
568 
569     return err;
570 }
571 
572 // pre: caller has reserved the packet buffer
573 int hci_send_acl_packet_buffer(int size){
574 
575     // log_info("hci_send_acl_packet_buffer size %u", size);
576 
577     if (!hci_stack->hci_packet_buffer_reserved) {
578         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
579         return 0;
580     }
581 
582     uint8_t * packet = hci_stack->hci_packet_buffer;
583     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
584 
585     // check for free places on Bluetooth module
586     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
587         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
588         hci_release_packet_buffer();
589         return BTSTACK_ACL_BUFFERS_FULL;
590     }
591 
592     hci_connection_t *connection = hci_connection_for_handle( con_handle);
593     if (!connection) {
594         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
595         hci_release_packet_buffer();
596         return 0;
597     }
598 
599 #ifdef ENABLE_CLASSIC
600     hci_connection_timestamp(connection);
601 #endif
602 
603     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
604 
605     // setup data
606     hci_stack->acl_fragmentation_total_size = size;
607     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
608 
609     return hci_send_acl_packet_fragments(connection);
610 }
611 
612 #ifdef ENABLE_CLASSIC
613 // pre: caller has reserved the packet buffer
614 int hci_send_sco_packet_buffer(int size){
615 
616     // log_info("hci_send_acl_packet_buffer size %u", size);
617 
618     if (!hci_stack->hci_packet_buffer_reserved) {
619         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
620         return 0;
621     }
622 
623     uint8_t * packet = hci_stack->hci_packet_buffer;
624 
625     // skip checks in loopback mode
626     if (!hci_stack->loopback_mode){
627         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);   // same for ACL and SCO
628 
629         // check for free places on Bluetooth module
630         if (!hci_can_send_prepared_sco_packet_now()) {
631             log_error("hci_send_sco_packet_buffer called but no free ACL buffers on controller");
632             hci_release_packet_buffer();
633             return BTSTACK_ACL_BUFFERS_FULL;
634         }
635 
636         // track send packet in connection struct
637         hci_connection_t *connection = hci_connection_for_handle( con_handle);
638         if (!connection) {
639             log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle);
640             hci_release_packet_buffer();
641             return 0;
642         }
643         connection->num_sco_packets_sent++;
644     }
645 
646     hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
647     int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
648 
649     if (hci_transport_synchronous()){
650         hci_release_packet_buffer();
651         // notify upper stack that it might be possible to send again
652         uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
653         hci_emit_event(&event[0], sizeof(event), 0);    // don't dump
654     }
655 
656     return err;
657 }
658 #endif
659 
660 static void acl_handler(uint8_t *packet, int size){
661 
662     // log_info("acl_handler: size %u", size);
663 
664     // get info
665     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
666     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
667     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
668     uint16_t acl_length         = READ_ACL_LENGTH(packet);
669 
670     // ignore non-registered handle
671     if (!conn){
672         log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle);
673         return;
674     }
675 
676     // assert packet is complete
677     if (acl_length + 4 != size){
678         log_error("hci.c: acl_handler called with ACL packet of wrong size %d, expected %u => dropping packet", size, acl_length + 4);
679         return;
680     }
681 
682 #ifdef ENABLE_CLASSIC
683     // update idle timestamp
684     hci_connection_timestamp(conn);
685 #endif
686 
687     // handle different packet types
688     switch (acl_flags & 0x03) {
689 
690         case 0x01: // continuation fragment
691 
692             // sanity checks
693             if (conn->acl_recombination_pos == 0) {
694                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
695                 return;
696             }
697             if (conn->acl_recombination_pos + acl_length > 4 + HCI_ACL_BUFFER_SIZE){
698                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
699                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
700                 conn->acl_recombination_pos = 0;
701                 return;
702             }
703 
704             // append fragment payload (header already stored)
705             memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos], &packet[4], acl_length );
706             conn->acl_recombination_pos += acl_length;
707 
708             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length,
709             //        conn->acl_recombination_pos, conn->acl_recombination_length);
710 
711             // forward complete L2CAP packet if complete.
712             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
713                 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
714                 // reset recombination buffer
715                 conn->acl_recombination_length = 0;
716                 conn->acl_recombination_pos = 0;
717             }
718             break;
719 
720         case 0x02: { // first fragment
721 
722             // sanity check
723             if (conn->acl_recombination_pos) {
724                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
725                 conn->acl_recombination_pos = 0;
726             }
727 
728             // peek into L2CAP packet!
729             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
730 
731             // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length);
732 
733             // compare fragment size to L2CAP packet size
734             if (acl_length >= l2cap_length + 4){
735                 // forward fragment as L2CAP packet
736                 hci_emit_acl_packet(packet, acl_length + 4);
737             } else {
738 
739                 if (acl_length > HCI_ACL_BUFFER_SIZE){
740                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
741                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
742                     return;
743                 }
744 
745                 // store first fragment and tweak acl length for complete package
746                 memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], packet, acl_length + 4);
747                 conn->acl_recombination_pos    = acl_length + 4;
748                 conn->acl_recombination_length = l2cap_length;
749                 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2, l2cap_length +4);
750             }
751             break;
752 
753         }
754         default:
755             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
756             return;
757     }
758 
759     // execute main loop
760     hci_run();
761 }
762 
763 static void hci_shutdown_connection(hci_connection_t *conn){
764     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
765 
766 #ifdef ENABLE_SCO_OVER_HCI
767     int addr_type = conn->address_type;
768 #endif
769 
770     btstack_run_loop_remove_timer(&conn->timeout);
771 
772     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
773     btstack_memory_hci_connection_free( conn );
774 
775     // now it's gone
776     hci_emit_nr_connections_changed();
777 
778     // update SCO
779     if (addr_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
780         hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
781     }
782 }
783 
784 #ifdef ENABLE_CLASSIC
785 
786 static const uint16_t packet_type_sizes[] = {
787     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
788     HCI_ACL_DH1_SIZE, 0, 0, 0,
789     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
790     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
791 };
792 static const uint8_t  packet_type_feature_requirement_bit[] = {
793      0, // 3 slot packets
794      1, // 5 slot packets
795     25, // EDR 2 mpbs
796     26, // EDR 3 mbps
797     39, // 3 slot EDR packts
798     40, // 5 slot EDR packet
799 };
800 static const uint16_t packet_type_feature_packet_mask[] = {
801     0x0f00, // 3 slot packets
802     0xf000, // 5 slot packets
803     0x1102, // EDR 2 mpbs
804     0x2204, // EDR 3 mbps
805     0x0300, // 3 slot EDR packts
806     0x3000, // 5 slot EDR packet
807 };
808 
809 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
810     // enable packet types based on size
811     uint16_t packet_types = 0;
812     unsigned int i;
813     for (i=0;i<16;i++){
814         if (packet_type_sizes[i] == 0) continue;
815         if (packet_type_sizes[i] <= buffer_size){
816             packet_types |= 1 << i;
817         }
818     }
819     // disable packet types due to missing local supported features
820     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
821         unsigned int bit_idx = packet_type_feature_requirement_bit[i];
822         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
823         if (feature_set) continue;
824         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
825         packet_types &= ~packet_type_feature_packet_mask[i];
826     }
827     // flip bits for "may not be used"
828     packet_types ^= 0x3306;
829     return packet_types;
830 }
831 
832 uint16_t hci_usable_acl_packet_types(void){
833     return hci_stack->packet_types;
834 }
835 #endif
836 
837 uint8_t* hci_get_outgoing_packet_buffer(void){
838     // hci packet buffer is >= acl data packet length
839     return hci_stack->hci_packet_buffer;
840 }
841 
842 uint16_t hci_max_acl_data_packet_length(void){
843     return hci_stack->acl_data_packet_length;
844 }
845 
846 #ifdef ENABLE_CLASSIC
847 int hci_extended_sco_link_supported(void){
848     // No. 31, byte 3, bit 7
849     return (hci_stack->local_supported_features[3] & (1 << 7)) != 0;
850 }
851 #endif
852 
853 int hci_non_flushable_packet_boundary_flag_supported(void){
854     // No. 54, byte 6, bit 6
855     return (hci_stack->local_supported_features[6] & (1 << 6)) != 0;
856 }
857 
858 static int gap_ssp_supported(void){
859     // No. 51, byte 6, bit 3
860     return (hci_stack->local_supported_features[6] & (1 << 3)) != 0;
861 }
862 
863 static int hci_classic_supported(void){
864 #ifdef ENABLE_CLASSIC
865     // No. 37, byte 4, bit 5, = No BR/EDR Support
866     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
867 #else
868     return 0;
869 #endif
870 }
871 
872 static int hci_le_supported(void){
873 #ifdef ENABLE_BLE
874     // No. 37, byte 4, bit 6 = LE Supported (Controller)
875     return (hci_stack->local_supported_features[4] & (1 << 6)) != 0;
876 #else
877     return 0;
878 #endif
879 }
880 
881 #ifdef ENABLE_BLE
882 
883 /**
884  * @brief Get addr type and address used for LE in Advertisements, Scan Responses,
885  */
886 void gap_le_get_own_address(uint8_t * addr_type, bd_addr_t addr){
887     *addr_type = hci_stack->le_own_addr_type;
888     if (hci_stack->le_own_addr_type){
889         memcpy(addr, hci_stack->le_random_address, 6);
890     } else {
891         memcpy(addr, hci_stack->local_bd_addr, 6);
892     }
893 }
894 
895 #ifdef ENABLE_LE_CENTRAL
896 void le_handle_advertisement_report(uint8_t *packet, int size){
897 
898     UNUSED(size);
899 
900     int offset = 3;
901     int num_reports = packet[offset];
902     offset += 1;
903 
904     int i;
905     // log_info("HCI: handle adv report with num reports: %d", num_reports);
906     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
907     for (i=0; i<num_reports;i++){
908         uint8_t data_length = packet[offset + 8];
909         uint8_t event_size = 10 + data_length;
910         int pos = 0;
911         event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
912         event[pos++] = event_size;
913         memcpy(&event[pos], &packet[offset], 1+1+6); // event type + address type + address
914         offset += 8;
915         pos += 8;
916         event[pos++] = packet[offset + 1 + data_length]; // rssi
917         event[pos++] = packet[offset++]; //data_length;
918         memcpy(&event[pos], &packet[offset], data_length);
919         pos += data_length;
920         offset += data_length + 1; // rssi
921         hci_emit_event(event, pos, 1);
922     }
923 }
924 #endif
925 #endif
926 
927 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
928 
929 static uint32_t hci_transport_uart_get_main_baud_rate(void){
930     if (!hci_stack->config) return 0;
931     uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
932     // Limit baud rate for Broadcom chipsets to 3 mbps
933     if (hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION && baud_rate > 3000000){
934         baud_rate = 3000000;
935     }
936     return baud_rate;
937 }
938 
939 static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){
940     UNUSED(ds);
941 
942     switch (hci_stack->substate){
943         case HCI_INIT_W4_SEND_RESET:
944             log_info("Resend HCI Reset");
945             hci_stack->substate = HCI_INIT_SEND_RESET;
946             hci_stack->num_cmd_packets = 1;
947             hci_run();
948             break;
949         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET:
950             log_info("Resend HCI Reset - CSR Warm Boot with Link Reset");
951             if (hci_stack->hci_transport->reset_link){
952                 hci_stack->hci_transport->reset_link();
953             }
954             // no break - explicit fallthrough to HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT
955         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
956             log_info("Resend HCI Reset - CSR Warm Boot");
957             hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
958             hci_stack->num_cmd_packets = 1;
959             hci_run();
960             break;
961         case HCI_INIT_W4_SEND_BAUD_CHANGE:
962             if (hci_stack->hci_transport->set_baudrate){
963                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
964                 log_info("Local baud rate change to %"PRIu32"(timeout handler)", baud_rate);
965                 hci_stack->hci_transport->set_baudrate(baud_rate);
966             }
967             // For CSR, HCI Reset is sent on new baud rate
968             if (hci_stack->manufacturer == COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
969                 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
970                 hci_run();
971             }
972             break;
973         default:
974             break;
975     }
976 }
977 #endif
978 
979 static void hci_initializing_next_state(void){
980     hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1);
981 }
982 
983 // assumption: hci_can_send_command_packet_now() == true
984 static void hci_initializing_run(void){
985     log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now());
986     switch (hci_stack->substate){
987         case HCI_INIT_SEND_RESET:
988             hci_state_reset();
989 
990 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
991             // prepare reset if command complete not received in 100ms
992             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
993             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
994             btstack_run_loop_add_timer(&hci_stack->timeout);
995 #endif
996             // send command
997             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
998             hci_send_cmd(&hci_reset);
999             break;
1000         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
1001             hci_send_cmd(&hci_read_local_version_information);
1002             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
1003             break;
1004         case HCI_INIT_SEND_READ_LOCAL_NAME:
1005             hci_send_cmd(&hci_read_local_name);
1006             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME;
1007             break;
1008 
1009 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1010         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1011             hci_state_reset();
1012             // prepare reset if command complete not received in 100ms
1013             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1014             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1015             btstack_run_loop_add_timer(&hci_stack->timeout);
1016             // send command
1017             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1018             hci_send_cmd(&hci_reset);
1019             break;
1020         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
1021             hci_state_reset();
1022             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
1023             hci_send_cmd(&hci_reset);
1024             break;
1025         case HCI_INIT_SEND_BAUD_CHANGE: {
1026             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1027             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1028             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1029             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1030             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1031             // STLC25000D: baudrate change happens within 0.5 s after command was send,
1032             // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
1033             if (hci_stack->manufacturer == COMPANY_ID_ST_MICROELECTRONICS){
1034                 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1035                 btstack_run_loop_add_timer(&hci_stack->timeout);
1036             }
1037             break;
1038         }
1039         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
1040             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1041             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1042             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1043             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
1044             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1045             break;
1046         }
1047         case HCI_INIT_CUSTOM_INIT:
1048             // Custom initialization
1049             if (hci_stack->chipset && hci_stack->chipset->next_command){
1050                 int valid_cmd = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
1051                 if (valid_cmd){
1052                     int size = 3 + hci_stack->hci_packet_buffer[2];
1053                     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1054                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
1055                     switch (valid_cmd) {
1056                         case 1:
1057                         default:
1058                             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
1059                             break;
1060                         case 2: // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
1061                             log_info("CSR Warm Boot");
1062                             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1063                             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1064                             btstack_run_loop_add_timer(&hci_stack->timeout);
1065                             if (hci_stack->manufacturer == COMPANY_ID_CAMBRIDGE_SILICON_RADIO
1066                                 && hci_stack->config
1067                                 && hci_stack->chipset
1068                                 // && hci_stack->chipset->set_baudrate_command -- there's no such command
1069                                 && hci_stack->hci_transport->set_baudrate
1070                                 && hci_transport_uart_get_main_baud_rate()){
1071                                 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1072                             } else {
1073                                hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET;
1074                             }
1075                             break;
1076                     }
1077                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
1078                     break;
1079                 }
1080                 log_info("Init script done");
1081 
1082                 // Init script download causes baud rate to reset on Broadcom chipsets, restore UART baud rate if needed
1083                 if (hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION){
1084                     int need_baud_change = hci_stack->config
1085                         && hci_stack->chipset
1086                         && hci_stack->chipset->set_baudrate_command
1087                         && hci_stack->hci_transport->set_baudrate
1088                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1089                     if (need_baud_change) {
1090                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
1091                         log_info("Local baud rate change to %"PRIu32" after init script (bcm)", baud_rate);
1092                         hci_stack->hci_transport->set_baudrate(baud_rate);
1093                     }
1094                 }
1095             }
1096             // otherwise continue
1097             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1098             hci_send_cmd(&hci_read_local_supported_commands);
1099             break;
1100         case HCI_INIT_SET_BD_ADDR:
1101             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
1102             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1103             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1104             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
1105             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1106             break;
1107 #endif
1108 
1109         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
1110             log_info("Resend hci_read_local_supported_commands after CSR Warm Boot double reset");
1111             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1112             hci_send_cmd(&hci_read_local_supported_commands);
1113             break;
1114         case HCI_INIT_READ_BD_ADDR:
1115             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
1116             hci_send_cmd(&hci_read_bd_addr);
1117             break;
1118         case HCI_INIT_READ_BUFFER_SIZE:
1119             hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
1120             hci_send_cmd(&hci_read_buffer_size);
1121             break;
1122         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
1123             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
1124             hci_send_cmd(&hci_read_local_supported_features);
1125             break;
1126         case HCI_INIT_SET_EVENT_MASK:
1127             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
1128             if (hci_le_supported()){
1129                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
1130             } else {
1131                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
1132                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
1133             }
1134             break;
1135 #ifdef ENABLE_CLASSIC
1136         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
1137             hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
1138             hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
1139             break;
1140         case HCI_INIT_WRITE_PAGE_TIMEOUT:
1141             hci_stack->substate = HCI_INIT_W4_WRITE_PAGE_TIMEOUT;
1142             hci_send_cmd(&hci_write_page_timeout, 0x6000);  // ca. 15 sec
1143             break;
1144         case HCI_INIT_WRITE_CLASS_OF_DEVICE:
1145             hci_stack->substate = HCI_INIT_W4_WRITE_CLASS_OF_DEVICE;
1146             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1147             break;
1148         case HCI_INIT_WRITE_LOCAL_NAME:
1149             hci_stack->substate = HCI_INIT_W4_WRITE_LOCAL_NAME;
1150             if (hci_stack->local_name){
1151                 hci_send_cmd(&hci_write_local_name, hci_stack->local_name);
1152             } else {
1153                 char local_name[8+17+1];
1154                 // BTstack 11:22:33:44:55:66
1155                 memcpy(local_name, "BTstack ", 8);
1156                 memcpy(&local_name[8], bd_addr_to_str(hci_stack->local_bd_addr), 17);   // strlen(bd_addr_to_str(...)) = 17
1157                 local_name[8+17] = '\0';
1158                 log_info("---> Name %s", local_name);
1159                 hci_send_cmd(&hci_write_local_name, local_name);
1160             }
1161             break;
1162         case HCI_INIT_WRITE_EIR_DATA:
1163             hci_stack->substate = HCI_INIT_W4_WRITE_EIR_DATA;
1164             hci_send_cmd(&hci_write_extended_inquiry_response, 0, hci_stack->eir_data);
1165             break;
1166         case HCI_INIT_WRITE_INQUIRY_MODE:
1167             hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE;
1168             hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode);
1169             break;
1170         case HCI_INIT_WRITE_SCAN_ENABLE:
1171             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
1172             hci_stack->substate = HCI_INIT_W4_WRITE_SCAN_ENABLE;
1173             break;
1174         // only sent if ENABLE_SCO_OVER_HCI is defined
1175         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1176             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1177             hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
1178             break;
1179         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1180             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1181             hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
1182             break;
1183         // only sent if ENABLE_SCO_OVER_HCI and manufacturer is Broadcom
1184         case HCI_INIT_BCM_WRITE_SCO_PCM_INT:
1185             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1186             log_info("BCM: Route SCO data via HCI transport");
1187             hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0);
1188             break;
1189 
1190 #endif
1191 #ifdef ENABLE_BLE
1192         // LE INIT
1193         case HCI_INIT_LE_READ_BUFFER_SIZE:
1194             hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
1195             hci_send_cmd(&hci_le_read_buffer_size);
1196             break;
1197         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
1198             // LE Supported Host = 1, Simultaneous Host = 0
1199             hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
1200             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
1201             break;
1202 #ifdef ENABLE_LE_CENTRAL
1203         case HCI_INIT_READ_WHITE_LIST_SIZE:
1204             hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
1205             hci_send_cmd(&hci_le_read_white_list_size);
1206             break;
1207         case HCI_INIT_LE_SET_SCAN_PARAMETERS:
1208             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, own address type, accept all advs
1209             hci_stack->substate = HCI_INIT_W4_LE_SET_SCAN_PARAMETERS;
1210             hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, hci_stack->le_own_addr_type, 0);
1211             break;
1212 #endif
1213 #endif
1214         default:
1215             return;
1216     }
1217 }
1218 
1219 static void hci_init_done(void){
1220     // done. tell the app
1221     log_info("hci_init_done -> HCI_STATE_WORKING");
1222     hci_stack->state = HCI_STATE_WORKING;
1223     hci_emit_state();
1224     hci_run();
1225 }
1226 
1227 static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
1228     UNUSED(size);
1229 
1230     uint8_t command_completed = 0;
1231 
1232     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
1233         uint16_t opcode = little_endian_read_16(packet,3);
1234         if (opcode == hci_stack->last_cmd_opcode){
1235             command_completed = 1;
1236             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
1237         } else {
1238             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
1239         }
1240     }
1241 
1242     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
1243         uint8_t  status = packet[2];
1244         uint16_t opcode = little_endian_read_16(packet,4);
1245         if (opcode == hci_stack->last_cmd_opcode){
1246             if (status){
1247                 command_completed = 1;
1248                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
1249             } else {
1250                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
1251             }
1252         } else {
1253             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
1254         }
1255     }
1256 
1257 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1258 
1259     // Vendor == CSR
1260     if (hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
1261         // TODO: track actual command
1262         command_completed = 1;
1263     }
1264 
1265     // Vendor == Toshiba
1266     if (hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
1267         // TODO: track actual command
1268         command_completed = 1;
1269     }
1270 
1271     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
1272     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
1273     //
1274     // HCI Reset
1275     // Timeout 100 ms
1276     // HCI Reset
1277     // Command Complete Reset
1278     // HCI Read Local Version Information
1279     // Command Complete Reset - but we expected Command Complete Read Local Version Information
1280     // hang...
1281     //
1282     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1283     if (!command_completed
1284             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
1285             && hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION){
1286 
1287         uint16_t opcode = little_endian_read_16(packet,3);
1288         if (opcode == hci_reset.opcode){
1289             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
1290             return;
1291         }
1292     }
1293 
1294     // CSR & H5
1295     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1296     if (!command_completed
1297             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
1298             && hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS){
1299 
1300         uint16_t opcode = little_endian_read_16(packet,3);
1301         if (opcode == hci_reset.opcode){
1302             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1303             return;
1304         }
1305     }
1306 
1307     // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT
1308     // fix: Correct substate and behave as command below
1309     if (command_completed){
1310         switch (hci_stack->substate){
1311             case HCI_INIT_SEND_RESET:
1312                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1313                 break;
1314             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1315                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1316                 break;
1317             default:
1318                 break;
1319         }
1320     }
1321 
1322 #endif
1323 
1324     if (!command_completed) return;
1325 
1326     int need_baud_change = 0;
1327     int need_addr_change = 0;
1328 
1329 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1330     need_baud_change = hci_stack->config
1331                         && hci_stack->chipset
1332                         && hci_stack->chipset->set_baudrate_command
1333                         && hci_stack->hci_transport->set_baudrate
1334                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1335 
1336     need_addr_change = hci_stack->custom_bd_addr_set
1337                         && hci_stack->chipset
1338                         && hci_stack->chipset->set_bd_addr_command;
1339 #endif
1340 
1341     switch(hci_stack->substate){
1342 
1343 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1344         case HCI_INIT_SEND_RESET:
1345             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
1346             // fix: just correct substate and behave as command below
1347             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1348             btstack_run_loop_remove_timer(&hci_stack->timeout);
1349             break;
1350         case HCI_INIT_W4_SEND_RESET:
1351             btstack_run_loop_remove_timer(&hci_stack->timeout);
1352             break;
1353         case HCI_INIT_W4_SEND_READ_LOCAL_NAME:
1354             log_info("Received local name, need baud change %d", need_baud_change);
1355             if (need_baud_change){
1356                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE;
1357                 return;
1358             }
1359             // skip baud change
1360             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1361             return;
1362         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1363             // for STLC2500D, baud rate change already happened.
1364             // for others, baud rate gets changed now
1365             if ((hci_stack->manufacturer != COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
1366                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1367                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change)", baud_rate);
1368                 hci_stack->hci_transport->set_baudrate(baud_rate);
1369             }
1370             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1371             return;
1372         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1373             btstack_run_loop_remove_timer(&hci_stack->timeout);
1374             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1375             return;
1376         case HCI_INIT_W4_CUSTOM_INIT:
1377             // repeat custom init
1378             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1379             return;
1380 #else
1381         case HCI_INIT_W4_SEND_RESET:
1382             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1383             return ;
1384 #endif
1385 
1386         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
1387             if (need_baud_change && hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION){
1388                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
1389                 return;
1390             }
1391             if (need_addr_change){
1392                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1393                 return;
1394             }
1395             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1396             return;
1397 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1398         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
1399             if (need_baud_change){
1400                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1401                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change_bcm))", baud_rate);
1402                 hci_stack->hci_transport->set_baudrate(baud_rate);
1403             }
1404             if (need_addr_change){
1405                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1406                 return;
1407             }
1408             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1409             return;
1410         case HCI_INIT_W4_SET_BD_ADDR:
1411             // for STLC2500D, bd addr change only gets active after sending reset command
1412             if (hci_stack->manufacturer == COMPANY_ID_ST_MICROELECTRONICS){
1413                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
1414                 return;
1415             }
1416             // skipping st warm boot
1417             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1418             return;
1419         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
1420             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1421             return;
1422 #endif
1423         case HCI_INIT_W4_READ_BD_ADDR:
1424             // only read buffer size if supported
1425             if (hci_stack->local_supported_commands[0] & 0x01) {
1426                 hci_stack->substate = HCI_INIT_READ_BUFFER_SIZE;
1427                 return;
1428             }
1429             // skipping read buffer size
1430             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES;
1431             return;
1432         case HCI_INIT_W4_SET_EVENT_MASK:
1433             // skip Classic init commands for LE only chipsets
1434             if (!hci_classic_supported()){
1435 #ifdef ENABLE_BLE
1436                 if (hci_le_supported()){
1437                     hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE; // skip all classic command
1438                     return;
1439                 }
1440 #endif
1441                 log_error("Neither BR/EDR nor LE supported");
1442                 hci_init_done();
1443                 return;
1444             }
1445             if (!gap_ssp_supported()){
1446                 hci_stack->substate = HCI_INIT_WRITE_PAGE_TIMEOUT;
1447                 return;
1448             }
1449             break;
1450 #ifdef ENABLE_BLE
1451         case HCI_INIT_W4_LE_READ_BUFFER_SIZE:
1452             // skip write le host if not supported (e.g. on LE only EM9301)
1453             if (hci_stack->local_supported_commands[0] & 0x02) break;
1454 #ifdef ENABLE_LE_CENTRAL
1455             hci_stack->substate = HCI_INIT_READ_WHITE_LIST_SIZE;
1456 #else
1457             hci_init_done();
1458 #endif
1459             return;
1460 #endif
1461         case HCI_INIT_W4_WRITE_LOCAL_NAME:
1462             // skip write eir data if no eir data set
1463             if (hci_stack->eir_data) break;
1464             hci_stack->substate = HCI_INIT_WRITE_INQUIRY_MODE;
1465             return;
1466 
1467 #ifdef ENABLE_SCO_OVER_HCI
1468         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1469             // skip write synchronous flow control if not supported
1470             if (hci_stack->local_supported_commands[0] & 0x04) break;
1471             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1472             // explicit fall through to reduce repetitions
1473 
1474         case HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1475             // skip write default erroneous data reporting if not supported
1476             if (hci_stack->local_supported_commands[0] & 0x08) break;
1477             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1478             // explicit fall through to reduce repetitions
1479 
1480         case HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1481             // skip bcm set sco pcm config on non-Broadcom chipsets
1482             if (hci_stack->manufacturer == COMPANY_ID_BROADCOM_CORPORATION) break;
1483             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1484             // explicit fall through to reduce repetitions
1485 
1486         case HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT:
1487             if (!hci_le_supported()){
1488                 // SKIP LE init for Classic only configuration
1489                 hci_init_done();
1490                 return;
1491             }
1492             break;
1493 #else
1494         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1495             if (!hci_le_supported()){
1496                 // SKIP LE init for Classic only configuration
1497                 hci_init_done();
1498                 return;
1499             }
1500 #endif
1501             break;
1502         // Response to command before init done state -> init done
1503         case (HCI_INIT_DONE-1):
1504             hci_init_done();
1505             return;
1506 
1507         default:
1508             break;
1509     }
1510     hci_initializing_next_state();
1511 }
1512 
1513 static void event_handler(uint8_t *packet, int size){
1514 
1515     uint16_t event_length = packet[1];
1516 
1517     // assert packet is complete
1518     if (size != event_length + 2){
1519         log_error("hci.c: event_handler called with event packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
1520         return;
1521     }
1522 
1523     bd_addr_t addr;
1524     bd_addr_type_t addr_type;
1525     uint8_t link_type;
1526     hci_con_handle_t handle;
1527     hci_connection_t * conn;
1528     int i;
1529 
1530     // warnings
1531     (void) link_type;
1532 
1533     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
1534 
1535     switch (hci_event_packet_get_type(packet)) {
1536 
1537         case HCI_EVENT_COMMAND_COMPLETE:
1538             // get num cmd packets - limit to 1 to reduce complexity
1539             hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
1540 
1541             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_name)){
1542                 if (packet[5]) break;
1543                 // terminate, name 248 chars
1544                 packet[6+248] = 0;
1545                 log_info("local name: %s", &packet[6]);
1546             }
1547             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_buffer_size)){
1548                 // from offset 5
1549                 // status
1550                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
1551                 hci_stack->acl_data_packet_length = little_endian_read_16(packet, 6);
1552                 hci_stack->sco_data_packet_length = packet[8];
1553                 hci_stack->acl_packets_total_num  = little_endian_read_16(packet, 9);
1554                 hci_stack->sco_packets_total_num  = little_endian_read_16(packet, 11);
1555 
1556                 if (hci_stack->state == HCI_STATE_INITIALIZING){
1557                     // determine usable ACL payload size
1558                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){
1559                         hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
1560                     }
1561                     log_info("hci_read_buffer_size: acl used size %u, count %u / sco size %u, count %u",
1562                              hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
1563                              hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
1564                 }
1565             }
1566 #ifdef ENABLE_BLE
1567             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_buffer_size)){
1568                 hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
1569                 hci_stack->le_acl_packets_total_num  = packet[8];
1570                     // determine usable ACL payload size
1571                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
1572                         hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
1573                     }
1574                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
1575             }
1576 #ifdef ENABLE_LE_CENTRAL
1577             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_white_list_size)){
1578                 hci_stack->le_whitelist_capacity = packet[6];
1579                 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
1580             }
1581 #endif
1582 #endif
1583             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
1584                 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1],
1585 				hci_stack->local_bd_addr);
1586                 log_info("Local Address, Status: 0x%02x: Addr: %s",
1587                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
1588 #ifdef ENABLE_CLASSIC
1589                 if (hci_stack->link_key_db){
1590                     hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
1591                 }
1592 #endif
1593             }
1594 #ifdef ENABLE_CLASSIC
1595             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
1596                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1597             }
1598 #endif
1599 
1600             // Note: HCI init checks
1601             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_features)){
1602                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
1603 
1604 #ifdef ENABLE_CLASSIC
1605                 // determine usable ACL packet types based on host buffer size and supported features
1606                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
1607                 log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
1608 #endif
1609                 // Classic/LE
1610                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1611             }
1612             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_version_information)){
1613                 // hci_stack->hci_version    = little_endian_read_16(packet, 4);
1614                 // hci_stack->hci_revision   = little_endian_read_16(packet, 6);
1615                 // hci_stack->lmp_version    = little_endian_read_16(packet, 8);
1616                 hci_stack->manufacturer   = little_endian_read_16(packet, 10);
1617                 // hci_stack->lmp_subversion = little_endian_read_16(packet, 12);
1618                 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
1619             }
1620             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
1621                 hci_stack->local_supported_commands[0] =
1622                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+14] & 0x80) >> 7 |  // bit 0 = Octet 14, bit 7
1623                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+24] & 0x40) >> 5 |  // bit 1 = Octet 24, bit 6
1624                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+10] & 0x10) >> 2 |  // bit 2 = Octet 10, bit 4
1625                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+18] & 0x08);        // bit 3 = Octet 18, bit 3
1626                     log_info("Local supported commands summary 0x%02x", hci_stack->local_supported_commands[0]);
1627             }
1628 #ifdef ENABLE_CLASSIC
1629             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_synchronous_flow_control_enable)){
1630                 if (packet[5] == 0){
1631                     hci_stack->synchronous_flow_control_enabled = 1;
1632                 }
1633             }
1634 #endif
1635             break;
1636 
1637         case HCI_EVENT_COMMAND_STATUS:
1638             // get num cmd packets - limit to 1 to reduce complexity
1639             hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
1640             break;
1641 
1642         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
1643             int offset = 3;
1644             for (i=0; i<packet[2];i++){
1645                 handle = little_endian_read_16(packet, offset);
1646                 offset += 2;
1647                 uint16_t num_packets = little_endian_read_16(packet, offset);
1648                 offset += 2;
1649 
1650                 conn = hci_connection_for_handle(handle);
1651                 if (!conn){
1652                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
1653                     continue;
1654                 }
1655 
1656                 if (conn->address_type == BD_ADDR_TYPE_SCO){
1657 #ifdef ENABLE_CLASSIC
1658                     if (conn->num_sco_packets_sent >= num_packets){
1659                         conn->num_sco_packets_sent -= num_packets;
1660                     } else {
1661                         log_error("hci_number_completed_packets, more sco slots freed then sent.");
1662                         conn->num_sco_packets_sent = 0;
1663                     }
1664                     hci_notify_if_sco_can_send_now();
1665 #endif
1666                 } else {
1667                     if (conn->num_acl_packets_sent >= num_packets){
1668                         conn->num_acl_packets_sent -= num_packets;
1669                     } else {
1670                         log_error("hci_number_completed_packets, more acl slots freed then sent.");
1671                         conn->num_acl_packets_sent = 0;
1672                     }
1673                 }
1674                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
1675             }
1676             break;
1677         }
1678 
1679 #ifdef ENABLE_CLASSIC
1680         case HCI_EVENT_CONNECTION_REQUEST:
1681             reverse_bd_addr(&packet[2], addr);
1682             // TODO: eval COD 8-10
1683             link_type = packet[11];
1684             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
1685             addr_type = link_type == 1 ? BD_ADDR_TYPE_CLASSIC : BD_ADDR_TYPE_SCO;
1686             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1687             if (!conn) {
1688                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1689             }
1690             if (!conn) {
1691                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
1692                 hci_stack->decline_reason = 0x0d;
1693                 bd_addr_copy(hci_stack->decline_addr, addr);
1694                 break;
1695             }
1696             conn->role  = HCI_ROLE_SLAVE;
1697             conn->state = RECEIVED_CONNECTION_REQUEST;
1698             // store info about eSCO
1699             if (link_type == 0x02){
1700                 conn->remote_supported_feature_eSCO = 1;
1701             }
1702             hci_run();
1703             break;
1704 
1705         case HCI_EVENT_CONNECTION_COMPLETE:
1706             // Connection management
1707             reverse_bd_addr(&packet[5], addr);
1708             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1709             addr_type = BD_ADDR_TYPE_CLASSIC;
1710             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1711             if (conn) {
1712                 if (!packet[2]){
1713                     conn->state = OPEN;
1714                     conn->con_handle = little_endian_read_16(packet, 3);
1715                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
1716 
1717                     // restart timer
1718                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1719                     btstack_run_loop_add_timer(&conn->timeout);
1720 
1721                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1722 
1723                     hci_emit_nr_connections_changed();
1724                 } else {
1725                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
1726                     uint8_t status = packet[2];
1727                     bd_addr_t bd_address;
1728                     memcpy(&bd_address, conn->address, 6);
1729 
1730                     // connection failed, remove entry
1731                     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1732                     btstack_memory_hci_connection_free( conn );
1733 
1734                     // notify client if dedicated bonding
1735                     if (notify_dedicated_bonding_failed){
1736                         log_info("hci notify_dedicated_bonding_failed");
1737                         hci_emit_dedicated_bonding_result(bd_address, status);
1738                     }
1739 
1740                     // if authentication error, also delete link key
1741                     if (packet[2] == 0x05) {
1742                         gap_drop_link_key_for_bd_addr(addr);
1743                     }
1744                 }
1745             }
1746             break;
1747 
1748         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
1749             reverse_bd_addr(&packet[5], addr);
1750             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1751             if (packet[2]){
1752                 // connection failed
1753                 break;
1754             }
1755             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1756             if (!conn) {
1757                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1758             }
1759             if (!conn) {
1760                 break;
1761             }
1762             conn->state = OPEN;
1763             conn->con_handle = little_endian_read_16(packet, 3);
1764 
1765 #ifdef ENABLE_SCO_OVER_HCI
1766             // update SCO
1767             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
1768                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
1769             }
1770 #endif
1771             break;
1772 
1773         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1774             handle = little_endian_read_16(packet, 3);
1775             conn = hci_connection_for_handle(handle);
1776             if (!conn) break;
1777             if (!packet[2]){
1778                 uint8_t * features = &packet[5];
1779                 if (features[6] & (1 << 3)){
1780                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
1781                 }
1782                 if (features[3] & (1<<7)){
1783                     conn->remote_supported_feature_eSCO = 1;
1784                 }
1785             }
1786             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
1787             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x, eSCO %u", conn->bonding_flags, conn->remote_supported_feature_eSCO);
1788             if (conn->bonding_flags & BONDING_DEDICATED){
1789                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1790             }
1791             break;
1792 
1793         case HCI_EVENT_LINK_KEY_REQUEST:
1794             log_info("HCI_EVENT_LINK_KEY_REQUEST");
1795             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
1796             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
1797             if (hci_stack->bondable && !hci_stack->link_key_db) break;
1798             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
1799             hci_run();
1800             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
1801             return;
1802 
1803         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
1804             reverse_bd_addr(&packet[2], addr);
1805             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
1806             if (!conn) break;
1807             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
1808             link_key_type_t link_key_type = (link_key_type_t)packet[24];
1809             // Change Connection Encryption keeps link key type
1810             if (link_key_type != CHANGED_COMBINATION_KEY){
1811                 conn->link_key_type = link_key_type;
1812             }
1813             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
1814             // still forward event to allow dismiss of pairing dialog
1815             break;
1816         }
1817 
1818         case HCI_EVENT_PIN_CODE_REQUEST:
1819             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
1820             // non-bondable mode: pin code negative reply will be sent
1821             if (!hci_stack->bondable){
1822                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
1823                 hci_run();
1824                 return;
1825             }
1826             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
1827             if (!hci_stack->link_key_db) break;
1828             hci_event_pin_code_request_get_bd_addr(packet, addr);
1829             hci_stack->link_key_db->delete_link_key(addr);
1830             break;
1831 
1832         case HCI_EVENT_IO_CAPABILITY_REQUEST:
1833             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
1834             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
1835             break;
1836 
1837         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
1838             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1839             if (!hci_stack->ssp_auto_accept) break;
1840             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
1841             break;
1842 
1843         case HCI_EVENT_USER_PASSKEY_REQUEST:
1844             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1845             if (!hci_stack->ssp_auto_accept) break;
1846             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
1847             break;
1848 #endif
1849 
1850         case HCI_EVENT_ENCRYPTION_CHANGE:
1851             handle = little_endian_read_16(packet, 3);
1852             conn = hci_connection_for_handle(handle);
1853             if (!conn) break;
1854             if (packet[2] == 0) {
1855                 if (packet[5]){
1856                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
1857                 } else {
1858                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
1859                 }
1860             }
1861 #ifdef ENABLE_CLASSIC
1862             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1863 #endif
1864             break;
1865 
1866 #ifdef ENABLE_CLASSIC
1867         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
1868             handle = little_endian_read_16(packet, 3);
1869             conn = hci_connection_for_handle(handle);
1870             if (!conn) break;
1871 
1872             // dedicated bonding: send result and disconnect
1873             if (conn->bonding_flags & BONDING_DEDICATED){
1874                 conn->bonding_flags &= ~BONDING_DEDICATED;
1875                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
1876                 conn->bonding_status = packet[2];
1877                 break;
1878             }
1879 
1880             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
1881                 // link key sufficient for requested security
1882                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
1883                 break;
1884             }
1885             // not enough
1886             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1887             break;
1888 #endif
1889 
1890         // HCI_EVENT_DISCONNECTION_COMPLETE
1891         // has been split, to first notify stack before shutting connection down
1892         // see end of function, too.
1893         case HCI_EVENT_DISCONNECTION_COMPLETE:
1894             if (packet[2]) break;   // status != 0
1895             handle = little_endian_read_16(packet, 3);
1896             // drop outgoing ACL fragments if it is for closed connection
1897             if (hci_stack->acl_fragmentation_total_size > 0) {
1898                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
1899                     log_info("hci: drop fragmented ACL data for closed connection");
1900                      hci_stack->acl_fragmentation_total_size = 0;
1901                      hci_stack->acl_fragmentation_pos = 0;
1902                 }
1903             }
1904 
1905             // re-enable advertisements for le connections if active
1906             conn = hci_connection_for_handle(handle);
1907             if (!conn) break;
1908 #ifdef ENABLE_BLE
1909 #ifdef ENABLE_LE_PERIPHERAL
1910             if (hci_is_le_connection(conn) && hci_stack->le_advertisements_enabled){
1911                 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
1912             }
1913 #endif
1914 #endif
1915             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
1916             break;
1917 
1918         case HCI_EVENT_HARDWARE_ERROR:
1919             log_error("Hardware Error: 0x%02x", packet[2]);
1920             if (hci_stack->hardware_error_callback){
1921                 (*hci_stack->hardware_error_callback)(packet[2]);
1922             } else {
1923                 // if no special requests, just reboot stack
1924                 hci_power_control_off();
1925                 hci_power_control_on();
1926             }
1927             break;
1928 
1929 #ifdef ENABLE_CLASSIC
1930         case HCI_EVENT_ROLE_CHANGE:
1931             if (packet[2]) break;   // status != 0
1932             handle = little_endian_read_16(packet, 3);
1933             conn = hci_connection_for_handle(handle);
1934             if (!conn) break;       // no conn
1935             conn->role = packet[9];
1936             break;
1937 #endif
1938 
1939         case HCI_EVENT_TRANSPORT_PACKET_SENT:
1940             // release packet buffer only for asynchronous transport and if there are not further fragements
1941             if (hci_transport_synchronous()) {
1942                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
1943                 return; // instead of break: to avoid re-entering hci_run()
1944             }
1945             if (hci_stack->acl_fragmentation_total_size) break;
1946             hci_release_packet_buffer();
1947 
1948             // L2CAP receives this event via the hci_emit_event below
1949 
1950 #ifdef ENABLE_CLASSIC
1951             // For SCO, we do the can_send_now_check here
1952             hci_notify_if_sco_can_send_now();
1953 #endif
1954             break;
1955 
1956 #ifdef ENABLE_CLASSIC
1957         case HCI_EVENT_SCO_CAN_SEND_NOW:
1958             // For SCO, we do the can_send_now_check here
1959             hci_notify_if_sco_can_send_now();
1960             return;
1961 #endif
1962 
1963 #ifdef ENABLE_BLE
1964         case HCI_EVENT_LE_META:
1965             switch (packet[2]){
1966 #ifdef ENABLE_LE_CENTRAL
1967                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
1968                     // log_info("advertising report received");
1969                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
1970                     le_handle_advertisement_report(packet, size);
1971                     break;
1972 #endif
1973                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
1974                     // Connection management
1975                     reverse_bd_addr(&packet[8], addr);
1976                     addr_type = (bd_addr_type_t)packet[7];
1977                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
1978                     conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1979 #ifdef ENABLE_LE_CENTRAL
1980                     // if auto-connect, remove from whitelist in both roles
1981                     if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){
1982                         hci_remove_from_whitelist(addr_type, addr);
1983                     }
1984                     // handle error: error is reported only to the initiator -> outgoing connection
1985                     if (packet[3]){
1986                         // outgoing connection establishment is done
1987                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
1988                         // remove entry
1989                         if (conn){
1990                             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1991                             btstack_memory_hci_connection_free( conn );
1992                         }
1993                         break;
1994                     }
1995 #endif
1996                     // on success, both hosts receive connection complete event
1997                     if (packet[6] == HCI_ROLE_MASTER){
1998 #ifdef ENABLE_LE_CENTRAL
1999                         // if we're master, it was an outgoing connection and we're done with it
2000                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2001 #endif
2002                     } else {
2003 #ifdef ENABLE_LE_PERIPHERAL
2004                         // if we're slave, it was an incoming connection, advertisements have stopped
2005                         hci_stack->le_advertisements_active = 0;
2006                         // try to re-enable them
2007                         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
2008 #endif
2009                     }
2010                     // LE connections are auto-accepted, so just create a connection if there isn't one already
2011                     if (!conn){
2012                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2013                     }
2014                     // no memory, sorry.
2015                     if (!conn){
2016                         break;
2017                     }
2018 
2019                     conn->state = OPEN;
2020                     conn->role  = packet[6];
2021                     conn->con_handle = little_endian_read_16(packet, 4);
2022 
2023                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
2024 
2025                     // restart timer
2026                     // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2027                     // btstack_run_loop_add_timer(&conn->timeout);
2028 
2029                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2030 
2031                     hci_emit_nr_connections_changed();
2032                     break;
2033 
2034             // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
2035 
2036                 default:
2037                     break;
2038             }
2039             break;
2040 #endif
2041         default:
2042             break;
2043     }
2044 
2045     // handle BT initialization
2046     if (hci_stack->state == HCI_STATE_INITIALIZING){
2047         hci_initializing_event_handler(packet, size);
2048     }
2049 
2050     // help with BT sleep
2051     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
2052         && hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE
2053         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
2054         hci_initializing_next_state();
2055     }
2056 
2057     // notify upper stack
2058 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
2059 
2060     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
2061     if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){
2062         if (!packet[2]){
2063             handle = little_endian_read_16(packet, 3);
2064             hci_connection_t * aConn = hci_connection_for_handle(handle);
2065             if (aConn) {
2066                 uint8_t status = aConn->bonding_status;
2067                 uint16_t flags = aConn->bonding_flags;
2068                 bd_addr_t bd_address;
2069                 memcpy(&bd_address, aConn->address, 6);
2070                 hci_shutdown_connection(aConn);
2071                 // connection struct is gone, don't access anymore
2072                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
2073                     hci_emit_dedicated_bonding_result(bd_address, status);
2074                 }
2075             }
2076         }
2077     }
2078 
2079 	// execute main loop
2080 	hci_run();
2081 }
2082 
2083 #ifdef ENABLE_CLASSIC
2084 static void sco_handler(uint8_t * packet, uint16_t size){
2085     if (!hci_stack->sco_packet_handler) return;
2086     hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
2087 }
2088 #endif
2089 
2090 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
2091     hci_dump_packet(packet_type, 1, packet, size);
2092     switch (packet_type) {
2093         case HCI_EVENT_PACKET:
2094             event_handler(packet, size);
2095             break;
2096         case HCI_ACL_DATA_PACKET:
2097             acl_handler(packet, size);
2098             break;
2099 #ifdef ENABLE_CLASSIC
2100         case HCI_SCO_DATA_PACKET:
2101             sco_handler(packet, size);
2102             break;
2103 #endif
2104         default:
2105             break;
2106     }
2107 }
2108 
2109 /**
2110  * @brief Add event packet handler.
2111  */
2112 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
2113     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
2114 }
2115 
2116 
2117 /** Register HCI packet handlers */
2118 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
2119     hci_stack->acl_packet_handler = handler;
2120 }
2121 
2122 #ifdef ENABLE_CLASSIC
2123 /**
2124  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
2125  */
2126 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
2127     hci_stack->sco_packet_handler = handler;
2128 }
2129 #endif
2130 
2131 static void hci_state_reset(void){
2132     // no connections yet
2133     hci_stack->connections = NULL;
2134 
2135     // keep discoverable/connectable as this has been requested by the client(s)
2136     // hci_stack->discoverable = 0;
2137     // hci_stack->connectable = 0;
2138     // hci_stack->bondable = 1;
2139     // hci_stack->own_addr_type = 0;
2140 
2141     // buffer is free
2142     hci_stack->hci_packet_buffer_reserved = 0;
2143 
2144     // no pending cmds
2145     hci_stack->decline_reason = 0;
2146     hci_stack->new_scan_enable_value = 0xff;
2147 
2148     // LE
2149 #ifdef ENABLE_BLE
2150     memset(hci_stack->le_random_address, 0, 6);
2151     hci_stack->le_random_address_set = 0;
2152 #endif
2153 #ifdef ENABLE_LE_CENTRAL
2154     hci_stack->le_scanning_state = LE_SCAN_IDLE;
2155     hci_stack->le_scan_type = 0xff;
2156     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2157     hci_stack->le_whitelist = 0;
2158     hci_stack->le_whitelist_capacity = 0;
2159 #endif
2160 
2161     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
2162     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
2163     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
2164     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
2165     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
2166     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
2167 }
2168 
2169 #ifdef ENABLE_CLASSIC
2170 /**
2171  * @brief Configure Bluetooth hardware control. Has to be called before power on.
2172  */
2173 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
2174     // store and open remote device db
2175     hci_stack->link_key_db = link_key_db;
2176     if (hci_stack->link_key_db) {
2177         hci_stack->link_key_db->open();
2178     }
2179 }
2180 #endif
2181 
2182 void hci_init(const hci_transport_t *transport, const void *config){
2183 
2184 #ifdef HAVE_MALLOC
2185     if (!hci_stack) {
2186         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
2187     }
2188 #else
2189     hci_stack = &hci_stack_static;
2190 #endif
2191     memset(hci_stack, 0, sizeof(hci_stack_t));
2192 
2193     // reference to use transport layer implementation
2194     hci_stack->hci_transport = transport;
2195 
2196     // reference to used config
2197     hci_stack->config = config;
2198 
2199     // setup pointer for outgoing packet buffer
2200     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
2201 
2202     // max acl payload size defined in config.h
2203     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
2204 
2205     // register packet handlers with transport
2206     transport->register_packet_handler(&packet_handler);
2207 
2208     hci_stack->state = HCI_STATE_OFF;
2209 
2210     // class of device
2211     hci_stack->class_of_device = 0x007a020c; // Smartphone
2212 
2213     // bondable by default
2214     hci_stack->bondable = 1;
2215 
2216     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
2217     hci_stack->ssp_enable = 1;
2218     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
2219     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
2220     hci_stack->ssp_auto_accept = 1;
2221 
2222     // voice setting - signed 16 bit pcm data with CVSD over the air
2223     hci_stack->sco_voice_setting = 0x60;
2224 
2225     hci_state_reset();
2226 }
2227 
2228 /**
2229  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
2230  */
2231 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
2232     hci_stack->chipset = chipset_driver;
2233 
2234     // reset chipset driver - init is also called on power_up
2235     if (hci_stack->chipset && hci_stack->chipset->init){
2236         hci_stack->chipset->init(hci_stack->config);
2237     }
2238 }
2239 
2240 /**
2241  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
2242  */
2243 void hci_set_control(const btstack_control_t *hardware_control){
2244     // references to used control implementation
2245     hci_stack->control = hardware_control;
2246     // init with transport config
2247     hardware_control->init(hci_stack->config);
2248 }
2249 
2250 void hci_close(void){
2251     // close remote device db
2252     if (hci_stack->link_key_db) {
2253         hci_stack->link_key_db->close();
2254     }
2255 
2256     btstack_linked_list_iterator_t lit;
2257     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
2258     while (btstack_linked_list_iterator_has_next(&lit)){
2259         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
2260         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
2261         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
2262         hci_shutdown_connection(connection);
2263     }
2264 
2265     hci_power_control(HCI_POWER_OFF);
2266 
2267 #ifdef HAVE_MALLOC
2268     free(hci_stack);
2269 #endif
2270     hci_stack = NULL;
2271 }
2272 
2273 #ifdef ENABLE_CLASSIC
2274 void gap_set_class_of_device(uint32_t class_of_device){
2275     hci_stack->class_of_device = class_of_device;
2276 }
2277 
2278 void hci_disable_l2cap_timeout_check(void){
2279     disable_l2cap_timeouts = 1;
2280 }
2281 #endif
2282 
2283 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
2284 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
2285 void hci_set_bd_addr(bd_addr_t addr){
2286     memcpy(hci_stack->custom_bd_addr, addr, 6);
2287     hci_stack->custom_bd_addr_set = 1;
2288 }
2289 #endif
2290 
2291 // State-Module-Driver overview
2292 // state                    module  low-level
2293 // HCI_STATE_OFF             off      close
2294 // HCI_STATE_INITIALIZING,   on       open
2295 // HCI_STATE_WORKING,        on       open
2296 // HCI_STATE_HALTING,        on       open
2297 // HCI_STATE_SLEEPING,    off/sleep   close
2298 // HCI_STATE_FALLING_ASLEEP  on       open
2299 
2300 static int hci_power_control_on(void){
2301 
2302     // power on
2303     int err = 0;
2304     if (hci_stack->control && hci_stack->control->on){
2305         err = (*hci_stack->control->on)();
2306     }
2307     if (err){
2308         log_error( "POWER_ON failed");
2309         hci_emit_hci_open_failed();
2310         return err;
2311     }
2312 
2313     // int chipset driver
2314     if (hci_stack->chipset && hci_stack->chipset->init){
2315         hci_stack->chipset->init(hci_stack->config);
2316     }
2317 
2318     // init transport
2319     if (hci_stack->hci_transport->init){
2320         hci_stack->hci_transport->init(hci_stack->config);
2321     }
2322 
2323     // open transport
2324     err = hci_stack->hci_transport->open();
2325     if (err){
2326         log_error( "HCI_INIT failed, turning Bluetooth off again");
2327         if (hci_stack->control && hci_stack->control->off){
2328             (*hci_stack->control->off)();
2329         }
2330         hci_emit_hci_open_failed();
2331         return err;
2332     }
2333     return 0;
2334 }
2335 
2336 static void hci_power_control_off(void){
2337 
2338     log_info("hci_power_control_off");
2339 
2340     // close low-level device
2341     hci_stack->hci_transport->close();
2342 
2343     log_info("hci_power_control_off - hci_transport closed");
2344 
2345     // power off
2346     if (hci_stack->control && hci_stack->control->off){
2347         (*hci_stack->control->off)();
2348     }
2349 
2350     log_info("hci_power_control_off - control closed");
2351 
2352     hci_stack->state = HCI_STATE_OFF;
2353 }
2354 
2355 static void hci_power_control_sleep(void){
2356 
2357     log_info("hci_power_control_sleep");
2358 
2359 #if 0
2360     // don't close serial port during sleep
2361 
2362     // close low-level device
2363     hci_stack->hci_transport->close(hci_stack->config);
2364 #endif
2365 
2366     // sleep mode
2367     if (hci_stack->control && hci_stack->control->sleep){
2368         (*hci_stack->control->sleep)();
2369     }
2370 
2371     hci_stack->state = HCI_STATE_SLEEPING;
2372 }
2373 
2374 static int hci_power_control_wake(void){
2375 
2376     log_info("hci_power_control_wake");
2377 
2378     // wake on
2379     if (hci_stack->control && hci_stack->control->wake){
2380         (*hci_stack->control->wake)();
2381     }
2382 
2383 #if 0
2384     // open low-level device
2385     int err = hci_stack->hci_transport->open(hci_stack->config);
2386     if (err){
2387         log_error( "HCI_INIT failed, turning Bluetooth off again");
2388         if (hci_stack->control && hci_stack->control->off){
2389             (*hci_stack->control->off)();
2390         }
2391         hci_emit_hci_open_failed();
2392         return err;
2393     }
2394 #endif
2395 
2396     return 0;
2397 }
2398 
2399 static void hci_power_transition_to_initializing(void){
2400     // set up state machine
2401     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
2402     hci_stack->hci_packet_buffer_reserved = 0;
2403     hci_stack->state = HCI_STATE_INITIALIZING;
2404     hci_stack->substate = HCI_INIT_SEND_RESET;
2405 }
2406 
2407 int hci_power_control(HCI_POWER_MODE power_mode){
2408 
2409     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
2410 
2411     int err = 0;
2412     switch (hci_stack->state){
2413 
2414         case HCI_STATE_OFF:
2415             switch (power_mode){
2416                 case HCI_POWER_ON:
2417                     err = hci_power_control_on();
2418                     if (err) {
2419                         log_error("hci_power_control_on() error %d", err);
2420                         return err;
2421                     }
2422                     hci_power_transition_to_initializing();
2423                     break;
2424                 case HCI_POWER_OFF:
2425                     // do nothing
2426                     break;
2427                 case HCI_POWER_SLEEP:
2428                     // do nothing (with SLEEP == OFF)
2429                     break;
2430             }
2431             break;
2432 
2433         case HCI_STATE_INITIALIZING:
2434             switch (power_mode){
2435                 case HCI_POWER_ON:
2436                     // do nothing
2437                     break;
2438                 case HCI_POWER_OFF:
2439                     // no connections yet, just turn it off
2440                     hci_power_control_off();
2441                     break;
2442                 case HCI_POWER_SLEEP:
2443                     // no connections yet, just turn it off
2444                     hci_power_control_sleep();
2445                     break;
2446             }
2447             break;
2448 
2449         case HCI_STATE_WORKING:
2450             switch (power_mode){
2451                 case HCI_POWER_ON:
2452                     // do nothing
2453                     break;
2454                 case HCI_POWER_OFF:
2455                     // see hci_run
2456                     hci_stack->state = HCI_STATE_HALTING;
2457                     break;
2458                 case HCI_POWER_SLEEP:
2459                     // see hci_run
2460                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2461                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2462                     break;
2463             }
2464             break;
2465 
2466         case HCI_STATE_HALTING:
2467             switch (power_mode){
2468                 case HCI_POWER_ON:
2469                     hci_power_transition_to_initializing();
2470                     break;
2471                 case HCI_POWER_OFF:
2472                     // do nothing
2473                     break;
2474                 case HCI_POWER_SLEEP:
2475                     // see hci_run
2476                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2477                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2478                     break;
2479             }
2480             break;
2481 
2482         case HCI_STATE_FALLING_ASLEEP:
2483             switch (power_mode){
2484                 case HCI_POWER_ON:
2485 
2486 #ifdef HAVE_PLATFORM_IPHONE_OS
2487                     // nothing to do, if H4 supports power management
2488                     if (btstack_control_iphone_power_management_enabled()){
2489                         hci_stack->state = HCI_STATE_INITIALIZING;
2490                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
2491                         break;
2492                     }
2493 #endif
2494                     hci_power_transition_to_initializing();
2495                     break;
2496                 case HCI_POWER_OFF:
2497                     // see hci_run
2498                     hci_stack->state = HCI_STATE_HALTING;
2499                     break;
2500                 case HCI_POWER_SLEEP:
2501                     // do nothing
2502                     break;
2503             }
2504             break;
2505 
2506         case HCI_STATE_SLEEPING:
2507             switch (power_mode){
2508                 case HCI_POWER_ON:
2509 
2510 #ifdef HAVE_PLATFORM_IPHONE_OS
2511                     // nothing to do, if H4 supports power management
2512                     if (btstack_control_iphone_power_management_enabled()){
2513                         hci_stack->state = HCI_STATE_INITIALIZING;
2514                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
2515                         hci_update_scan_enable();
2516                         break;
2517                     }
2518 #endif
2519                     err = hci_power_control_wake();
2520                     if (err) return err;
2521                     hci_power_transition_to_initializing();
2522                     break;
2523                 case HCI_POWER_OFF:
2524                     hci_stack->state = HCI_STATE_HALTING;
2525                     break;
2526                 case HCI_POWER_SLEEP:
2527                     // do nothing
2528                     break;
2529             }
2530             break;
2531     }
2532 
2533     // create internal event
2534 	hci_emit_state();
2535 
2536 	// trigger next/first action
2537 	hci_run();
2538 
2539     return 0;
2540 }
2541 
2542 
2543 #ifdef ENABLE_CLASSIC
2544 
2545 static void hci_update_scan_enable(void){
2546     // 2 = page scan, 1 = inq scan
2547     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
2548     hci_run();
2549 }
2550 
2551 void gap_discoverable_control(uint8_t enable){
2552     if (enable) enable = 1; // normalize argument
2553 
2554     if (hci_stack->discoverable == enable){
2555         hci_emit_discoverable_enabled(hci_stack->discoverable);
2556         return;
2557     }
2558 
2559     hci_stack->discoverable = enable;
2560     hci_update_scan_enable();
2561 }
2562 
2563 void gap_connectable_control(uint8_t enable){
2564     if (enable) enable = 1; // normalize argument
2565 
2566     // don't emit event
2567     if (hci_stack->connectable == enable) return;
2568 
2569     hci_stack->connectable = enable;
2570     hci_update_scan_enable();
2571 }
2572 #endif
2573 
2574 void gap_local_bd_addr(bd_addr_t address_buffer){
2575     memcpy(address_buffer, hci_stack->local_bd_addr, 6);
2576 }
2577 
2578 static void hci_run(void){
2579 
2580     // log_info("hci_run: entered");
2581     btstack_linked_item_t * it;
2582 
2583     // send continuation fragments first, as they block the prepared packet buffer
2584     if (hci_stack->acl_fragmentation_total_size > 0) {
2585         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
2586         hci_connection_t *connection = hci_connection_for_handle(con_handle);
2587         if (connection) {
2588             if (hci_can_send_prepared_acl_packet_now(con_handle)){
2589                 hci_send_acl_packet_fragments(connection);
2590                 return;
2591             }
2592         } else {
2593             // connection gone -> discard further fragments
2594             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
2595             hci_stack->acl_fragmentation_total_size = 0;
2596             hci_stack->acl_fragmentation_pos = 0;
2597         }
2598     }
2599 
2600     if (!hci_can_send_command_packet_now()) return;
2601 
2602     // global/non-connection oriented commands
2603 
2604 #ifdef ENABLE_CLASSIC
2605     // decline incoming connections
2606     if (hci_stack->decline_reason){
2607         uint8_t reason = hci_stack->decline_reason;
2608         hci_stack->decline_reason = 0;
2609         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
2610         return;
2611     }
2612 
2613     // send scan enable
2614     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
2615         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
2616         hci_stack->new_scan_enable_value = 0xff;
2617         return;
2618     }
2619 #endif
2620 
2621 #ifdef ENABLE_BLE
2622     // advertisements, active scanning, and creating connections requires randaom address to be set if using private address
2623     if ((hci_stack->state == HCI_STATE_WORKING)
2624     && (hci_stack->le_own_addr_type == BD_ADDR_TYPE_LE_PUBLIC || hci_stack->le_random_address_set)){
2625 
2626 #ifdef ENABLE_LE_CENTRAL
2627         // handle le scan
2628         switch(hci_stack->le_scanning_state){
2629             case LE_START_SCAN:
2630                 hci_stack->le_scanning_state = LE_SCANNING;
2631                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
2632                 return;
2633 
2634             case LE_STOP_SCAN:
2635                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
2636                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
2637                 return;
2638             default:
2639                 break;
2640         }
2641         if (hci_stack->le_scan_type != 0xff){
2642             // defaults: active scanning, accept all advertisement packets
2643             int scan_type = hci_stack->le_scan_type;
2644             hci_stack->le_scan_type = 0xff;
2645             hci_send_cmd(&hci_le_set_scan_parameters, scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->le_own_addr_type, 0);
2646             return;
2647         }
2648 #endif
2649 #ifdef ENABLE_LE_PERIPHERAL
2650         // le advertisement control
2651         if (hci_stack->le_advertisements_todo){
2652             log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo );
2653         }
2654         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){
2655             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE;
2656             hci_send_cmd(&hci_le_set_advertise_enable, 0);
2657             return;
2658         }
2659         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
2660             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
2661             hci_send_cmd(&hci_le_set_advertising_parameters,
2662                  hci_stack->le_advertisements_interval_min,
2663                  hci_stack->le_advertisements_interval_max,
2664                  hci_stack->le_advertisements_type,
2665                  hci_stack->le_own_addr_type,
2666                  hci_stack->le_advertisements_direct_address_type,
2667                  hci_stack->le_advertisements_direct_address,
2668                  hci_stack->le_advertisements_channel_map,
2669                  hci_stack->le_advertisements_filter_policy);
2670             return;
2671         }
2672         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
2673             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
2674             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, hci_stack->le_advertisements_data);
2675             return;
2676         }
2677         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
2678             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
2679             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len,
2680                 hci_stack->le_scan_response_data);
2681             return;
2682         }
2683         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){
2684             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE;
2685             hci_send_cmd(&hci_le_set_advertise_enable, 1);
2686             return;
2687         }
2688 #endif
2689 
2690 #ifdef ENABLE_LE_CENTRAL
2691         //
2692         // LE Whitelist Management
2693         //
2694 
2695         // check if whitelist needs modification
2696         btstack_linked_list_iterator_t lit;
2697         int modification_pending = 0;
2698         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2699         while (btstack_linked_list_iterator_has_next(&lit)){
2700             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
2701             if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
2702                 modification_pending = 1;
2703                 break;
2704             }
2705         }
2706 
2707         if (modification_pending){
2708             // stop connnecting if modification pending
2709             if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){
2710                 hci_send_cmd(&hci_le_create_connection_cancel);
2711                 return;
2712             }
2713 
2714             // add/remove entries
2715             btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2716             while (btstack_linked_list_iterator_has_next(&lit)){
2717                 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
2718                 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
2719                     entry->state = LE_WHITELIST_ON_CONTROLLER;
2720                     hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
2721                     return;
2722 
2723                 }
2724                 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
2725                     bd_addr_t address;
2726                     bd_addr_type_t address_type = entry->address_type;
2727                     memcpy(address, entry->address, 6);
2728                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
2729                     btstack_memory_whitelist_entry_free(entry);
2730                     hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
2731                     return;
2732                 }
2733             }
2734         }
2735 
2736         // start connecting
2737         if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE &&
2738             !btstack_linked_list_empty(&hci_stack->le_whitelist)){
2739             bd_addr_t null_addr;
2740             memset(null_addr, 0, 6);
2741             hci_send_cmd(&hci_le_create_connection,
2742                  0x0060,    // scan interval: 60 ms
2743                  0x0030,    // scan interval: 30 ms
2744                  1,         // use whitelist
2745                  0,         // peer address type
2746                  null_addr, // peer bd addr
2747                  hci_stack->le_own_addr_type, // our addr type:
2748                  0x0008,    // conn interval min
2749                  0x0018,    // conn interval max
2750                  0,         // conn latency
2751                  0x0048,    // supervision timeout
2752                  0x0001,    // min ce length
2753                  0x0001     // max ce length
2754                  );
2755             return;
2756         }
2757 #endif
2758     }
2759 #endif
2760 
2761     // send pending HCI commands
2762     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
2763         hci_connection_t * connection = (hci_connection_t *) it;
2764 
2765         switch(connection->state){
2766             case SEND_CREATE_CONNECTION:
2767                 switch(connection->address_type){
2768 #ifdef ENABLE_CLASSIC
2769                     case BD_ADDR_TYPE_CLASSIC:
2770                         log_info("sending hci_create_connection");
2771                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
2772                         break;
2773 #endif
2774                     default:
2775 #ifdef ENABLE_BLE
2776 #ifdef ENABLE_LE_CENTRAL
2777                         log_info("sending hci_le_create_connection");
2778                         hci_send_cmd(&hci_le_create_connection,
2779                                      0x0060,    // scan interval: 60 ms
2780                                      0x0030,    // scan interval: 30 ms
2781                                      0,         // don't use whitelist
2782                                      connection->address_type, // peer address type
2783                                      connection->address,      // peer bd addr
2784                                      hci_stack->le_own_addr_type,  // our addr type:
2785                                      0x0008,    // conn interval min
2786                                      0x0018,    // conn interval max
2787                                      0,         // conn latency
2788                                      0x0048,    // supervision timeout
2789                                      0x0001,    // min ce length
2790                                      0x0001     // max ce length
2791                                      );
2792 
2793                         connection->state = SENT_CREATE_CONNECTION;
2794 #endif
2795 #endif
2796                         break;
2797                 }
2798                 return;
2799 
2800 #ifdef ENABLE_CLASSIC
2801             case RECEIVED_CONNECTION_REQUEST:
2802                 log_info("sending hci_accept_connection_request, remote eSCO %u", connection->remote_supported_feature_eSCO);
2803                 connection->state = ACCEPTED_CONNECTION_REQUEST;
2804                 connection->role  = HCI_ROLE_SLAVE;
2805                 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
2806                     hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
2807                 }
2808                 return;
2809 #endif
2810 
2811 #ifdef ENABLE_BLE
2812 #ifdef ENABLE_LE_CENTRAL
2813             case SEND_CANCEL_CONNECTION:
2814                 connection->state = SENT_CANCEL_CONNECTION;
2815                 hci_send_cmd(&hci_le_create_connection_cancel);
2816                 return;
2817 #endif
2818 #endif
2819             case SEND_DISCONNECT:
2820                 connection->state = SENT_DISCONNECT;
2821                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
2822                 return;
2823 
2824             default:
2825                 break;
2826         }
2827 
2828 #ifdef ENABLE_CLASSIC
2829         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
2830             log_info("responding to link key request");
2831             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
2832             link_key_t link_key;
2833             link_key_type_t link_key_type;
2834             if ( hci_stack->link_key_db
2835               && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type)
2836               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
2837                connection->link_key_type = link_key_type;
2838                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
2839             } else {
2840                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
2841             }
2842             return;
2843         }
2844 
2845         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
2846             log_info("denying to pin request");
2847             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
2848             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
2849             return;
2850         }
2851 
2852         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
2853             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
2854             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
2855             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
2856                 // tweak authentication requirements
2857                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
2858                 if (connection->bonding_flags & BONDING_DEDICATED){
2859                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
2860                 }
2861                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
2862                     authreq |= 1;
2863                 }
2864                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
2865             } else {
2866                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
2867             }
2868             return;
2869         }
2870 
2871         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
2872             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
2873             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
2874             return;
2875         }
2876 
2877         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
2878             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
2879             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
2880             return;
2881         }
2882 
2883         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
2884             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
2885             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
2886             return;
2887         }
2888 
2889         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
2890             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
2891             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
2892             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
2893             return;
2894         }
2895 
2896         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
2897             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
2898             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
2899             return;
2900         }
2901 
2902         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
2903             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
2904             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
2905             return;
2906         }
2907 #endif
2908 
2909         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
2910             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
2911             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
2912             return;
2913         }
2914 
2915 #ifdef ENABLE_BLE
2916         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
2917             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2918 
2919             uint16_t connection_interval_min = connection->le_conn_interval_min;
2920             connection->le_conn_interval_min = 0;
2921             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
2922                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
2923                 0x0000, 0xffff);
2924         }
2925 #endif
2926     }
2927 
2928     hci_connection_t * connection;
2929     switch (hci_stack->state){
2930         case HCI_STATE_INITIALIZING:
2931             hci_initializing_run();
2932             break;
2933 
2934         case HCI_STATE_HALTING:
2935 
2936             log_info("HCI_STATE_HALTING");
2937 
2938             // free whitelist entries
2939 #ifdef ENABLE_BLE
2940 #ifdef ENABLE_LE_CENTRAL
2941             {
2942                 btstack_linked_list_iterator_t lit;
2943                 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2944                 while (btstack_linked_list_iterator_has_next(&lit)){
2945                     whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
2946                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
2947                     btstack_memory_whitelist_entry_free(entry);
2948                 }
2949             }
2950 #endif
2951 #endif
2952             // close all open connections
2953             connection =  (hci_connection_t *) hci_stack->connections;
2954             if (connection){
2955                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
2956                 if (!hci_can_send_command_packet_now()) return;
2957 
2958                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
2959 
2960                 // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
2961                 hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
2962 
2963                 // ... which would be ignored anyway as we shutdown (free) the connection now
2964                 hci_shutdown_connection(connection);
2965 
2966                 // finally, send the disconnect command
2967                 hci_send_cmd(&hci_disconnect, con_handle, 0x13);  // remote closed connection
2968                 return;
2969             }
2970             log_info("HCI_STATE_HALTING, calling off");
2971 
2972             // switch mode
2973             hci_power_control_off();
2974 
2975             log_info("HCI_STATE_HALTING, emitting state");
2976             hci_emit_state();
2977             log_info("HCI_STATE_HALTING, done");
2978             break;
2979 
2980         case HCI_STATE_FALLING_ASLEEP:
2981             switch(hci_stack->substate) {
2982                 case HCI_FALLING_ASLEEP_DISCONNECT:
2983                     log_info("HCI_STATE_FALLING_ASLEEP");
2984                     // close all open connections
2985                     connection =  (hci_connection_t *) hci_stack->connections;
2986 
2987 #ifdef HAVE_PLATFORM_IPHONE_OS
2988                     // don't close connections, if H4 supports power management
2989                     if (btstack_control_iphone_power_management_enabled()){
2990                         connection = NULL;
2991                     }
2992 #endif
2993                     if (connection){
2994 
2995                         // send disconnect
2996                         if (!hci_can_send_command_packet_now()) return;
2997 
2998                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
2999                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
3000 
3001                         // send disconnected event right away - causes higher layer connections to get closed, too.
3002                         hci_shutdown_connection(connection);
3003                         return;
3004                     }
3005 
3006                     if (hci_classic_supported()){
3007                         // disable page and inquiry scan
3008                         if (!hci_can_send_command_packet_now()) return;
3009 
3010                         log_info("HCI_STATE_HALTING, disabling inq scans");
3011                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
3012 
3013                         // continue in next sub state
3014                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
3015                         break;
3016                     }
3017                     // no break - fall through for ble-only chips
3018 
3019                 case HCI_FALLING_ASLEEP_COMPLETE:
3020                     log_info("HCI_STATE_HALTING, calling sleep");
3021 #ifdef HAVE_PLATFORM_IPHONE_OS
3022                     // don't actually go to sleep, if H4 supports power management
3023                     if (btstack_control_iphone_power_management_enabled()){
3024                         // SLEEP MODE reached
3025                         hci_stack->state = HCI_STATE_SLEEPING;
3026                         hci_emit_state();
3027                         break;
3028                     }
3029 #endif
3030                     // switch mode
3031                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
3032                     hci_emit_state();
3033                     break;
3034 
3035                 default:
3036                     break;
3037             }
3038             break;
3039 
3040         default:
3041             break;
3042     }
3043 }
3044 
3045 int hci_send_cmd_packet(uint8_t *packet, int size){
3046     // house-keeping
3047 
3048     if (IS_COMMAND(packet, hci_write_loopback_mode)){
3049         hci_stack->loopback_mode = packet[3];
3050     }
3051 
3052 #ifdef ENABLE_CLASSIC
3053     bd_addr_t addr;
3054     hci_connection_t * conn;
3055 
3056     // create_connection?
3057     if (IS_COMMAND(packet, hci_create_connection)){
3058         reverse_bd_addr(&packet[3], addr);
3059         log_info("Create_connection to %s", bd_addr_to_str(addr));
3060 
3061         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3062         if (!conn){
3063             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3064             if (!conn){
3065                 // notify client that alloc failed
3066                 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3067                 return 0; // don't sent packet to controller
3068             }
3069             conn->state = SEND_CREATE_CONNECTION;
3070         }
3071         log_info("conn state %u", conn->state);
3072         switch (conn->state){
3073             // if connection active exists
3074             case OPEN:
3075                 // and OPEN, emit connection complete command, don't send to controller
3076                 hci_emit_connection_complete(addr, conn->con_handle, 0);
3077                 return 0;
3078             case SEND_CREATE_CONNECTION:
3079                 // connection created by hci, e.g. dedicated bonding
3080                 break;
3081             default:
3082                 // otherwise, just ignore as it is already in the open process
3083                 return 0;
3084         }
3085         conn->state = SENT_CREATE_CONNECTION;
3086     }
3087 
3088     if (IS_COMMAND(packet, hci_link_key_request_reply)){
3089         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
3090     }
3091     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
3092         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
3093     }
3094 
3095     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
3096         if (hci_stack->link_key_db){
3097             reverse_bd_addr(&packet[3], addr);
3098             hci_stack->link_key_db->delete_link_key(addr);
3099         }
3100     }
3101 
3102     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
3103     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
3104         reverse_bd_addr(&packet[3], addr);
3105         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3106         if (conn){
3107             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
3108         }
3109     }
3110 
3111     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
3112     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
3113     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
3114     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
3115         reverse_bd_addr(&packet[3], addr);
3116         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3117         if (conn){
3118             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
3119         }
3120     }
3121 
3122 #ifdef ENABLE_SCO_OVER_HCI
3123     // setup_synchronous_connection? Voice setting at offset 22
3124     if (IS_COMMAND(packet, hci_setup_synchronous_connection)){
3125         // TODO: compare to current setting if sco connection already active
3126         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
3127     }
3128     // accept_synchronus_connection? Voice setting at offset 18
3129     if (IS_COMMAND(packet, hci_accept_synchronous_connection)){
3130         // TODO: compare to current setting if sco connection already active
3131         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
3132     }
3133 #endif
3134 #endif
3135 
3136 #ifdef ENABLE_BLE
3137 #ifdef ENABLE_LE_PERIPHERAL
3138     if (IS_COMMAND(packet, hci_le_set_random_address)){
3139         hci_stack->le_random_address_set = 1;
3140         reverse_bd_addr(&packet[3], hci_stack->le_random_address);
3141     }
3142     if (IS_COMMAND(packet, hci_le_set_advertise_enable)){
3143         hci_stack->le_advertisements_active = packet[3];
3144     }
3145 #endif
3146 #ifdef ENABLE_LE_CENTRAL
3147     if (IS_COMMAND(packet, hci_le_create_connection)){
3148         // white list used?
3149         uint8_t initiator_filter_policy = packet[7];
3150         switch (initiator_filter_policy){
3151             case 0:
3152                 // whitelist not used
3153                 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
3154                 break;
3155             case 1:
3156                 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
3157                 break;
3158             default:
3159                 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
3160                 break;
3161         }
3162     }
3163     if (IS_COMMAND(packet, hci_le_create_connection_cancel)){
3164         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3165     }
3166 #endif
3167 #endif
3168 
3169     hci_stack->num_cmd_packets--;
3170 
3171     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3172     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3173 
3174     // release packet buffer for synchronous transport implementations
3175     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
3176         hci_stack->hci_packet_buffer_reserved = 0;
3177     }
3178 
3179     return err;
3180 }
3181 
3182 // disconnect because of security block
3183 void hci_disconnect_security_block(hci_con_handle_t con_handle){
3184     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3185     if (!connection) return;
3186     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3187 }
3188 
3189 
3190 // Configure Secure Simple Pairing
3191 
3192 #ifdef ENABLE_CLASSIC
3193 
3194 // enable will enable SSP during init
3195 void gap_ssp_set_enable(int enable){
3196     hci_stack->ssp_enable = enable;
3197 }
3198 
3199 static int hci_local_ssp_activated(void){
3200     return gap_ssp_supported() && hci_stack->ssp_enable;
3201 }
3202 
3203 // if set, BTstack will respond to io capability request using authentication requirement
3204 void gap_ssp_set_io_capability(int io_capability){
3205     hci_stack->ssp_io_capability = io_capability;
3206 }
3207 void gap_ssp_set_authentication_requirement(int authentication_requirement){
3208     hci_stack->ssp_authentication_requirement = authentication_requirement;
3209 }
3210 
3211 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
3212 void gap_ssp_set_auto_accept(int auto_accept){
3213     hci_stack->ssp_auto_accept = auto_accept;
3214 }
3215 #endif
3216 
3217 // va_list part of hci_send_cmd
3218 int hci_send_cmd_va_arg(const hci_cmd_t *cmd, va_list argptr){
3219     if (!hci_can_send_command_packet_now()){
3220         log_error("hci_send_cmd called but cannot send packet now");
3221         return 0;
3222     }
3223 
3224     // for HCI INITIALIZATION
3225     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
3226     hci_stack->last_cmd_opcode = cmd->opcode;
3227 
3228     hci_reserve_packet_buffer();
3229     uint8_t * packet = hci_stack->hci_packet_buffer;
3230     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
3231     return hci_send_cmd_packet(packet, size);
3232 }
3233 
3234 /**
3235  * pre: numcmds >= 0 - it's allowed to send a command to the controller
3236  */
3237 int hci_send_cmd(const hci_cmd_t *cmd, ...){
3238     va_list argptr;
3239     va_start(argptr, cmd);
3240     int res = hci_send_cmd_va_arg(cmd, argptr);
3241     va_end(argptr);
3242     return res;
3243 }
3244 
3245 // Create various non-HCI events.
3246 // TODO: generalize, use table similar to hci_create_command
3247 
3248 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
3249     // dump packet
3250     if (dump) {
3251         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
3252     }
3253 
3254     // dispatch to all event handlers
3255     btstack_linked_list_iterator_t it;
3256     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
3257     while (btstack_linked_list_iterator_has_next(&it)){
3258         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
3259         entry->callback(HCI_EVENT_PACKET, 0, event, size);
3260     }
3261 }
3262 
3263 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
3264     if (!hci_stack->acl_packet_handler) return;
3265     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
3266 }
3267 
3268 #ifdef ENABLE_CLASSIC
3269 static void hci_notify_if_sco_can_send_now(void){
3270     // notify SCO sender if waiting
3271     if (!hci_stack->sco_waiting_for_can_send_now) return;
3272     if (hci_can_send_sco_packet_now()){
3273         hci_stack->sco_waiting_for_can_send_now = 0;
3274         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
3275         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
3276         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
3277     }
3278 }
3279 #endif
3280 
3281 void hci_emit_state(void){
3282     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
3283     uint8_t event[3];
3284     event[0] = BTSTACK_EVENT_STATE;
3285     event[1] = sizeof(event) - 2;
3286     event[2] = hci_stack->state;
3287     hci_emit_event(event, sizeof(event), 1);
3288 }
3289 
3290 #ifdef ENABLE_CLASSIC
3291 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3292     uint8_t event[13];
3293     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
3294     event[1] = sizeof(event) - 2;
3295     event[2] = status;
3296     little_endian_store_16(event, 3, con_handle);
3297     reverse_bd_addr(address, &event[5]);
3298     event[11] = 1; // ACL connection
3299     event[12] = 0; // encryption disabled
3300     hci_emit_event(event, sizeof(event), 1);
3301 }
3302 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
3303     if (disable_l2cap_timeouts) return;
3304     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
3305     uint8_t event[4];
3306     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
3307     event[1] = sizeof(event) - 2;
3308     little_endian_store_16(event, 2, conn->con_handle);
3309     hci_emit_event(event, sizeof(event), 1);
3310 }
3311 #endif
3312 
3313 #ifdef ENABLE_BLE
3314 #ifdef ENABLE_LE_CENTRAL
3315 static void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3316     uint8_t event[21];
3317     event[0] = HCI_EVENT_LE_META;
3318     event[1] = sizeof(event) - 2;
3319     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
3320     event[3] = status;
3321     little_endian_store_16(event, 4, con_handle);
3322     event[6] = 0; // TODO: role
3323     event[7] = address_type;
3324     reverse_bd_addr(address, &event[8]);
3325     little_endian_store_16(event, 14, 0); // interval
3326     little_endian_store_16(event, 16, 0); // latency
3327     little_endian_store_16(event, 18, 0); // supervision timeout
3328     event[20] = 0; // master clock accuracy
3329     hci_emit_event(event, sizeof(event), 1);
3330 }
3331 #endif
3332 #endif
3333 
3334 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
3335     uint8_t event[6];
3336     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
3337     event[1] = sizeof(event) - 2;
3338     event[2] = 0; // status = OK
3339     little_endian_store_16(event, 3, con_handle);
3340     event[5] = reason;
3341     hci_emit_event(event, sizeof(event), 1);
3342 }
3343 
3344 static void hci_emit_nr_connections_changed(void){
3345     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
3346     uint8_t event[3];
3347     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
3348     event[1] = sizeof(event) - 2;
3349     event[2] = nr_hci_connections();
3350     hci_emit_event(event, sizeof(event), 1);
3351 }
3352 
3353 static void hci_emit_hci_open_failed(void){
3354     log_info("BTSTACK_EVENT_POWERON_FAILED");
3355     uint8_t event[2];
3356     event[0] = BTSTACK_EVENT_POWERON_FAILED;
3357     event[1] = sizeof(event) - 2;
3358     hci_emit_event(event, sizeof(event), 1);
3359 }
3360 
3361 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
3362     log_info("hci_emit_dedicated_bonding_result %u ", status);
3363     uint8_t event[9];
3364     int pos = 0;
3365     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
3366     event[pos++] = sizeof(event) - 2;
3367     event[pos++] = status;
3368     reverse_bd_addr(address, &event[pos]);
3369     hci_emit_event(event, sizeof(event), 1);
3370 }
3371 
3372 
3373 #ifdef ENABLE_CLASSIC
3374 
3375 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
3376     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
3377     uint8_t event[5];
3378     int pos = 0;
3379     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
3380     event[pos++] = sizeof(event) - 2;
3381     little_endian_store_16(event, 2, con_handle);
3382     pos += 2;
3383     event[pos++] = level;
3384     hci_emit_event(event, sizeof(event), 1);
3385 }
3386 
3387 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
3388     if (!connection) return LEVEL_0;
3389     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
3390     return gap_security_level_for_link_key_type(connection->link_key_type);
3391 }
3392 
3393 static void hci_emit_discoverable_enabled(uint8_t enabled){
3394     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
3395     uint8_t event[3];
3396     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
3397     event[1] = sizeof(event) - 2;
3398     event[2] = enabled;
3399     hci_emit_event(event, sizeof(event), 1);
3400 }
3401 
3402 #ifdef ENABLE_CLASSIC
3403 // query if remote side supports eSCO
3404 int hci_remote_esco_supported(hci_con_handle_t con_handle){
3405     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3406     if (!connection) return 0;
3407     return connection->remote_supported_feature_eSCO;
3408 }
3409 
3410 // query if remote side supports SSP
3411 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
3412     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3413     if (!connection) return 0;
3414     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
3415 }
3416 
3417 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
3418     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
3419 }
3420 #endif
3421 
3422 // GAP API
3423 /**
3424  * @bbrief enable/disable bonding. default is enabled
3425  * @praram enabled
3426  */
3427 void gap_set_bondable_mode(int enable){
3428     hci_stack->bondable = enable ? 1 : 0;
3429 }
3430 /**
3431  * @brief Get bondable mode.
3432  * @return 1 if bondable
3433  */
3434 int gap_get_bondable_mode(void){
3435     return hci_stack->bondable;
3436 }
3437 
3438 /**
3439  * @brief map link keys to security levels
3440  */
3441 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
3442     switch (link_key_type){
3443         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
3444             return LEVEL_4;
3445         case COMBINATION_KEY:
3446         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
3447             return LEVEL_3;
3448         default:
3449             return LEVEL_2;
3450     }
3451 }
3452 
3453 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
3454     log_info("gap_mitm_protection_required_for_security_level %u", level);
3455     return level > LEVEL_2;
3456 }
3457 
3458 /**
3459  * @brief get current security level
3460  */
3461 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
3462     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3463     if (!connection) return LEVEL_0;
3464     return gap_security_level_for_connection(connection);
3465 }
3466 
3467 /**
3468  * @brief request connection to device to
3469  * @result GAP_AUTHENTICATION_RESULT
3470  */
3471 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
3472     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3473     if (!connection){
3474         hci_emit_security_level(con_handle, LEVEL_0);
3475         return;
3476     }
3477     gap_security_level_t current_level = gap_security_level(con_handle);
3478     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
3479     if (current_level >= requested_level){
3480         hci_emit_security_level(con_handle, current_level);
3481         return;
3482     }
3483 
3484     connection->requested_security_level = requested_level;
3485 
3486 #if 0
3487     // sending encryption request without a link key results in an error.
3488     // TODO: figure out how to use it properly
3489 
3490     // would enabling ecnryption suffice (>= LEVEL_2)?
3491     if (hci_stack->link_key_db){
3492         link_key_type_t link_key_type;
3493         link_key_t      link_key;
3494         if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){
3495             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
3496                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
3497                 return;
3498             }
3499         }
3500     }
3501 #endif
3502 
3503     // try to authenticate connection
3504     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
3505     hci_run();
3506 }
3507 
3508 /**
3509  * @brief start dedicated bonding with device. disconnect after bonding
3510  * @param device
3511  * @param request MITM protection
3512  * @result GAP_DEDICATED_BONDING_COMPLETE
3513  */
3514 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
3515 
3516     // create connection state machine
3517     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
3518 
3519     if (!connection){
3520         return BTSTACK_MEMORY_ALLOC_FAILED;
3521     }
3522 
3523     // delete linkn key
3524     gap_drop_link_key_for_bd_addr(device);
3525 
3526     // configure LEVEL_2/3, dedicated bonding
3527     connection->state = SEND_CREATE_CONNECTION;
3528     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
3529     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
3530     connection->bonding_flags = BONDING_DEDICATED;
3531 
3532     // wait for GAP Security Result and send GAP Dedicated Bonding complete
3533 
3534     // handle: connnection failure (connection complete != ok)
3535     // handle: authentication failure
3536     // handle: disconnect on done
3537 
3538     hci_run();
3539 
3540     return 0;
3541 }
3542 #endif
3543 
3544 void gap_set_local_name(const char * local_name){
3545     hci_stack->local_name = local_name;
3546 }
3547 
3548 
3549 #ifdef ENABLE_BLE
3550 
3551 #ifdef ENABLE_LE_CENTRAL
3552 void gap_start_scan(void){
3553     if (hci_stack->le_scanning_state == LE_SCANNING) return;
3554     hci_stack->le_scanning_state = LE_START_SCAN;
3555     hci_run();
3556 }
3557 
3558 void gap_stop_scan(void){
3559     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return;
3560     hci_stack->le_scanning_state = LE_STOP_SCAN;
3561     hci_run();
3562 }
3563 
3564 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
3565     hci_stack->le_scan_type     = scan_type;
3566     hci_stack->le_scan_interval = scan_interval;
3567     hci_stack->le_scan_window   = scan_window;
3568     hci_run();
3569 }
3570 
3571 uint8_t gap_connect(bd_addr_t addr, bd_addr_type_t addr_type){
3572     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3573     if (!conn){
3574         log_info("gap_connect: no connection exists yet, creating context");
3575         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
3576         if (!conn){
3577             // notify client that alloc failed
3578             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3579             log_info("gap_connect: failed to alloc hci_connection_t");
3580             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
3581         }
3582         conn->state = SEND_CREATE_CONNECTION;
3583         log_info("gap_connect: send create connection next");
3584         hci_run();
3585         return 0;
3586     }
3587 
3588     if (!hci_is_le_connection(conn) ||
3589         conn->state == SEND_CREATE_CONNECTION ||
3590         conn->state == SENT_CREATE_CONNECTION) {
3591         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
3592         log_error("gap_connect: classic connection or connect is already being created");
3593         return GATT_CLIENT_IN_WRONG_STATE;
3594     }
3595 
3596     log_info("gap_connect: context exists with state %u", conn->state);
3597     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0);
3598     hci_run();
3599     return 0;
3600 }
3601 
3602 // @assumption: only a single outgoing LE Connection exists
3603 static hci_connection_t * gap_get_outgoing_connection(void){
3604     btstack_linked_item_t *it;
3605     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3606         hci_connection_t * conn = (hci_connection_t *) it;
3607         if (!hci_is_le_connection(conn)) continue;
3608         switch (conn->state){
3609             case SEND_CREATE_CONNECTION:
3610             case SENT_CREATE_CONNECTION:
3611                 return conn;
3612             default:
3613                 break;
3614         };
3615     }
3616     return NULL;
3617 }
3618 
3619 uint8_t gap_connect_cancel(void){
3620     hci_connection_t * conn = gap_get_outgoing_connection();
3621     if (!conn) return 0;
3622     switch (conn->state){
3623         case SEND_CREATE_CONNECTION:
3624             // skip sending create connection and emit event instead
3625             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
3626             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
3627             btstack_memory_hci_connection_free( conn );
3628             break;
3629         case SENT_CREATE_CONNECTION:
3630             // request to send cancel connection
3631             conn->state = SEND_CANCEL_CONNECTION;
3632             hci_run();
3633             break;
3634         default:
3635             break;
3636     }
3637     return 0;
3638 }
3639 #endif
3640 
3641 /**
3642  * @brief Updates the connection parameters for a given LE connection
3643  * @param handle
3644  * @param conn_interval_min (unit: 1.25ms)
3645  * @param conn_interval_max (unit: 1.25ms)
3646  * @param conn_latency
3647  * @param supervision_timeout (unit: 10ms)
3648  * @returns 0 if ok
3649  */
3650 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
3651     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
3652     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3653     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3654     connection->le_conn_interval_min = conn_interval_min;
3655     connection->le_conn_interval_max = conn_interval_max;
3656     connection->le_conn_latency = conn_latency;
3657     connection->le_supervision_timeout = supervision_timeout;
3658     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
3659     hci_run();
3660     return 0;
3661 }
3662 
3663 /**
3664  * @brief Request an update of the connection parameter for a given LE connection
3665  * @param handle
3666  * @param conn_interval_min (unit: 1.25ms)
3667  * @param conn_interval_max (unit: 1.25ms)
3668  * @param conn_latency
3669  * @param supervision_timeout (unit: 10ms)
3670  * @returns 0 if ok
3671  */
3672 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
3673     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
3674     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3675     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3676     connection->le_conn_interval_min = conn_interval_min;
3677     connection->le_conn_interval_max = conn_interval_max;
3678     connection->le_conn_latency = conn_latency;
3679     connection->le_supervision_timeout = supervision_timeout;
3680     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
3681     hci_run();
3682     return 0;
3683 }
3684 
3685 #ifdef ENABLE_LE_PERIPHERAL
3686 
3687 static void gap_advertisments_changed(void){
3688     // disable advertisements before updating adv, scan data, or adv params
3689     if (hci_stack->le_advertisements_active){
3690         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
3691     }
3692     hci_run();
3693 }
3694 
3695 /**
3696  * @brief Set Advertisement Data
3697  * @param advertising_data_length
3698  * @param advertising_data (max 31 octets)
3699  * @note data is not copied, pointer has to stay valid
3700  */
3701 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
3702     hci_stack->le_advertisements_data_len = advertising_data_length;
3703     hci_stack->le_advertisements_data = advertising_data;
3704     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3705     gap_advertisments_changed();
3706 }
3707 
3708 /**
3709  * @brief Set Scan Response Data
3710  * @param advertising_data_length
3711  * @param advertising_data (max 31 octets)
3712  * @note data is not copied, pointer has to stay valid
3713  */
3714 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
3715     hci_stack->le_scan_response_data_len = scan_response_data_length;
3716     hci_stack->le_scan_response_data = scan_response_data;
3717     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
3718     gap_advertisments_changed();
3719 }
3720 
3721 /**
3722  * @brief Set Advertisement Parameters
3723  * @param adv_int_min
3724  * @param adv_int_max
3725  * @param adv_type
3726  * @param direct_address_type
3727  * @param direct_address
3728  * @param channel_map
3729  * @param filter_policy
3730  *
3731  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
3732  */
3733  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
3734     uint8_t direct_address_typ, bd_addr_t direct_address,
3735     uint8_t channel_map, uint8_t filter_policy) {
3736 
3737     hci_stack->le_advertisements_interval_min = adv_int_min;
3738     hci_stack->le_advertisements_interval_max = adv_int_max;
3739     hci_stack->le_advertisements_type = adv_type;
3740     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
3741     hci_stack->le_advertisements_channel_map = channel_map;
3742     hci_stack->le_advertisements_filter_policy = filter_policy;
3743     memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6);
3744 
3745     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3746     gap_advertisments_changed();
3747  }
3748 
3749 /**
3750  * @brief Enable/Disable Advertisements
3751  * @param enabled
3752  */
3753 void gap_advertisements_enable(int enabled){
3754     hci_stack->le_advertisements_enabled = enabled;
3755     if (enabled && !hci_stack->le_advertisements_active){
3756         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
3757     }
3758     if (!enabled && hci_stack->le_advertisements_active){
3759         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE;
3760     }
3761     hci_run();
3762 }
3763 
3764 #endif
3765 
3766 void hci_le_set_own_address_type(uint8_t own_address_type){
3767     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
3768     if (own_address_type == hci_stack->le_own_addr_type) return;
3769     hci_stack->le_own_addr_type = own_address_type;
3770 
3771 #ifdef ENABLE_LE_PERIPHERAL
3772     // update advertisement parameters, too
3773     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3774     gap_advertisments_changed();
3775 #endif
3776 #ifdef ENABLE_LE_CENTRAL
3777     // note: we don't update scan parameters or modify ongoing connection attempts
3778 #endif
3779 }
3780 
3781 #endif
3782 
3783 uint8_t gap_disconnect(hci_con_handle_t handle){
3784     hci_connection_t * conn = hci_connection_for_handle(handle);
3785     if (!conn){
3786         hci_emit_disconnection_complete(handle, 0);
3787         return 0;
3788     }
3789     conn->state = SEND_DISCONNECT;
3790     hci_run();
3791     return 0;
3792 }
3793 
3794 /**
3795  * @brief Get connection type
3796  * @param con_handle
3797  * @result connection_type
3798  */
3799 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
3800     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
3801     if (!conn) return GAP_CONNECTION_INVALID;
3802     switch (conn->address_type){
3803         case BD_ADDR_TYPE_LE_PUBLIC:
3804         case BD_ADDR_TYPE_LE_RANDOM:
3805             return GAP_CONNECTION_LE;
3806         case BD_ADDR_TYPE_SCO:
3807             return GAP_CONNECTION_SCO;
3808         case BD_ADDR_TYPE_CLASSIC:
3809             return GAP_CONNECTION_ACL;
3810         default:
3811             return GAP_CONNECTION_INVALID;
3812     }
3813 }
3814 
3815 #ifdef ENABLE_BLE
3816 
3817 #ifdef ENABLE_LE_CENTRAL
3818 /**
3819  * @brief Auto Connection Establishment - Start Connecting to device
3820  * @param address_typ
3821  * @param address
3822  * @returns 0 if ok
3823  */
3824 int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){
3825     // check capacity
3826     int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist);
3827     if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
3828     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
3829     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
3830     entry->address_type = address_type;
3831     memcpy(entry->address, address, 6);
3832     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
3833     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
3834     hci_run();
3835     return 0;
3836 }
3837 
3838 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){
3839     btstack_linked_list_iterator_t it;
3840     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
3841     while (btstack_linked_list_iterator_has_next(&it)){
3842         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
3843         if (entry->address_type != address_type) continue;
3844         if (memcmp(entry->address, address, 6) != 0) continue;
3845         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
3846             // remove from controller if already present
3847             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
3848             continue;
3849         }
3850         // direclty remove entry from whitelist
3851         btstack_linked_list_iterator_remove(&it);
3852         btstack_memory_whitelist_entry_free(entry);
3853     }
3854 }
3855 
3856 /**
3857  * @brief Auto Connection Establishment - Stop Connecting to device
3858  * @param address_typ
3859  * @param address
3860  * @returns 0 if ok
3861  */
3862 int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){
3863     hci_remove_from_whitelist(address_type, address);
3864     hci_run();
3865     return 0;
3866 }
3867 
3868 /**
3869  * @brief Auto Connection Establishment - Stop everything
3870  * @note  Convenience function to stop all active auto connection attempts
3871  */
3872 void gap_auto_connection_stop_all(void){
3873     btstack_linked_list_iterator_t it;
3874     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
3875     while (btstack_linked_list_iterator_has_next(&it)){
3876         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
3877         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
3878             // remove from controller if already present
3879             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
3880             continue;
3881         }
3882         // directly remove entry from whitelist
3883         btstack_linked_list_iterator_remove(&it);
3884         btstack_memory_whitelist_entry_free(entry);
3885     }
3886     hci_run();
3887 }
3888 #endif
3889 #endif
3890 
3891 #ifdef ENABLE_CLASSIC
3892 /**
3893  * @brief Set Extended Inquiry Response data
3894  * @param eir_data size 240 bytes, is not copied make sure memory is accessible during stack startup
3895  * @note has to be done before stack starts up
3896  */
3897 void gap_set_extended_inquiry_response(const uint8_t * data){
3898     hci_stack->eir_data = data;
3899 }
3900 
3901 /**
3902  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
3903  * @param inquriy_mode see bluetooth_defines.h
3904  */
3905 void hci_set_inquiry_mode(inquiry_mode_t mode){
3906     hci_stack->inquiry_mode = mode;
3907 }
3908 
3909 /**
3910  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
3911  */
3912 void hci_set_sco_voice_setting(uint16_t voice_setting){
3913     hci_stack->sco_voice_setting = voice_setting;
3914 }
3915 
3916 /**
3917  * @brief Get SCO Voice Setting
3918  * @return current voice setting
3919  */
3920 uint16_t hci_get_sco_voice_setting(void){
3921     return hci_stack->sco_voice_setting;
3922 }
3923 
3924 /** @brief Get SCO packet length for current SCO Voice setting
3925  *  @note  Using SCO packets of the exact length is required for USB transfer
3926  *  @return Length of SCO packets in bytes (not audio frames)
3927  */
3928 int hci_get_sco_packet_length(void){
3929     // see Core Spec for H2 USB Transfer.
3930     if (hci_stack->sco_voice_setting & 0x0020) return 51;
3931     return 27;
3932 }
3933 #endif
3934 
3935 /**
3936  * @brief Set callback for Bluetooth Hardware Error
3937  */
3938 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
3939     hci_stack->hardware_error_callback = fn;
3940 }
3941 
3942 void hci_disconnect_all(void){
3943     btstack_linked_list_iterator_t it;
3944     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
3945     while (btstack_linked_list_iterator_has_next(&it)){
3946         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
3947         if (con->state == SENT_DISCONNECT) continue;
3948         con->state = SEND_DISCONNECT;
3949     }
3950     hci_run();
3951 }
3952 
3953 uint16_t hci_get_manufacturer(void){
3954     return hci_stack->manufacturer;
3955 }
3956