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