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