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