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