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