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