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