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