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