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