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