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