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