xref: /btstack/src/hci.c (revision d622dcd08a916bbeae590cb4fbecf31c7c9b5c55)
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 #define __BTSTACK_FILE__ "hci.c"
39 
40 /*
41  *  hci.c
42  *
43  *  Created by Matthias Ringwald on 4/29/09.
44  *
45  */
46 
47 #include "btstack_config.h"
48 
49 
50 #ifdef ENABLE_CLASSIC
51 #ifdef HAVE_EMBEDDED_TICK
52 #include "btstack_run_loop_embedded.h"
53 #endif
54 #endif
55 
56 #ifdef HAVE_PLATFORM_IPHONE_OS
57 #include "../port/ios/src/btstack_control_iphone.h"
58 #endif
59 
60 #ifdef ENABLE_BLE
61 #include "gap.h"
62 #endif
63 
64 #include <stdarg.h>
65 #include <string.h>
66 #include <stdio.h>
67 #include <inttypes.h>
68 
69 #include "btstack_debug.h"
70 #include "btstack_event.h"
71 #include "btstack_linked_list.h"
72 #include "btstack_memory.h"
73 #include "bluetooth_company_id.h"
74 #include "bluetooth_data_types.h"
75 #include "gap.h"
76 #include "hci.h"
77 #include "hci_cmd.h"
78 #include "hci_dump.h"
79 #include "ad_parser.h"
80 
81 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
82 #ifndef HCI_HOST_ACL_PACKET_NUM
83 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_NUM"
84 #endif
85 #ifndef HCI_HOST_ACL_PACKET_LEN
86 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_LEN"
87 #endif
88 #ifndef HCI_HOST_SCO_PACKET_NUM
89 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_NUM"
90 #endif
91 #ifndef HCI_HOST_SCO_PACKET_LEN
92 #error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_LEN"
93 #endif
94 #endif
95 
96 #define HCI_CONNECTION_TIMEOUT_MS 10000
97 #define HCI_RESET_RESEND_TIMEOUT_MS 200
98 
99 // Names are arbitrarily shortened to 32 bytes if not requested otherwise
100 #ifndef GAP_INQUIRY_MAX_NAME_LEN
101 #define GAP_INQUIRY_MAX_NAME_LEN 32
102 #endif
103 
104 // GAP inquiry state: 0 = off, 0x01 - 0x30 = requested duration, 0xfe = active, 0xff = stop requested
105 #define GAP_INQUIRY_DURATION_MIN 0x01
106 #define GAP_INQUIRY_DURATION_MAX 0x30
107 #define GAP_INQUIRY_STATE_ACTIVE 0x80
108 #define GAP_INQUIRY_STATE_IDLE 0
109 #define GAP_INQUIRY_STATE_W2_CANCEL 0x81
110 #define GAP_INQUIRY_STATE_W4_CANCELLED 0x82
111 
112 // GAP Remote Name Request
113 #define GAP_REMOTE_NAME_STATE_IDLE 0
114 #define GAP_REMOTE_NAME_STATE_W2_SEND 1
115 #define GAP_REMOTE_NAME_STATE_W4_COMPLETE 2
116 
117 // GAP Pairing
118 #define GAP_PAIRING_STATE_IDLE                       0
119 #define GAP_PAIRING_STATE_SEND_PIN                   1
120 #define GAP_PAIRING_STATE_SEND_PIN_NEGATIVE          2
121 #define GAP_PAIRING_STATE_SEND_PASSKEY               3
122 #define GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE      4
123 #define GAP_PAIRING_STATE_SEND_CONFIRMATION          5
124 #define GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE 6
125 
126 
127 // prototypes
128 #ifdef ENABLE_CLASSIC
129 static void hci_update_scan_enable(void);
130 static void hci_emit_discoverable_enabled(uint8_t enabled);
131 static int  hci_local_ssp_activated(void);
132 static int  hci_remote_ssp_supported(hci_con_handle_t con_handle);
133 static void hci_notify_if_sco_can_send_now(void);
134 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status);
135 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
136 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level);
137 static void hci_connection_timeout_handler(btstack_timer_source_t *timer);
138 static void hci_connection_timestamp(hci_connection_t *connection);
139 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn);
140 static void gap_inquiry_explode(uint8_t * packet);
141 #endif
142 
143 static int  hci_power_control_on(void);
144 static void hci_power_control_off(void);
145 static void hci_state_reset(void);
146 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason);
147 static void hci_emit_nr_connections_changed(void);
148 static void hci_emit_hci_open_failed(void);
149 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status);
150 static void hci_emit_event(uint8_t * event, uint16_t size, int dump);
151 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size);
152 static void hci_run(void);
153 static int  hci_is_le_connection(hci_connection_t * connection);
154 static int  hci_number_free_acl_slots_for_connection_type( bd_addr_type_t address_type);
155 
156 #ifdef ENABLE_BLE
157 #ifdef ENABLE_LE_CENTRAL
158 // called from test/ble_client/advertising_data_parser.c
159 void le_handle_advertisement_report(uint8_t *packet, uint16_t size);
160 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address);
161 static hci_connection_t * gap_get_outgoing_connection(void);
162 #endif
163 #endif
164 
165 // the STACK is here
166 #ifndef HAVE_MALLOC
167 static hci_stack_t   hci_stack_static;
168 #endif
169 static hci_stack_t * hci_stack = NULL;
170 
171 #ifdef ENABLE_CLASSIC
172 // default name
173 static const char * default_classic_name = "BTstack 00:00:00:00:00:00";
174 
175 // test helper
176 static uint8_t disable_l2cap_timeouts = 0;
177 #endif
178 
179 /**
180  * create connection for given address
181  *
182  * @return connection OR NULL, if no memory left
183  */
184 static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
185     log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type);
186     hci_connection_t * conn = btstack_memory_hci_connection_get();
187     if (!conn) return NULL;
188     memset(conn, 0, sizeof(hci_connection_t));
189     bd_addr_copy(conn->address, addr);
190     conn->address_type = addr_type;
191     conn->con_handle = 0xffff;
192     conn->authentication_flags = AUTH_FLAGS_NONE;
193     conn->bonding_flags = 0;
194     conn->requested_security_level = LEVEL_0;
195 #ifdef ENABLE_CLASSIC
196     btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler);
197     btstack_run_loop_set_timer_context(&conn->timeout, conn);
198     hci_connection_timestamp(conn);
199 #endif
200     conn->acl_recombination_length = 0;
201     conn->acl_recombination_pos = 0;
202     conn->num_acl_packets_sent = 0;
203     conn->num_sco_packets_sent = 0;
204     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
205     btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn);
206     return conn;
207 }
208 
209 
210 /**
211  * get le connection parameter range
212 *
213  * @return le connection parameter range struct
214  */
215 void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){
216     *range = hci_stack->le_connection_parameter_range;
217 }
218 
219 /**
220  * set le connection parameter range
221  *
222  */
223 
224 void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){
225     hci_stack->le_connection_parameter_range = *range;
226 }
227 
228 /**
229  * get hci connections iterator
230  *
231  * @return hci connections iterator
232  */
233 
234 void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){
235     btstack_linked_list_iterator_init(it, &hci_stack->connections);
236 }
237 
238 /**
239  * get connection for a given handle
240  *
241  * @return connection OR NULL, if not found
242  */
243 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
244     btstack_linked_list_iterator_t it;
245     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
246     while (btstack_linked_list_iterator_has_next(&it)){
247         hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
248         if ( item->con_handle == con_handle ) {
249             return item;
250         }
251     }
252     return NULL;
253 }
254 
255 /**
256  * get connection for given address
257  *
258  * @return connection OR NULL, if not found
259  */
260 hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t  addr, bd_addr_type_t addr_type){
261     btstack_linked_list_iterator_t it;
262     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
263     while (btstack_linked_list_iterator_has_next(&it)){
264         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
265         if (connection->address_type != addr_type)  continue;
266         if (memcmp(addr, connection->address, 6) != 0) continue;
267         return connection;
268     }
269     return NULL;
270 }
271 
272 
273 #ifdef ENABLE_CLASSIC
274 
275 #ifdef ENABLE_SCO_OVER_HCI
276 static int hci_number_sco_connections(void){
277     int connections = 0;
278     btstack_linked_list_iterator_t it;
279     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
280     while (btstack_linked_list_iterator_has_next(&it)){
281         hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
282         if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
283         connections++;
284     }
285     return connections;
286 }
287 #endif
288 
289 static void hci_connection_timeout_handler(btstack_timer_source_t *timer){
290     hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer);
291 #ifdef HAVE_EMBEDDED_TICK
292     if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
293         // connections might be timed out
294         hci_emit_l2cap_check_timeout(connection);
295     }
296 #else
297     if (btstack_run_loop_get_time_ms() > connection->timestamp + HCI_CONNECTION_TIMEOUT_MS){
298         // connections might be timed out
299         hci_emit_l2cap_check_timeout(connection);
300     }
301 #endif
302 }
303 
304 static void hci_connection_timestamp(hci_connection_t *connection){
305 #ifdef HAVE_EMBEDDED_TICK
306     connection->timestamp = btstack_run_loop_embedded_get_ticks();
307 #else
308     connection->timestamp = btstack_run_loop_get_time_ms();
309 #endif
310 }
311 
312 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
313     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
314 }
315 
316 
317 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
318     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
319 }
320 
321 /**
322  * add authentication flags and reset timer
323  * @note: assumes classic connection
324  * @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets
325  */
326 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
327     bd_addr_t addr;
328     reverse_bd_addr(bd_addr, addr);
329     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
330     if (conn) {
331         connectionSetAuthenticationFlags(conn, flags);
332         hci_connection_timestamp(conn);
333     }
334 }
335 
336 int  hci_authentication_active_for_handle(hci_con_handle_t handle){
337     hci_connection_t * conn = hci_connection_for_handle(handle);
338     if (!conn) return 0;
339     if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
340     if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
341     return 0;
342 }
343 
344 void gap_drop_link_key_for_bd_addr(bd_addr_t addr){
345     if (!hci_stack->link_key_db) return;
346     log_info("gap_drop_link_key_for_bd_addr: %s", bd_addr_to_str(addr));
347     hci_stack->link_key_db->delete_link_key(addr);
348 }
349 
350 void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){
351     if (!hci_stack->link_key_db) return;
352     log_info("gap_store_link_key_for_bd_addr: %s, type %u", bd_addr_to_str(addr), type);
353     hci_stack->link_key_db->put_link_key(addr, link_key, type);
354 }
355 
356 void gap_delete_all_link_keys(void){
357     bd_addr_t  addr;
358     link_key_t link_key;
359     link_key_type_t type;
360     btstack_link_key_iterator_t it;
361     int ok = gap_link_key_iterator_init(&it);
362     if (!ok) {
363         log_error("could not initialize iterator");
364         return;
365     }
366     while (gap_link_key_iterator_get_next(&it, addr, link_key, &type)){
367         gap_drop_link_key_for_bd_addr(addr);
368     }
369     gap_link_key_iterator_done(&it);
370 }
371 
372 int gap_link_key_iterator_init(btstack_link_key_iterator_t * it){
373     if (!hci_stack->link_key_db) return 0;
374     if (!hci_stack->link_key_db->iterator_init) return 0;
375     return hci_stack->link_key_db->iterator_init(it);
376 }
377 int gap_link_key_iterator_get_next(btstack_link_key_iterator_t * it, bd_addr_t bd_addr, link_key_t link_key, link_key_type_t * type){
378     if (!hci_stack->link_key_db) return 0;
379     return hci_stack->link_key_db->iterator_get_next(it, bd_addr, link_key, type);
380 }
381 void gap_link_key_iterator_done(btstack_link_key_iterator_t * it){
382     if (!hci_stack->link_key_db) return;
383     hci_stack->link_key_db->iterator_done(it);
384 }
385 #endif
386 
387 static int hci_is_le_connection(hci_connection_t * connection){
388     return  connection->address_type == BD_ADDR_TYPE_LE_PUBLIC ||
389     connection->address_type == BD_ADDR_TYPE_LE_RANDOM;
390 }
391 
392 /**
393  * count connections
394  */
395 static int nr_hci_connections(void){
396     int count = 0;
397     btstack_linked_item_t *it;
398     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next, count++);
399     return count;
400 }
401 
402 static int hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){
403 
404     unsigned int num_packets_sent_classic = 0;
405     unsigned int num_packets_sent_le = 0;
406 
407     btstack_linked_item_t *it;
408     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
409         hci_connection_t * connection = (hci_connection_t *) it;
410         if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
411             num_packets_sent_classic += connection->num_acl_packets_sent;
412         } else {
413             num_packets_sent_le += connection->num_acl_packets_sent;
414         }
415     }
416     log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num);
417     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
418     int free_slots_le = 0;
419 
420     if (free_slots_classic < 0){
421         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);
422         return 0;
423     }
424 
425     if (hci_stack->le_acl_packets_total_num){
426         // if we have LE slots, they are used
427         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
428         if (free_slots_le < 0){
429             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);
430             return 0;
431         }
432     } else {
433         // otherwise, classic slots are used for LE, too
434         free_slots_classic -= num_packets_sent_le;
435         if (free_slots_classic < 0){
436             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);
437             return 0;
438         }
439     }
440 
441     switch (address_type){
442         case BD_ADDR_TYPE_UNKNOWN:
443             log_error("hci_number_free_acl_slots: unknown address type");
444             return 0;
445 
446         case BD_ADDR_TYPE_CLASSIC:
447             return free_slots_classic;
448 
449         default:
450            if (hci_stack->le_acl_packets_total_num){
451                return free_slots_le;
452            }
453            return free_slots_classic;
454     }
455 }
456 
457 int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
458     // get connection type
459     hci_connection_t * connection = hci_connection_for_handle(con_handle);
460     if (!connection){
461         log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
462         return 0;
463     }
464     return hci_number_free_acl_slots_for_connection_type(connection->address_type);
465 }
466 
467 #ifdef ENABLE_CLASSIC
468 static int hci_number_free_sco_slots(void){
469     unsigned int num_sco_packets_sent  = 0;
470     btstack_linked_item_t *it;
471     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
472         hci_connection_t * connection = (hci_connection_t *) it;
473         num_sco_packets_sent += connection->num_sco_packets_sent;
474     }
475     if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
476         log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num);
477         return 0;
478     }
479     // log_info("hci_number_free_sco_slots u", handle, num_sco_packets_sent);
480     return hci_stack->sco_packets_total_num - num_sco_packets_sent;
481 }
482 #endif
483 
484 // only used to send HCI Host Number Completed Packets
485 static int hci_can_send_comand_packet_transport(void){
486     if (hci_stack->hci_packet_buffer_reserved) return 0;
487 
488     // check for async hci transport implementations
489     if (hci_stack->hci_transport->can_send_packet_now){
490         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
491             return 0;
492         }
493     }
494     return 1;
495 }
496 
497 // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
498 int hci_can_send_command_packet_now(void){
499     if (hci_can_send_comand_packet_transport() == 0) return 0;
500     return hci_stack->num_cmd_packets > 0;
501 }
502 
503 static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){
504     // check for async hci transport implementations
505     if (!hci_stack->hci_transport->can_send_packet_now) return 1;
506     return hci_stack->hci_transport->can_send_packet_now(packet_type);
507 }
508 
509 static int hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){
510     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
511     return hci_number_free_acl_slots_for_connection_type(address_type) > 0;
512 }
513 
514 int hci_can_send_acl_le_packet_now(void){
515     if (hci_stack->hci_packet_buffer_reserved) return 0;
516     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC);
517 }
518 
519 int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
520     if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
521     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
522 }
523 
524 int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
525     if (hci_stack->hci_packet_buffer_reserved) return 0;
526     return hci_can_send_prepared_acl_packet_now(con_handle);
527 }
528 
529 #ifdef ENABLE_CLASSIC
530 int hci_can_send_acl_classic_packet_now(void){
531     if (hci_stack->hci_packet_buffer_reserved) return 0;
532     return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_CLASSIC);
533 }
534 
535 int hci_can_send_prepared_sco_packet_now(void){
536     if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return 0;
537     if (!hci_stack->synchronous_flow_control_enabled) return 1;
538     return hci_number_free_sco_slots() > 0;
539 }
540 
541 int hci_can_send_sco_packet_now(void){
542     if (hci_stack->hci_packet_buffer_reserved) return 0;
543     return hci_can_send_prepared_sco_packet_now();
544 }
545 
546 void hci_request_sco_can_send_now_event(void){
547     hci_stack->sco_waiting_for_can_send_now = 1;
548     hci_notify_if_sco_can_send_now();
549 }
550 #endif
551 
552 // used for internal checks in l2cap.c
553 int hci_is_packet_buffer_reserved(void){
554     return hci_stack->hci_packet_buffer_reserved;
555 }
556 
557 // reserves outgoing packet buffer. @returns 1 if successful
558 int hci_reserve_packet_buffer(void){
559     if (hci_stack->hci_packet_buffer_reserved) {
560         log_error("hci_reserve_packet_buffer called but buffer already reserved");
561         return 0;
562     }
563     hci_stack->hci_packet_buffer_reserved = 1;
564     return 1;
565 }
566 
567 void hci_release_packet_buffer(void){
568     hci_stack->hci_packet_buffer_reserved = 0;
569 }
570 
571 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
572 static int hci_transport_synchronous(void){
573     return hci_stack->hci_transport->can_send_packet_now == NULL;
574 }
575 
576 static int hci_send_acl_packet_fragments(hci_connection_t *connection){
577 
578     // 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);
579 
580     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
581     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
582     if (hci_is_le_connection(connection) && hci_stack->le_data_packets_length > 0){
583         max_acl_data_packet_length = hci_stack->le_data_packets_length;
584     }
585 
586     // testing: reduce buffer to minimum
587     // max_acl_data_packet_length = 52;
588 
589     log_debug("hci_send_acl_packet_fragments entered");
590 
591     int err;
592     // multiple packets could be send on a synchronous HCI transport
593     while (1){
594 
595         log_debug("hci_send_acl_packet_fragments loop entered");
596 
597         // get current data
598         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4;
599         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
600         int more_fragments = 0;
601 
602         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
603         if (current_acl_data_packet_length > max_acl_data_packet_length){
604             more_fragments = 1;
605             current_acl_data_packet_length = max_acl_data_packet_length;
606         }
607 
608         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
609         if (acl_header_pos > 0){
610             uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
611             handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12);
612             little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
613         }
614 
615         // update header len
616         little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length);
617 
618         // count packet
619         connection->num_acl_packets_sent++;
620         log_debug("hci_send_acl_packet_fragments loop before send (more fragments %d)", more_fragments);
621 
622         // update state for next fragment (if any) as "transport done" might be sent during send_packet already
623         if (more_fragments){
624             // update start of next fragment to send
625             hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
626         } else {
627             // done
628             hci_stack->acl_fragmentation_pos = 0;
629             hci_stack->acl_fragmentation_total_size = 0;
630         }
631 
632         // send packet
633         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
634         const int size = current_acl_data_packet_length + 4;
635         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
636         err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
637 
638         log_debug("hci_send_acl_packet_fragments loop after send (more fragments %d)", more_fragments);
639 
640         // done yet?
641         if (!more_fragments) break;
642 
643         // can send more?
644         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
645     }
646 
647     log_debug("hci_send_acl_packet_fragments loop over");
648 
649     // release buffer now for synchronous transport
650     if (hci_transport_synchronous()){
651         hci_release_packet_buffer();
652         // notify upper stack that it might be possible to send again
653         uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
654         hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
655     }
656 
657     return err;
658 }
659 
660 // pre: caller has reserved the packet buffer
661 int hci_send_acl_packet_buffer(int size){
662 
663     // log_info("hci_send_acl_packet_buffer size %u", size);
664 
665     if (!hci_stack->hci_packet_buffer_reserved) {
666         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
667         return 0;
668     }
669 
670     uint8_t * packet = hci_stack->hci_packet_buffer;
671     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
672 
673     // check for free places on Bluetooth module
674     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
675         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
676         hci_release_packet_buffer();
677         return BTSTACK_ACL_BUFFERS_FULL;
678     }
679 
680     hci_connection_t *connection = hci_connection_for_handle( con_handle);
681     if (!connection) {
682         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
683         hci_release_packet_buffer();
684         return 0;
685     }
686 
687 #ifdef ENABLE_CLASSIC
688     hci_connection_timestamp(connection);
689 #endif
690 
691     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
692 
693     // setup data
694     hci_stack->acl_fragmentation_total_size = size;
695     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
696 
697     return hci_send_acl_packet_fragments(connection);
698 }
699 
700 #ifdef ENABLE_CLASSIC
701 // pre: caller has reserved the packet buffer
702 int hci_send_sco_packet_buffer(int size){
703 
704     // log_info("hci_send_acl_packet_buffer size %u", size);
705 
706     if (!hci_stack->hci_packet_buffer_reserved) {
707         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
708         return 0;
709     }
710 
711     uint8_t * packet = hci_stack->hci_packet_buffer;
712 
713     // skip checks in loopback mode
714     if (!hci_stack->loopback_mode){
715         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);   // same for ACL and SCO
716 
717         // check for free places on Bluetooth module
718         if (!hci_can_send_prepared_sco_packet_now()) {
719             log_error("hci_send_sco_packet_buffer called but no free ACL buffers on controller");
720             hci_release_packet_buffer();
721             return BTSTACK_ACL_BUFFERS_FULL;
722         }
723 
724         // track send packet in connection struct
725         hci_connection_t *connection = hci_connection_for_handle( con_handle);
726         if (!connection) {
727             log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle);
728             hci_release_packet_buffer();
729             return 0;
730         }
731         connection->num_sco_packets_sent++;
732     }
733 
734     hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
735     int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
736 
737     if (hci_transport_synchronous()){
738         hci_release_packet_buffer();
739         // notify upper stack that it might be possible to send again
740         uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
741         hci_emit_event(&event[0], sizeof(event), 0);    // don't dump
742     }
743 
744     return err;
745 }
746 #endif
747 
748 static void acl_handler(uint8_t *packet, int size){
749 
750     // log_info("acl_handler: size %u", size);
751 
752     // get info
753     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
754     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
755     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
756     uint16_t acl_length         = READ_ACL_LENGTH(packet);
757 
758     // ignore non-registered handle
759     if (!conn){
760         log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle);
761         return;
762     }
763 
764     // assert packet is complete
765     if (acl_length + 4 != size){
766         log_error("hci.c: acl_handler called with ACL packet of wrong size %d, expected %u => dropping packet", size, acl_length + 4);
767         return;
768     }
769 
770 #ifdef ENABLE_CLASSIC
771     // update idle timestamp
772     hci_connection_timestamp(conn);
773 #endif
774 
775 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
776     hci_stack->host_completed_packets = 1;
777     conn->num_packets_completed++;
778 #endif
779 
780     // handle different packet types
781     switch (acl_flags & 0x03) {
782 
783         case 0x01: // continuation fragment
784 
785             // sanity checks
786             if (conn->acl_recombination_pos == 0) {
787                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
788                 return;
789             }
790             if (conn->acl_recombination_pos + acl_length > 4 + HCI_ACL_BUFFER_SIZE){
791                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
792                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
793                 conn->acl_recombination_pos = 0;
794                 return;
795             }
796 
797             // append fragment payload (header already stored)
798             memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos], &packet[4], acl_length );
799             conn->acl_recombination_pos += acl_length;
800 
801             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length,
802             //        conn->acl_recombination_pos, conn->acl_recombination_length);
803 
804             // forward complete L2CAP packet if complete.
805             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
806                 hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
807                 // reset recombination buffer
808                 conn->acl_recombination_length = 0;
809                 conn->acl_recombination_pos = 0;
810             }
811             break;
812 
813         case 0x02: { // first fragment
814 
815             // sanity check
816             if (conn->acl_recombination_pos) {
817                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
818                 conn->acl_recombination_pos = 0;
819             }
820 
821             // peek into L2CAP packet!
822             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
823 
824             // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length);
825 
826             // compare fragment size to L2CAP packet size
827             if (acl_length >= l2cap_length + 4){
828                 // forward fragment as L2CAP packet
829                 hci_emit_acl_packet(packet, acl_length + 4);
830             } else {
831 
832                 if (acl_length > HCI_ACL_BUFFER_SIZE){
833                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
834                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
835                     return;
836                 }
837 
838                 // store first fragment and tweak acl length for complete package
839                 memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], packet, acl_length + 4);
840                 conn->acl_recombination_pos    = acl_length + 4;
841                 conn->acl_recombination_length = l2cap_length;
842                 little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2, l2cap_length +4);
843             }
844             break;
845 
846         }
847         default:
848             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
849             return;
850     }
851 
852     // execute main loop
853     hci_run();
854 }
855 
856 static void hci_shutdown_connection(hci_connection_t *conn){
857     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
858 
859 #ifdef ENABLE_CLASSIC
860 #ifdef ENABLE_SCO_OVER_HCI
861     int addr_type = conn->address_type;
862 #endif
863 #endif
864 
865     btstack_run_loop_remove_timer(&conn->timeout);
866 
867     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
868     btstack_memory_hci_connection_free( conn );
869 
870     // now it's gone
871     hci_emit_nr_connections_changed();
872 
873 #ifdef ENABLE_CLASSIC
874 #ifdef ENABLE_SCO_OVER_HCI
875     // update SCO
876     if (addr_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
877         hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
878     }
879 #endif
880 #endif
881 }
882 
883 #ifdef ENABLE_CLASSIC
884 
885 static const uint16_t packet_type_sizes[] = {
886     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
887     HCI_ACL_DH1_SIZE, 0, 0, 0,
888     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
889     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
890 };
891 static const uint8_t  packet_type_feature_requirement_bit[] = {
892      0, // 3 slot packets
893      1, // 5 slot packets
894     25, // EDR 2 mpbs
895     26, // EDR 3 mbps
896     39, // 3 slot EDR packts
897     40, // 5 slot EDR packet
898 };
899 static const uint16_t packet_type_feature_packet_mask[] = {
900     0x0f00, // 3 slot packets
901     0xf000, // 5 slot packets
902     0x1102, // EDR 2 mpbs
903     0x2204, // EDR 3 mbps
904     0x0300, // 3 slot EDR packts
905     0x3000, // 5 slot EDR packet
906 };
907 
908 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
909     // enable packet types based on size
910     uint16_t packet_types = 0;
911     unsigned int i;
912     for (i=0;i<16;i++){
913         if (packet_type_sizes[i] == 0) continue;
914         if (packet_type_sizes[i] <= buffer_size){
915             packet_types |= 1 << i;
916         }
917     }
918     // disable packet types due to missing local supported features
919     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
920         unsigned int bit_idx = packet_type_feature_requirement_bit[i];
921         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
922         if (feature_set) continue;
923         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
924         packet_types &= ~packet_type_feature_packet_mask[i];
925     }
926     // flip bits for "may not be used"
927     packet_types ^= 0x3306;
928     return packet_types;
929 }
930 
931 uint16_t hci_usable_acl_packet_types(void){
932     return hci_stack->packet_types;
933 }
934 #endif
935 
936 uint8_t* hci_get_outgoing_packet_buffer(void){
937     // hci packet buffer is >= acl data packet length
938     return hci_stack->hci_packet_buffer;
939 }
940 
941 uint16_t hci_max_acl_data_packet_length(void){
942     return hci_stack->acl_data_packet_length;
943 }
944 
945 #ifdef ENABLE_CLASSIC
946 int hci_extended_sco_link_supported(void){
947     // No. 31, byte 3, bit 7
948     return (hci_stack->local_supported_features[3] & (1 << 7)) != 0;
949 }
950 #endif
951 
952 int hci_non_flushable_packet_boundary_flag_supported(void){
953     // No. 54, byte 6, bit 6
954     return (hci_stack->local_supported_features[6] & (1 << 6)) != 0;
955 }
956 
957 static int gap_ssp_supported(void){
958     // No. 51, byte 6, bit 3
959     return (hci_stack->local_supported_features[6] & (1 << 3)) != 0;
960 }
961 
962 static int hci_classic_supported(void){
963 #ifdef ENABLE_CLASSIC
964     // No. 37, byte 4, bit 5, = No BR/EDR Support
965     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
966 #else
967     return 0;
968 #endif
969 }
970 
971 static int hci_le_supported(void){
972 #ifdef ENABLE_BLE
973     // No. 37, byte 4, bit 6 = LE Supported (Controller)
974     return (hci_stack->local_supported_features[4] & (1 << 6)) != 0;
975 #else
976     return 0;
977 #endif
978 }
979 
980 #ifdef ENABLE_BLE
981 
982 /**
983  * @brief Get addr type and address used for LE in Advertisements, Scan Responses,
984  */
985 void gap_le_get_own_address(uint8_t * addr_type, bd_addr_t addr){
986     *addr_type = hci_stack->le_own_addr_type;
987     if (hci_stack->le_own_addr_type){
988         memcpy(addr, hci_stack->le_random_address, 6);
989     } else {
990         memcpy(addr, hci_stack->local_bd_addr, 6);
991     }
992 }
993 
994 #ifdef ENABLE_LE_CENTRAL
995 void le_handle_advertisement_report(uint8_t *packet, uint16_t size){
996 
997     int offset = 3;
998     int num_reports = packet[offset];
999     offset += 1;
1000 
1001     int i;
1002     // log_info("HCI: handle adv report with num reports: %d", num_reports);
1003     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
1004     for (i=0; i<num_reports && offset < size;i++){
1005         uint8_t data_length = btstack_min( packet[offset + 8], LE_ADVERTISING_DATA_SIZE);
1006         uint8_t event_size = 10 + data_length;
1007         int pos = 0;
1008         event[pos++] = GAP_EVENT_ADVERTISING_REPORT;
1009         event[pos++] = event_size;
1010         memcpy(&event[pos], &packet[offset], 1+1+6); // event type + address type + address
1011         offset += 8;
1012         pos += 8;
1013         event[pos++] = packet[offset + 1 + data_length]; // rssi
1014         event[pos++] = packet[offset++]; //data_length;
1015         memcpy(&event[pos], &packet[offset], data_length);
1016         pos += data_length;
1017         offset += data_length + 1; // rssi
1018         hci_emit_event(event, pos, 1);
1019     }
1020 }
1021 #endif
1022 #endif
1023 
1024 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1025 
1026 static uint32_t hci_transport_uart_get_main_baud_rate(void){
1027     if (!hci_stack->config) return 0;
1028     uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1029     // Limit baud rate for Broadcom chipsets to 3 mbps
1030     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION && baud_rate > 3000000){
1031         baud_rate = 3000000;
1032     }
1033     return baud_rate;
1034 }
1035 
1036 static void hci_initialization_timeout_handler(btstack_timer_source_t * ds){
1037     UNUSED(ds);
1038 
1039     switch (hci_stack->substate){
1040         case HCI_INIT_W4_SEND_RESET:
1041             log_info("Resend HCI Reset");
1042             hci_stack->substate = HCI_INIT_SEND_RESET;
1043             hci_stack->num_cmd_packets = 1;
1044             hci_run();
1045             break;
1046         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET:
1047             log_info("Resend HCI Reset - CSR Warm Boot with Link Reset");
1048             if (hci_stack->hci_transport->reset_link){
1049                 hci_stack->hci_transport->reset_link();
1050             }
1051             // no break - explicit fallthrough to HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT
1052         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1053             log_info("Resend HCI Reset - CSR Warm Boot");
1054             hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1055             hci_stack->num_cmd_packets = 1;
1056             hci_run();
1057             break;
1058         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1059             if (hci_stack->hci_transport->set_baudrate){
1060                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1061                 log_info("Local baud rate change to %"PRIu32"(timeout handler)", baud_rate);
1062                 hci_stack->hci_transport->set_baudrate(baud_rate);
1063             }
1064             // For CSR, HCI Reset is sent on new baud rate. Don't forget to reset link for H5/BCSP
1065             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
1066                 if (hci_stack->hci_transport->reset_link){
1067                     log_info("Link Reset");
1068                     hci_stack->hci_transport->reset_link();
1069                 }
1070                 hci_stack->substate = HCI_INIT_SEND_RESET_CSR_WARM_BOOT;
1071                 hci_run();
1072             }
1073             break;
1074         case HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY:
1075             // otherwise continue
1076             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1077             hci_send_cmd(&hci_read_local_supported_commands);
1078             break;
1079         default:
1080             break;
1081     }
1082 }
1083 #endif
1084 
1085 static void hci_initializing_next_state(void){
1086     hci_stack->substate = (hci_substate_t )( ((int) hci_stack->substate) + 1);
1087 }
1088 
1089 #if defined(ENABLE_CLASSIC) || defined(ENABLE_LE_PERIPHERAL)
1090 static void hci_replace_bd_addr_placeholder(uint8_t * data, uint16_t size){
1091     const int bd_addr_string_len = 17;
1092     int i = 0;
1093     while (i < size - bd_addr_string_len){
1094         if (memcmp(&data[i], "00:00:00:00:00:00", bd_addr_string_len)) {
1095             i++;
1096             continue;
1097         }
1098         // set real address
1099         memcpy(&data[i], bd_addr_to_str(hci_stack->local_bd_addr), bd_addr_string_len);
1100         i += bd_addr_string_len;
1101     }
1102 }
1103 #endif
1104 
1105 // assumption: hci_can_send_command_packet_now() == true
1106 static void hci_initializing_run(void){
1107     log_debug("hci_initializing_run: substate %u, can send %u", hci_stack->substate, hci_can_send_command_packet_now());
1108     switch (hci_stack->substate){
1109         case HCI_INIT_SEND_RESET:
1110             hci_state_reset();
1111 
1112 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1113             // prepare reset if command complete not received in 100ms
1114             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1115             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1116             btstack_run_loop_add_timer(&hci_stack->timeout);
1117 #endif
1118             // send command
1119             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1120             hci_send_cmd(&hci_reset);
1121             break;
1122         case HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION:
1123             hci_send_cmd(&hci_read_local_version_information);
1124             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION;
1125             break;
1126         case HCI_INIT_SEND_READ_LOCAL_NAME:
1127             hci_send_cmd(&hci_read_local_name);
1128             hci_stack->substate = HCI_INIT_W4_SEND_READ_LOCAL_NAME;
1129             break;
1130 
1131 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1132         case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1133             hci_state_reset();
1134             // prepare reset if command complete not received in 100ms
1135             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1136             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1137             btstack_run_loop_add_timer(&hci_stack->timeout);
1138             // send command
1139             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1140             hci_send_cmd(&hci_reset);
1141             break;
1142         case HCI_INIT_SEND_RESET_ST_WARM_BOOT:
1143             hci_state_reset();
1144             hci_stack->substate = HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT;
1145             hci_send_cmd(&hci_reset);
1146             break;
1147         case HCI_INIT_SEND_BAUD_CHANGE: {
1148             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1149             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1150             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1151             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1152             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1153             // STLC25000D: baudrate change happens within 0.5 s after command was send,
1154             // use timer to update baud rate after 100 ms (knowing exactly, when command was sent is non-trivial)
1155             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS){
1156                 btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1157                 btstack_run_loop_add_timer(&hci_stack->timeout);
1158             }
1159             break;
1160         }
1161         case HCI_INIT_SEND_BAUD_CHANGE_BCM: {
1162             uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1163             hci_stack->chipset->set_baudrate_command(baud_rate, hci_stack->hci_packet_buffer);
1164             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1165             hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE_BCM;
1166             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1167             break;
1168         }
1169         case HCI_INIT_CUSTOM_INIT:
1170             // Custom initialization
1171             if (hci_stack->chipset && hci_stack->chipset->next_command){
1172                 int valid_cmd = (*hci_stack->chipset->next_command)(hci_stack->hci_packet_buffer);
1173                 if (valid_cmd){
1174                     int size = 3 + hci_stack->hci_packet_buffer[2];
1175                     hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1176                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
1177                     switch (valid_cmd) {
1178                         case BTSTACK_CHIPSET_VALID_COMMAND:
1179                             hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT;
1180                             break;
1181                         case BTSTACK_CHIPSET_WARMSTART_REQUIRED:
1182                             // CSR Warm Boot: Wait a bit, then send HCI Reset until HCI Command Complete
1183                             log_info("CSR Warm Boot");
1184                             btstack_run_loop_set_timer(&hci_stack->timeout, HCI_RESET_RESEND_TIMEOUT_MS);
1185                             btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1186                             btstack_run_loop_add_timer(&hci_stack->timeout);
1187                             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO
1188                                 && hci_stack->config
1189                                 && hci_stack->chipset
1190                                 // && hci_stack->chipset->set_baudrate_command -- there's no such command
1191                                 && hci_stack->hci_transport->set_baudrate
1192                                 && hci_transport_uart_get_main_baud_rate()){
1193                                 hci_stack->substate = HCI_INIT_W4_SEND_BAUD_CHANGE;
1194                             } else {
1195                                hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT_LINK_RESET;
1196                             }
1197                             break;
1198                         default:
1199                             // should not get here
1200                             break;
1201                     }
1202                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
1203                     break;
1204                 }
1205                 log_info("Init script done");
1206 
1207                 // Init script download on Broadcom chipsets causes:
1208                 if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION
1209                 ||  hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA){
1210 
1211                     // - baud rate to reset, restore UART baud rate if needed
1212                     int need_baud_change = hci_stack->config
1213                         && hci_stack->chipset
1214                         && hci_stack->chipset->set_baudrate_command
1215                         && hci_stack->hci_transport->set_baudrate
1216                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1217                     if (need_baud_change) {
1218                         uint32_t baud_rate = ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_init;
1219                         log_info("Local baud rate change to %"PRIu32" after init script (bcm)", baud_rate);
1220                         hci_stack->hci_transport->set_baudrate(baud_rate);
1221                     }
1222 
1223                     // - RTS will raise during update, but manual RTS/CTS in WICED port on RedBear Duo cannot handle this
1224                     //   -> Work around: wait a few milliseconds here.
1225                     log_info("BCM delay after init script");
1226                     hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_BCM_DELAY;
1227                     btstack_run_loop_set_timer(&hci_stack->timeout, 10);
1228                     btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_initialization_timeout_handler);
1229                     btstack_run_loop_add_timer(&hci_stack->timeout);
1230                     break;
1231                 }
1232             }
1233             // otherwise continue
1234             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1235             hci_send_cmd(&hci_read_local_supported_commands);
1236             break;
1237         case HCI_INIT_SET_BD_ADDR:
1238             log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
1239             hci_stack->chipset->set_bd_addr_command(hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
1240             hci_stack->last_cmd_opcode = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
1241             hci_stack->substate = HCI_INIT_W4_SET_BD_ADDR;
1242             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
1243             break;
1244 #endif
1245 
1246         case HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS:
1247             log_info("Resend hci_read_local_supported_commands after CSR Warm Boot double reset");
1248             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS;
1249             hci_send_cmd(&hci_read_local_supported_commands);
1250             break;
1251         case HCI_INIT_READ_BD_ADDR:
1252             hci_stack->substate = HCI_INIT_W4_READ_BD_ADDR;
1253             hci_send_cmd(&hci_read_bd_addr);
1254             break;
1255         case HCI_INIT_READ_BUFFER_SIZE:
1256             hci_stack->substate = HCI_INIT_W4_READ_BUFFER_SIZE;
1257             hci_send_cmd(&hci_read_buffer_size);
1258             break;
1259         case HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES:
1260             hci_stack->substate = HCI_INIT_W4_READ_LOCAL_SUPPORTED_FEATURES;
1261             hci_send_cmd(&hci_read_local_supported_features);
1262             break;
1263 
1264 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
1265         case HCI_INIT_SET_CONTROLLER_TO_HOST_FLOW_CONTROL:
1266             hci_stack->substate = HCI_INIT_W4_SET_CONTROLLER_TO_HOST_FLOW_CONTROL;
1267             hci_send_cmd(&hci_set_controller_to_host_flow_control, 3);  // ACL + SCO Flow Control
1268             break;
1269         case HCI_INIT_HOST_BUFFER_SIZE:
1270             hci_stack->substate = HCI_INIT_W4_HOST_BUFFER_SIZE;
1271             hci_send_cmd(&hci_host_buffer_size, HCI_HOST_ACL_PACKET_LEN, HCI_HOST_SCO_PACKET_LEN,
1272                                                 HCI_HOST_ACL_PACKET_NUM, HCI_HOST_SCO_PACKET_NUM);
1273             break;
1274 #endif
1275 
1276         case HCI_INIT_SET_EVENT_MASK:
1277             hci_stack->substate = HCI_INIT_W4_SET_EVENT_MASK;
1278             if (hci_le_supported()){
1279                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
1280             } else {
1281                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
1282                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
1283             }
1284             break;
1285 
1286 #ifdef ENABLE_CLASSIC
1287         case HCI_INIT_WRITE_SIMPLE_PAIRING_MODE:
1288             hci_stack->substate = HCI_INIT_W4_WRITE_SIMPLE_PAIRING_MODE;
1289             hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
1290             break;
1291         case HCI_INIT_WRITE_PAGE_TIMEOUT:
1292             hci_stack->substate = HCI_INIT_W4_WRITE_PAGE_TIMEOUT;
1293             hci_send_cmd(&hci_write_page_timeout, 0x6000);  // ca. 15 sec
1294             break;
1295         case HCI_INIT_WRITE_CLASS_OF_DEVICE:
1296             hci_stack->substate = HCI_INIT_W4_WRITE_CLASS_OF_DEVICE;
1297             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
1298             break;
1299         case HCI_INIT_WRITE_LOCAL_NAME: {
1300             hci_stack->substate = HCI_INIT_W4_WRITE_LOCAL_NAME;
1301             hci_reserve_packet_buffer();
1302             uint8_t * packet = hci_stack->hci_packet_buffer;
1303             // construct HCI Command and send
1304             uint16_t opcode = hci_write_local_name.opcode;
1305             hci_stack->last_cmd_opcode = opcode;
1306             packet[0] = opcode & 0xff;
1307             packet[1] = opcode >> 8;
1308             packet[2] = DEVICE_NAME_LEN;
1309             memset(&packet[3], 0, DEVICE_NAME_LEN);
1310             memcpy(&packet[3], hci_stack->local_name, strlen(hci_stack->local_name));
1311             // expand '00:00:00:00:00:00' in name with bd_addr
1312             hci_replace_bd_addr_placeholder(&packet[3], DEVICE_NAME_LEN);
1313             hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + DEVICE_NAME_LEN);
1314             break;
1315         }
1316         case HCI_INIT_WRITE_EIR_DATA: {
1317             hci_stack->substate = HCI_INIT_W4_WRITE_EIR_DATA;
1318             hci_reserve_packet_buffer();
1319             uint8_t * packet = hci_stack->hci_packet_buffer;
1320             // construct HCI Command and send
1321             uint16_t opcode = hci_write_extended_inquiry_response.opcode;
1322             hci_stack->last_cmd_opcode = opcode;
1323             packet[0] = opcode & 0xff;
1324             packet[1] = opcode >> 8;
1325             packet[2] = 1 + 240;
1326             packet[3] = 0;  // FEC not required
1327             if (hci_stack->eir_data){
1328                 memcpy(&packet[4], hci_stack->eir_data, 240);
1329             } else {
1330                 memset(&packet[4], 0, 240);
1331                 int name_len = strlen(hci_stack->local_name);
1332                 packet[4] = name_len + 1;
1333                 packet[5] = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME;
1334                 memcpy(&packet[6], hci_stack->local_name, name_len);
1335             }
1336             // expand '00:00:00:00:00:00' in name with bd_addr
1337             hci_replace_bd_addr_placeholder(&packet[4], 240);
1338             hci_send_cmd_packet(packet, HCI_CMD_HEADER_SIZE + 1 + 240);
1339             break;
1340         }
1341         case HCI_INIT_WRITE_INQUIRY_MODE:
1342             hci_stack->substate = HCI_INIT_W4_WRITE_INQUIRY_MODE;
1343             hci_send_cmd(&hci_write_inquiry_mode, (int) hci_stack->inquiry_mode);
1344             break;
1345         case HCI_INIT_WRITE_SCAN_ENABLE:
1346             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
1347             hci_stack->substate = HCI_INIT_W4_WRITE_SCAN_ENABLE;
1348             break;
1349         // only sent if ENABLE_SCO_OVER_HCI is defined
1350         case HCI_INIT_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1351             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1352             hci_send_cmd(&hci_write_synchronous_flow_control_enable, 1); // SCO tracking enabled
1353             break;
1354         case HCI_INIT_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1355             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1356             hci_send_cmd(&hci_write_default_erroneous_data_reporting, 1);
1357             break;
1358         // only sent if ENABLE_SCO_OVER_HCI and manufacturer is Broadcom
1359         case HCI_INIT_BCM_WRITE_SCO_PCM_INT:
1360             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1361             log_info("BCM: Route SCO data via HCI transport");
1362             hci_send_cmd(&hci_bcm_write_sco_pcm_int, 1, 0, 0, 0, 0);
1363             break;
1364 
1365 #endif
1366 #ifdef ENABLE_BLE
1367         // LE INIT
1368         case HCI_INIT_LE_READ_BUFFER_SIZE:
1369             hci_stack->substate = HCI_INIT_W4_LE_READ_BUFFER_SIZE;
1370             hci_send_cmd(&hci_le_read_buffer_size);
1371             break;
1372         case HCI_INIT_LE_SET_EVENT_MASK:
1373             hci_stack->substate = HCI_INIT_W4_LE_SET_EVENT_MASK;
1374             hci_send_cmd(&hci_le_set_event_mask, 0x1FF, 0x0);
1375             break;
1376         case HCI_INIT_WRITE_LE_HOST_SUPPORTED:
1377             // LE Supported Host = 1, Simultaneous Host = 0
1378             hci_stack->substate = HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED;
1379             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
1380             break;
1381 #endif
1382 
1383 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1384         case HCI_INIT_LE_READ_MAX_DATA_LENGTH:
1385             hci_stack->substate = HCI_INIT_W4_LE_READ_MAX_DATA_LENGTH;
1386             hci_send_cmd(&hci_le_read_maximum_data_length);
1387             break;
1388         case HCI_INIT_LE_WRITE_SUGGESTED_DATA_LENGTH:
1389             hci_stack->substate = HCI_INIT_W4_LE_WRITE_SUGGESTED_DATA_LENGTH;
1390             hci_send_cmd(&hci_le_write_suggested_default_data_length, hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time);
1391             break;
1392 #endif
1393 
1394 #ifdef ENABLE_LE_CENTRAL
1395         case HCI_INIT_READ_WHITE_LIST_SIZE:
1396             hci_stack->substate = HCI_INIT_W4_READ_WHITE_LIST_SIZE;
1397             hci_send_cmd(&hci_le_read_white_list_size);
1398             break;
1399         case HCI_INIT_LE_SET_SCAN_PARAMETERS:
1400             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, own address type, accept all advs
1401             hci_stack->substate = HCI_INIT_W4_LE_SET_SCAN_PARAMETERS;
1402             hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, hci_stack->le_own_addr_type, 0);
1403             break;
1404 #endif
1405         default:
1406             return;
1407     }
1408 }
1409 
1410 static void hci_init_done(void){
1411     // done. tell the app
1412     log_info("hci_init_done -> HCI_STATE_WORKING");
1413     hci_stack->state = HCI_STATE_WORKING;
1414     hci_emit_state();
1415     hci_run();
1416 }
1417 
1418 static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
1419 
1420     UNUSED(size);   // ok: less than 6 bytes are read from our buffer
1421 
1422     uint8_t command_completed = 0;
1423 
1424     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE){
1425         uint16_t opcode = little_endian_read_16(packet,3);
1426         if (opcode == hci_stack->last_cmd_opcode){
1427             command_completed = 1;
1428             log_debug("Command complete for expected opcode %04x at substate %u", opcode, hci_stack->substate);
1429         } else {
1430             log_info("Command complete for different opcode %04x, expected %04x, at substate %u", opcode, hci_stack->last_cmd_opcode, hci_stack->substate);
1431         }
1432     }
1433 
1434     if (hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_STATUS){
1435         uint8_t  status = packet[2];
1436         uint16_t opcode = little_endian_read_16(packet,4);
1437         if (opcode == hci_stack->last_cmd_opcode){
1438             if (status){
1439                 command_completed = 1;
1440                 log_debug("Command status error 0x%02x for expected opcode %04x at substate %u", status, opcode, hci_stack->substate);
1441             } else {
1442                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
1443             }
1444         } else {
1445             log_debug("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
1446         }
1447     }
1448 
1449 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1450 
1451     // Vendor == CSR
1452     if (hci_stack->substate == HCI_INIT_W4_CUSTOM_INIT && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
1453         // TODO: track actual command
1454         command_completed = 1;
1455     }
1456 
1457     // Vendor == Toshiba
1458     if (hci_stack->substate == HCI_INIT_W4_SEND_BAUD_CHANGE && hci_event_packet_get_type(packet) == HCI_EVENT_VENDOR_SPECIFIC){
1459         // TODO: track actual command
1460         command_completed = 1;
1461         // Fix: no HCI Command Complete received, so num_cmd_packets not reset
1462         hci_stack->num_cmd_packets = 1;
1463     }
1464 
1465     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
1466     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
1467     //
1468     // HCI Reset
1469     // Timeout 100 ms
1470     // HCI Reset
1471     // Command Complete Reset
1472     // HCI Read Local Version Information
1473     // Command Complete Reset - but we expected Command Complete Read Local Version Information
1474     // hang...
1475     //
1476     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1477     if (!command_completed
1478             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
1479             && hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION){
1480 
1481         uint16_t opcode = little_endian_read_16(packet,3);
1482         if (opcode == hci_reset.opcode){
1483             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
1484             return;
1485         }
1486     }
1487 
1488     // CSR & H5
1489     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1490     if (!command_completed
1491             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
1492             && hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS){
1493 
1494         uint16_t opcode = little_endian_read_16(packet,3);
1495         if (opcode == hci_reset.opcode){
1496             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1497             return;
1498         }
1499     }
1500 
1501     // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT
1502     // fix: Correct substate and behave as command below
1503     if (command_completed){
1504         switch (hci_stack->substate){
1505             case HCI_INIT_SEND_RESET:
1506                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1507                 break;
1508             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1509                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1510                 break;
1511             default:
1512                 break;
1513         }
1514     }
1515 
1516 #endif
1517 
1518     if (!command_completed) return;
1519 
1520     int need_baud_change = 0;
1521     int need_addr_change = 0;
1522 
1523 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1524     need_baud_change = hci_stack->config
1525                         && hci_stack->chipset
1526                         && hci_stack->chipset->set_baudrate_command
1527                         && hci_stack->hci_transport->set_baudrate
1528                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1529 
1530     need_addr_change = hci_stack->custom_bd_addr_set
1531                         && hci_stack->chipset
1532                         && hci_stack->chipset->set_bd_addr_command;
1533 #endif
1534 
1535     switch(hci_stack->substate){
1536 
1537 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1538         case HCI_INIT_SEND_RESET:
1539             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
1540             // fix: just correct substate and behave as command below
1541             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1542             btstack_run_loop_remove_timer(&hci_stack->timeout);
1543             break;
1544         case HCI_INIT_W4_SEND_RESET:
1545             btstack_run_loop_remove_timer(&hci_stack->timeout);
1546             break;
1547         case HCI_INIT_W4_SEND_READ_LOCAL_NAME:
1548             log_info("Received local name, need baud change %d", need_baud_change);
1549             if (need_baud_change){
1550                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE;
1551                 return;
1552             }
1553             // skip baud change
1554             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1555             return;
1556         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1557             // for STLC2500D, baud rate change already happened.
1558             // for others, baud rate gets changed now
1559             if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
1560                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1561                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change)", baud_rate);
1562                 hci_stack->hci_transport->set_baudrate(baud_rate);
1563             }
1564             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1565             return;
1566         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1567             btstack_run_loop_remove_timer(&hci_stack->timeout);
1568             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1569             return;
1570         case HCI_INIT_W4_CUSTOM_INIT:
1571             // repeat custom init
1572             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1573             return;
1574 #else
1575         case HCI_INIT_W4_SEND_RESET:
1576             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1577             return ;
1578 #endif
1579 
1580         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
1581             if (need_baud_change &&
1582               ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) ||
1583                (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA))) {
1584                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
1585                 return;
1586             }
1587             if (need_addr_change){
1588                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1589                 return;
1590             }
1591             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1592             return;
1593 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1594         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
1595             if (need_baud_change){
1596                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1597                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change_bcm))", baud_rate);
1598                 hci_stack->hci_transport->set_baudrate(baud_rate);
1599             }
1600             if (need_addr_change){
1601                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1602                 return;
1603             }
1604             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1605             return;
1606         case HCI_INIT_W4_SET_BD_ADDR:
1607             // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command
1608             if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS)
1609             ||  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){
1610                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
1611                 return;
1612             }
1613             // skipping st warm boot
1614             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1615             return;
1616         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
1617             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1618             return;
1619 #endif
1620         case HCI_INIT_W4_READ_BD_ADDR:
1621             // only read buffer size if supported
1622             if (hci_stack->local_supported_commands[0] & 0x01) {
1623                 hci_stack->substate = HCI_INIT_READ_BUFFER_SIZE;
1624                 return;
1625             }
1626             // skipping read buffer size
1627             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES;
1628             return;
1629         case HCI_INIT_W4_SET_EVENT_MASK:
1630             // skip Classic init commands for LE only chipsets
1631             if (!hci_classic_supported()){
1632 #ifdef ENABLE_BLE
1633                 if (hci_le_supported()){
1634                     hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE; // skip all classic command
1635                     return;
1636                 }
1637 #endif
1638                 log_error("Neither BR/EDR nor LE supported");
1639                 hci_init_done();
1640                 return;
1641             }
1642             if (!gap_ssp_supported()){
1643                 hci_stack->substate = HCI_INIT_WRITE_PAGE_TIMEOUT;
1644                 return;
1645             }
1646             break;
1647 #ifdef ENABLE_BLE
1648         case HCI_INIT_W4_LE_READ_BUFFER_SIZE:
1649             // skip write le host if not supported (e.g. on LE only EM9301)
1650             if (hci_stack->local_supported_commands[0] & 0x02) break;
1651             hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1652             return;
1653 
1654 
1655 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1656         case HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED:
1657             if ((hci_stack->local_supported_commands[0] & 0x30) == 0x30){
1658                 hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1659                 return;
1660             }
1661             // explicit fall through to reduce repetitions
1662 #endif
1663 
1664 #ifdef ENABLE_LE_CENTRAL
1665             hci_stack->substate = HCI_INIT_READ_WHITE_LIST_SIZE;
1666 #else
1667             hci_init_done();
1668 #endif
1669             return;
1670 #endif
1671 
1672 #ifdef ENABLE_SCO_OVER_HCI
1673         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1674             // skip write synchronous flow control if not supported
1675             if (hci_stack->local_supported_commands[0] & 0x04) break;
1676             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1677             // explicit fall through to reduce repetitions
1678 
1679         case HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1680             // skip write default erroneous data reporting if not supported
1681             if (hci_stack->local_supported_commands[0] & 0x08) break;
1682             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1683             // explicit fall through to reduce repetitions
1684 
1685         case HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1686             // skip bcm set sco pcm config on non-Broadcom chipsets
1687             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) break;
1688             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1689             // explicit fall through to reduce repetitions
1690 
1691         case HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT:
1692             if (!hci_le_supported()){
1693                 // SKIP LE init for Classic only configuration
1694                 hci_init_done();
1695                 return;
1696             }
1697             break;
1698 
1699 #else /* !ENABLE_SCO_OVER_HCI */
1700 
1701         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1702 #ifdef ENABLE_BLE
1703             if (hci_le_supported()){
1704                 hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE;
1705                 return;
1706             }
1707 #endif
1708             // SKIP LE init for Classic only configuration
1709             hci_init_done();
1710             return;
1711 #endif /* ENABLE_SCO_OVER_HCI */
1712 
1713         // Response to command before init done state -> init done
1714         case (HCI_INIT_DONE-1):
1715             hci_init_done();
1716             return;
1717 
1718         default:
1719             break;
1720     }
1721     hci_initializing_next_state();
1722 }
1723 
1724 static void event_handler(uint8_t *packet, int size){
1725 
1726     uint16_t event_length = packet[1];
1727 
1728     // assert packet is complete
1729     if (size != event_length + 2){
1730         log_error("hci.c: event_handler called with event packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
1731         return;
1732     }
1733 
1734     bd_addr_t addr;
1735     bd_addr_type_t addr_type;
1736     hci_con_handle_t handle;
1737     hci_connection_t * conn;
1738     int i;
1739 #ifdef ENABLE_CLASSIC
1740     uint8_t link_type;
1741 #endif
1742 
1743     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
1744 
1745     switch (hci_event_packet_get_type(packet)) {
1746 
1747         case HCI_EVENT_COMMAND_COMPLETE:
1748             // get num cmd packets - limit to 1 to reduce complexity
1749             hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
1750 
1751             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_name)){
1752                 if (packet[5]) break;
1753                 // terminate, name 248 chars
1754                 packet[6+248] = 0;
1755                 log_info("local name: %s", &packet[6]);
1756             }
1757             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_buffer_size)){
1758                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
1759                 if (hci_stack->state == HCI_STATE_INITIALIZING){
1760                     uint16_t acl_len = little_endian_read_16(packet, 6);
1761                     uint16_t sco_len = packet[8];
1762 
1763                     // determine usable ACL/SCO payload size
1764                     hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
1765                     hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
1766 
1767                     hci_stack->acl_packets_total_num  = little_endian_read_16(packet, 9);
1768                     hci_stack->sco_packets_total_num  = little_endian_read_16(packet, 11);
1769 
1770                     log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
1771                              acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
1772                              hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
1773                 }
1774             }
1775 #ifdef ENABLE_BLE
1776             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_buffer_size)){
1777                 hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
1778                 hci_stack->le_acl_packets_total_num  = packet[8];
1779                 // determine usable ACL payload size
1780                 if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
1781                     hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
1782                 }
1783                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
1784             }
1785 #endif
1786 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1787             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_maximum_data_length)){
1788                 hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
1789                 hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
1790                 log_info("hci_le_read_maximum_data_length: tx octets %u, tx time %u us", hci_stack->le_supported_max_tx_octets, hci_stack->le_supported_max_tx_time);
1791             }
1792 #endif
1793 #ifdef ENABLE_LE_CENTRAL
1794             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_white_list_size)){
1795                 hci_stack->le_whitelist_capacity = packet[6];
1796                 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
1797             }
1798 #endif
1799             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
1800                 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1],
1801 				hci_stack->local_bd_addr);
1802                 log_info("Local Address, Status: 0x%02x: Addr: %s",
1803                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
1804 #ifdef ENABLE_CLASSIC
1805                 if (hci_stack->link_key_db){
1806                     hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
1807                 }
1808 #endif
1809             }
1810 #ifdef ENABLE_CLASSIC
1811             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
1812                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1813             }
1814             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_inquiry_cancel)){
1815                 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
1816                     hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
1817                     uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
1818                     hci_emit_event(event, sizeof(event), 1);
1819                 }
1820             }
1821 #endif
1822 
1823             // Note: HCI init checks
1824             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_features)){
1825                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
1826 
1827 #ifdef ENABLE_CLASSIC
1828                 // determine usable ACL packet types based on host buffer size and supported features
1829                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
1830                 log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
1831 #endif
1832                 // Classic/LE
1833                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1834             }
1835             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_version_information)){
1836                 // hci_stack->hci_version    = little_endian_read_16(packet, 4);
1837                 // hci_stack->hci_revision   = little_endian_read_16(packet, 6);
1838                 // hci_stack->lmp_version    = little_endian_read_16(packet, 8);
1839                 hci_stack->manufacturer   = little_endian_read_16(packet, 10);
1840                 // hci_stack->lmp_subversion = little_endian_read_16(packet, 12);
1841                 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
1842             }
1843             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
1844                 hci_stack->local_supported_commands[0] =
1845                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+14] & 0x80) >> 7 |  // bit 0 = Octet 14, bit 7
1846                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+24] & 0x40) >> 5 |  // bit 1 = Octet 24, bit 6
1847                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+10] & 0x10) >> 2 |  // bit 2 = Octet 10, bit 4
1848                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+18] & 0x08)      |  // bit 3 = Octet 18, bit 3
1849                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+34] & 0x01) << 4 |  // bit 4 = Octet 34, bit 0
1850                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+35] & 0x08) << 2;   // bit 5 = Octet 35, bit 3
1851                     log_info("Local supported commands summary 0x%02x", hci_stack->local_supported_commands[0]);
1852             }
1853 #ifdef ENABLE_CLASSIC
1854             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_synchronous_flow_control_enable)){
1855                 if (packet[5] == 0){
1856                     hci_stack->synchronous_flow_control_enabled = 1;
1857                 }
1858             }
1859 #endif
1860             break;
1861 
1862         case HCI_EVENT_COMMAND_STATUS:
1863             // get num cmd packets - limit to 1 to reduce complexity
1864             hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
1865             break;
1866 
1867         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
1868             int offset = 3;
1869             for (i=0; i<packet[2];i++){
1870                 handle = little_endian_read_16(packet, offset);
1871                 offset += 2;
1872                 uint16_t num_packets = little_endian_read_16(packet, offset);
1873                 offset += 2;
1874 
1875                 conn = hci_connection_for_handle(handle);
1876                 if (!conn){
1877                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
1878                     continue;
1879                 }
1880 
1881                 if (conn->address_type == BD_ADDR_TYPE_SCO){
1882 #ifdef ENABLE_CLASSIC
1883                     if (conn->num_sco_packets_sent >= num_packets){
1884                         conn->num_sco_packets_sent -= num_packets;
1885                     } else {
1886                         log_error("hci_number_completed_packets, more sco slots freed then sent.");
1887                         conn->num_sco_packets_sent = 0;
1888                     }
1889                     hci_notify_if_sco_can_send_now();
1890 #endif
1891                 } else {
1892                     if (conn->num_acl_packets_sent >= num_packets){
1893                         conn->num_acl_packets_sent -= num_packets;
1894                     } else {
1895                         log_error("hci_number_completed_packets, more acl slots freed then sent.");
1896                         conn->num_acl_packets_sent = 0;
1897                     }
1898                 }
1899                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
1900             }
1901             break;
1902         }
1903 
1904 #ifdef ENABLE_CLASSIC
1905         case HCI_EVENT_INQUIRY_COMPLETE:
1906             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
1907                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
1908                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
1909                 hci_emit_event(event, sizeof(event), 1);
1910             }
1911             break;
1912         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
1913             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
1914                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
1915             }
1916             break;
1917         case HCI_EVENT_CONNECTION_REQUEST:
1918             reverse_bd_addr(&packet[2], addr);
1919             // TODO: eval COD 8-10
1920             link_type = packet[11];
1921             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
1922             addr_type = link_type == 1 ? BD_ADDR_TYPE_CLASSIC : BD_ADDR_TYPE_SCO;
1923             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1924             if (!conn) {
1925                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1926             }
1927             if (!conn) {
1928                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
1929                 hci_stack->decline_reason = 0x0d;
1930                 bd_addr_copy(hci_stack->decline_addr, addr);
1931                 break;
1932             }
1933             conn->role  = HCI_ROLE_SLAVE;
1934             conn->state = RECEIVED_CONNECTION_REQUEST;
1935             // store info about eSCO
1936             if (link_type == 0x02){
1937                 conn->remote_supported_feature_eSCO = 1;
1938             }
1939             hci_run();
1940             break;
1941 
1942         case HCI_EVENT_CONNECTION_COMPLETE:
1943             // Connection management
1944             reverse_bd_addr(&packet[5], addr);
1945             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1946             addr_type = BD_ADDR_TYPE_CLASSIC;
1947             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1948             if (conn) {
1949                 if (!packet[2]){
1950                     conn->state = OPEN;
1951                     conn->con_handle = little_endian_read_16(packet, 3);
1952                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
1953 
1954                     // restart timer
1955                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1956                     btstack_run_loop_add_timer(&conn->timeout);
1957 
1958                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1959 
1960                     hci_emit_nr_connections_changed();
1961                 } else {
1962                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
1963                     uint8_t status = packet[2];
1964                     bd_addr_t bd_address;
1965                     memcpy(&bd_address, conn->address, 6);
1966 
1967                     // connection failed, remove entry
1968                     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1969                     btstack_memory_hci_connection_free( conn );
1970 
1971                     // notify client if dedicated bonding
1972                     if (notify_dedicated_bonding_failed){
1973                         log_info("hci notify_dedicated_bonding_failed");
1974                         hci_emit_dedicated_bonding_result(bd_address, status);
1975                     }
1976 
1977                     // if authentication error, also delete link key
1978                     if (packet[2] == 0x05) {
1979                         gap_drop_link_key_for_bd_addr(addr);
1980                     }
1981                 }
1982             }
1983             break;
1984 
1985         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
1986             reverse_bd_addr(&packet[5], addr);
1987             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1988             if (packet[2]){
1989                 // connection failed
1990                 break;
1991             }
1992             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1993             if (!conn) {
1994                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1995             }
1996             if (!conn) {
1997                 break;
1998             }
1999             conn->state = OPEN;
2000             conn->con_handle = little_endian_read_16(packet, 3);
2001 
2002 #ifdef ENABLE_SCO_OVER_HCI
2003             // update SCO
2004             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
2005                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
2006             }
2007 #endif
2008             break;
2009 
2010         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2011             handle = little_endian_read_16(packet, 3);
2012             conn = hci_connection_for_handle(handle);
2013             if (!conn) break;
2014             if (!packet[2]){
2015                 uint8_t * features = &packet[5];
2016                 if (features[6] & (1 << 3)){
2017                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
2018                 }
2019                 if (features[3] & (1<<7)){
2020                     conn->remote_supported_feature_eSCO = 1;
2021                 }
2022             }
2023             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
2024             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x, eSCO %u", conn->bonding_flags, conn->remote_supported_feature_eSCO);
2025             if (conn->bonding_flags & BONDING_DEDICATED){
2026                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2027             }
2028             break;
2029 
2030         case HCI_EVENT_LINK_KEY_REQUEST:
2031             log_info("HCI_EVENT_LINK_KEY_REQUEST");
2032             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
2033             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
2034             if (hci_stack->bondable && !hci_stack->link_key_db) break;
2035             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
2036             hci_run();
2037             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
2038             return;
2039 
2040         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
2041             reverse_bd_addr(&packet[2], addr);
2042             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2043             if (!conn) break;
2044             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
2045             link_key_type_t link_key_type = (link_key_type_t)packet[24];
2046             // Change Connection Encryption keeps link key type
2047             if (link_key_type != CHANGED_COMBINATION_KEY){
2048                 conn->link_key_type = link_key_type;
2049             }
2050             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
2051             // still forward event to allow dismiss of pairing dialog
2052             break;
2053         }
2054 
2055         case HCI_EVENT_PIN_CODE_REQUEST:
2056             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
2057             // non-bondable mode: pin code negative reply will be sent
2058             if (!hci_stack->bondable){
2059                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
2060                 hci_run();
2061                 return;
2062             }
2063             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
2064             if (!hci_stack->link_key_db) break;
2065             hci_event_pin_code_request_get_bd_addr(packet, addr);
2066             hci_stack->link_key_db->delete_link_key(addr);
2067             break;
2068 
2069         case HCI_EVENT_IO_CAPABILITY_REQUEST:
2070             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
2071             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
2072             break;
2073 
2074         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
2075             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2076             if (!hci_stack->ssp_auto_accept) break;
2077             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
2078             break;
2079 
2080         case HCI_EVENT_USER_PASSKEY_REQUEST:
2081             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2082             if (!hci_stack->ssp_auto_accept) break;
2083             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
2084             break;
2085 #endif
2086 
2087         case HCI_EVENT_ENCRYPTION_CHANGE:
2088             handle = little_endian_read_16(packet, 3);
2089             conn = hci_connection_for_handle(handle);
2090             if (!conn) break;
2091             if (packet[2] == 0) {
2092                 if (packet[5]){
2093                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
2094                 } else {
2095                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
2096                 }
2097             }
2098 #ifdef ENABLE_CLASSIC
2099             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2100 #endif
2101             break;
2102 
2103 #ifdef ENABLE_CLASSIC
2104         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
2105             handle = little_endian_read_16(packet, 3);
2106             conn = hci_connection_for_handle(handle);
2107             if (!conn) break;
2108 
2109             // dedicated bonding: send result and disconnect
2110             if (conn->bonding_flags & BONDING_DEDICATED){
2111                 conn->bonding_flags &= ~BONDING_DEDICATED;
2112                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2113                 conn->bonding_status = packet[2];
2114                 break;
2115             }
2116 
2117             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
2118                 // link key sufficient for requested security
2119                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2120                 break;
2121             }
2122             // not enough
2123             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2124             break;
2125 #endif
2126 
2127         // HCI_EVENT_DISCONNECTION_COMPLETE
2128         // has been split, to first notify stack before shutting connection down
2129         // see end of function, too.
2130         case HCI_EVENT_DISCONNECTION_COMPLETE:
2131             if (packet[2]) break;   // status != 0
2132             handle = little_endian_read_16(packet, 3);
2133             // drop outgoing ACL fragments if it is for closed connection
2134             if (hci_stack->acl_fragmentation_total_size > 0) {
2135                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
2136                     log_info("hci: drop fragmented ACL data for closed connection");
2137                      hci_stack->acl_fragmentation_total_size = 0;
2138                      hci_stack->acl_fragmentation_pos = 0;
2139                 }
2140             }
2141 
2142             // re-enable advertisements for le connections if active
2143             conn = hci_connection_for_handle(handle);
2144             if (!conn) break;
2145 #ifdef ENABLE_BLE
2146 #ifdef ENABLE_LE_PERIPHERAL
2147             if (hci_is_le_connection(conn) && hci_stack->le_advertisements_enabled){
2148                 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
2149             }
2150 #endif
2151 #endif
2152             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
2153             break;
2154 
2155         case HCI_EVENT_HARDWARE_ERROR:
2156             log_error("Hardware Error: 0x%02x", packet[2]);
2157             if (hci_stack->hardware_error_callback){
2158                 (*hci_stack->hardware_error_callback)(packet[2]);
2159             } else {
2160                 // if no special requests, just reboot stack
2161                 hci_power_control_off();
2162                 hci_power_control_on();
2163             }
2164             break;
2165 
2166 #ifdef ENABLE_CLASSIC
2167         case HCI_EVENT_ROLE_CHANGE:
2168             if (packet[2]) break;   // status != 0
2169             reverse_bd_addr(&packet[3], addr);
2170             addr_type = BD_ADDR_TYPE_CLASSIC;
2171             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2172             if (!conn) break;
2173             conn->role = packet[9];
2174             break;
2175 #endif
2176 
2177         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2178             // release packet buffer only for asynchronous transport and if there are not further fragements
2179             if (hci_transport_synchronous()) {
2180                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
2181                 return; // instead of break: to avoid re-entering hci_run()
2182             }
2183             if (hci_stack->acl_fragmentation_total_size) break;
2184             hci_release_packet_buffer();
2185 
2186             // L2CAP receives this event via the hci_emit_event below
2187 
2188 #ifdef ENABLE_CLASSIC
2189             // For SCO, we do the can_send_now_check here
2190             hci_notify_if_sco_can_send_now();
2191 #endif
2192             break;
2193 
2194 #ifdef ENABLE_CLASSIC
2195         case HCI_EVENT_SCO_CAN_SEND_NOW:
2196             // For SCO, we do the can_send_now_check here
2197             hci_notify_if_sco_can_send_now();
2198             return;
2199 
2200         // explode inquriy results for easier consumption
2201         case HCI_EVENT_INQUIRY_RESULT:
2202         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
2203         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
2204             gap_inquiry_explode(packet);
2205             break;
2206 #endif
2207 
2208 #ifdef ENABLE_BLE
2209         case HCI_EVENT_LE_META:
2210             switch (packet[2]){
2211 #ifdef ENABLE_LE_CENTRAL
2212                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
2213                     // log_info("advertising report received");
2214                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
2215                     le_handle_advertisement_report(packet, size);
2216                     break;
2217 #endif
2218                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
2219                     // Connection management
2220                     reverse_bd_addr(&packet[8], addr);
2221                     addr_type = (bd_addr_type_t)packet[7];
2222                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
2223                     conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2224 
2225 #ifdef ENABLE_LE_CENTRAL
2226                     // if auto-connect, remove from whitelist in both roles
2227                     if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){
2228                         hci_remove_from_whitelist(addr_type, addr);
2229                     }
2230                     // handle error: error is reported only to the initiator -> outgoing connection
2231                     if (packet[3]){
2232 
2233                         // handle cancelled outgoing connection
2234                         // "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
2235                         //  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
2236                         //  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
2237                         if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
2238                             conn = gap_get_outgoing_connection();
2239                         }
2240 
2241                         // outgoing connection establishment is done
2242                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2243                         // remove entry
2244                         if (conn){
2245                             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2246                             btstack_memory_hci_connection_free( conn );
2247                         }
2248                         break;
2249                     }
2250 #endif
2251                     // on success, both hosts receive connection complete event
2252                     if (packet[6] == HCI_ROLE_MASTER){
2253 #ifdef ENABLE_LE_CENTRAL
2254                         // if we're master, it was an outgoing connection and we're done with it
2255                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2256 #endif
2257                     } else {
2258 #ifdef ENABLE_LE_PERIPHERAL
2259                         // if we're slave, it was an incoming connection, advertisements have stopped
2260                         hci_stack->le_advertisements_active = 0;
2261                         // try to re-enable them
2262                         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
2263 #endif
2264                     }
2265                     // LE connections are auto-accepted, so just create a connection if there isn't one already
2266                     if (!conn){
2267                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2268                     }
2269                     // no memory, sorry.
2270                     if (!conn){
2271                         break;
2272                     }
2273 
2274                     conn->state = OPEN;
2275                     conn->role  = packet[6];
2276                     conn->con_handle = little_endian_read_16(packet, 4);
2277 
2278                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
2279 
2280                     // restart timer
2281                     // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2282                     // btstack_run_loop_add_timer(&conn->timeout);
2283 
2284                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2285 
2286                     hci_emit_nr_connections_changed();
2287                     break;
2288 
2289             // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
2290 
2291                 default:
2292                     break;
2293             }
2294             break;
2295 #endif
2296         default:
2297             break;
2298     }
2299 
2300     // handle BT initialization
2301     if (hci_stack->state == HCI_STATE_INITIALIZING){
2302         hci_initializing_event_handler(packet, size);
2303     }
2304 
2305     // help with BT sleep
2306     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
2307         && hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE
2308         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
2309         hci_initializing_next_state();
2310     }
2311 
2312     // notify upper stack
2313 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
2314 
2315     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
2316     if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){
2317         if (!packet[2]){
2318             handle = little_endian_read_16(packet, 3);
2319             hci_connection_t * aConn = hci_connection_for_handle(handle);
2320             if (aConn) {
2321                 uint8_t status = aConn->bonding_status;
2322                 uint16_t flags = aConn->bonding_flags;
2323                 bd_addr_t bd_address;
2324                 memcpy(&bd_address, aConn->address, 6);
2325                 hci_shutdown_connection(aConn);
2326                 // connection struct is gone, don't access anymore
2327                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
2328                     hci_emit_dedicated_bonding_result(bd_address, status);
2329                 }
2330             }
2331         }
2332     }
2333 
2334 	// execute main loop
2335 	hci_run();
2336 }
2337 
2338 #ifdef ENABLE_CLASSIC
2339 static void sco_handler(uint8_t * packet, uint16_t size){
2340     if (!hci_stack->sco_packet_handler) return;
2341     hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
2342 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2343     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
2344     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
2345     if (conn){
2346         conn->num_packets_completed++;
2347         hci_stack->host_completed_packets = 1;
2348         hci_run();
2349     }
2350 #endif
2351 }
2352 #endif
2353 
2354 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
2355     hci_dump_packet(packet_type, 1, packet, size);
2356     switch (packet_type) {
2357         case HCI_EVENT_PACKET:
2358             event_handler(packet, size);
2359             break;
2360         case HCI_ACL_DATA_PACKET:
2361             acl_handler(packet, size);
2362             break;
2363 #ifdef ENABLE_CLASSIC
2364         case HCI_SCO_DATA_PACKET:
2365             sco_handler(packet, size);
2366             break;
2367 #endif
2368         default:
2369             break;
2370     }
2371 }
2372 
2373 /**
2374  * @brief Add event packet handler.
2375  */
2376 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
2377     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
2378 }
2379 
2380 
2381 /** Register HCI packet handlers */
2382 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
2383     hci_stack->acl_packet_handler = handler;
2384 }
2385 
2386 #ifdef ENABLE_CLASSIC
2387 /**
2388  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
2389  */
2390 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
2391     hci_stack->sco_packet_handler = handler;
2392 }
2393 #endif
2394 
2395 static void hci_state_reset(void){
2396     // no connections yet
2397     hci_stack->connections = NULL;
2398 
2399     // keep discoverable/connectable as this has been requested by the client(s)
2400     // hci_stack->discoverable = 0;
2401     // hci_stack->connectable = 0;
2402     // hci_stack->bondable = 1;
2403     // hci_stack->own_addr_type = 0;
2404 
2405     // buffer is free
2406     hci_stack->hci_packet_buffer_reserved = 0;
2407 
2408     // no pending cmds
2409     hci_stack->decline_reason = 0;
2410     hci_stack->new_scan_enable_value = 0xff;
2411 
2412     // LE
2413 #ifdef ENABLE_BLE
2414     memset(hci_stack->le_random_address, 0, 6);
2415     hci_stack->le_random_address_set = 0;
2416 #endif
2417 #ifdef ENABLE_LE_CENTRAL
2418     hci_stack->le_scanning_state = LE_SCAN_IDLE;
2419     hci_stack->le_scan_type = 0xff;
2420     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2421     hci_stack->le_whitelist = 0;
2422     hci_stack->le_whitelist_capacity = 0;
2423 #endif
2424 }
2425 
2426 #ifdef ENABLE_CLASSIC
2427 /**
2428  * @brief Configure Bluetooth hardware control. Has to be called before power on.
2429  */
2430 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
2431     // store and open remote device db
2432     hci_stack->link_key_db = link_key_db;
2433     if (hci_stack->link_key_db) {
2434         hci_stack->link_key_db->open();
2435     }
2436 }
2437 #endif
2438 
2439 void hci_init(const hci_transport_t *transport, const void *config){
2440 
2441 #ifdef HAVE_MALLOC
2442     if (!hci_stack) {
2443         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
2444     }
2445 #else
2446     hci_stack = &hci_stack_static;
2447 #endif
2448     memset(hci_stack, 0, sizeof(hci_stack_t));
2449 
2450     // reference to use transport layer implementation
2451     hci_stack->hci_transport = transport;
2452 
2453     // reference to used config
2454     hci_stack->config = config;
2455 
2456     // setup pointer for outgoing packet buffer
2457     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
2458 
2459     // max acl payload size defined in config.h
2460     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
2461 
2462     // register packet handlers with transport
2463     transport->register_packet_handler(&packet_handler);
2464 
2465     hci_stack->state = HCI_STATE_OFF;
2466 
2467     // class of device
2468     hci_stack->class_of_device = 0x007a020c; // Smartphone
2469 
2470     // bondable by default
2471     hci_stack->bondable = 1;
2472 
2473 #ifdef ENABLE_CLASSIC
2474     // classic name
2475     hci_stack->local_name = default_classic_name;
2476 
2477     // Master slave policy
2478     hci_stack->master_slave_policy = 1;
2479 #endif
2480 
2481     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
2482     hci_stack->ssp_enable = 1;
2483     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
2484     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
2485     hci_stack->ssp_auto_accept = 1;
2486 
2487     // voice setting - signed 16 bit pcm data with CVSD over the air
2488     hci_stack->sco_voice_setting = 0x60;
2489 
2490 #ifdef ENABLE_LE_CENTRAL
2491     // connection parameter to use for outgoing connections
2492     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
2493     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
2494     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
2495     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
2496     hci_stack->le_connection_latency      = 4;         // 4
2497     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
2498     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
2499     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
2500 #endif
2501 
2502     // connection parameter range used to answer connection parameter update requests in l2cap
2503     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
2504     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
2505     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
2506     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
2507     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
2508     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
2509 
2510     hci_state_reset();
2511 }
2512 
2513 /**
2514  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
2515  */
2516 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
2517     hci_stack->chipset = chipset_driver;
2518 
2519     // reset chipset driver - init is also called on power_up
2520     if (hci_stack->chipset && hci_stack->chipset->init){
2521         hci_stack->chipset->init(hci_stack->config);
2522     }
2523 }
2524 
2525 /**
2526  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
2527  */
2528 void hci_set_control(const btstack_control_t *hardware_control){
2529     // references to used control implementation
2530     hci_stack->control = hardware_control;
2531     // init with transport config
2532     hardware_control->init(hci_stack->config);
2533 }
2534 
2535 void hci_close(void){
2536     // close remote device db
2537     if (hci_stack->link_key_db) {
2538         hci_stack->link_key_db->close();
2539     }
2540 
2541     btstack_linked_list_iterator_t lit;
2542     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
2543     while (btstack_linked_list_iterator_has_next(&lit)){
2544         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
2545         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
2546         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
2547         hci_shutdown_connection(connection);
2548     }
2549 
2550     hci_power_control(HCI_POWER_OFF);
2551 
2552 #ifdef HAVE_MALLOC
2553     free(hci_stack);
2554 #endif
2555     hci_stack = NULL;
2556 }
2557 
2558 #ifdef ENABLE_CLASSIC
2559 void gap_set_class_of_device(uint32_t class_of_device){
2560     hci_stack->class_of_device = class_of_device;
2561 }
2562 
2563 void hci_disable_l2cap_timeout_check(void){
2564     disable_l2cap_timeouts = 1;
2565 }
2566 #endif
2567 
2568 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
2569 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
2570 void hci_set_bd_addr(bd_addr_t addr){
2571     memcpy(hci_stack->custom_bd_addr, addr, 6);
2572     hci_stack->custom_bd_addr_set = 1;
2573 }
2574 #endif
2575 
2576 // State-Module-Driver overview
2577 // state                    module  low-level
2578 // HCI_STATE_OFF             off      close
2579 // HCI_STATE_INITIALIZING,   on       open
2580 // HCI_STATE_WORKING,        on       open
2581 // HCI_STATE_HALTING,        on       open
2582 // HCI_STATE_SLEEPING,    off/sleep   close
2583 // HCI_STATE_FALLING_ASLEEP  on       open
2584 
2585 static int hci_power_control_on(void){
2586 
2587     // power on
2588     int err = 0;
2589     if (hci_stack->control && hci_stack->control->on){
2590         err = (*hci_stack->control->on)();
2591     }
2592     if (err){
2593         log_error( "POWER_ON failed");
2594         hci_emit_hci_open_failed();
2595         return err;
2596     }
2597 
2598     // int chipset driver
2599     if (hci_stack->chipset && hci_stack->chipset->init){
2600         hci_stack->chipset->init(hci_stack->config);
2601     }
2602 
2603     // init transport
2604     if (hci_stack->hci_transport->init){
2605         hci_stack->hci_transport->init(hci_stack->config);
2606     }
2607 
2608     // open transport
2609     err = hci_stack->hci_transport->open();
2610     if (err){
2611         log_error( "HCI_INIT failed, turning Bluetooth off again");
2612         if (hci_stack->control && hci_stack->control->off){
2613             (*hci_stack->control->off)();
2614         }
2615         hci_emit_hci_open_failed();
2616         return err;
2617     }
2618     return 0;
2619 }
2620 
2621 static void hci_power_control_off(void){
2622 
2623     log_info("hci_power_control_off");
2624 
2625     // close low-level device
2626     hci_stack->hci_transport->close();
2627 
2628     log_info("hci_power_control_off - hci_transport closed");
2629 
2630     // power off
2631     if (hci_stack->control && hci_stack->control->off){
2632         (*hci_stack->control->off)();
2633     }
2634 
2635     log_info("hci_power_control_off - control closed");
2636 
2637     hci_stack->state = HCI_STATE_OFF;
2638 }
2639 
2640 static void hci_power_control_sleep(void){
2641 
2642     log_info("hci_power_control_sleep");
2643 
2644 #if 0
2645     // don't close serial port during sleep
2646 
2647     // close low-level device
2648     hci_stack->hci_transport->close(hci_stack->config);
2649 #endif
2650 
2651     // sleep mode
2652     if (hci_stack->control && hci_stack->control->sleep){
2653         (*hci_stack->control->sleep)();
2654     }
2655 
2656     hci_stack->state = HCI_STATE_SLEEPING;
2657 }
2658 
2659 static int hci_power_control_wake(void){
2660 
2661     log_info("hci_power_control_wake");
2662 
2663     // wake on
2664     if (hci_stack->control && hci_stack->control->wake){
2665         (*hci_stack->control->wake)();
2666     }
2667 
2668 #if 0
2669     // open low-level device
2670     int err = hci_stack->hci_transport->open(hci_stack->config);
2671     if (err){
2672         log_error( "HCI_INIT failed, turning Bluetooth off again");
2673         if (hci_stack->control && hci_stack->control->off){
2674             (*hci_stack->control->off)();
2675         }
2676         hci_emit_hci_open_failed();
2677         return err;
2678     }
2679 #endif
2680 
2681     return 0;
2682 }
2683 
2684 static void hci_power_transition_to_initializing(void){
2685     // set up state machine
2686     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
2687     hci_stack->hci_packet_buffer_reserved = 0;
2688     hci_stack->state = HCI_STATE_INITIALIZING;
2689     hci_stack->substate = HCI_INIT_SEND_RESET;
2690 }
2691 
2692 int hci_power_control(HCI_POWER_MODE power_mode){
2693 
2694     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
2695 
2696     int err = 0;
2697     switch (hci_stack->state){
2698 
2699         case HCI_STATE_OFF:
2700             switch (power_mode){
2701                 case HCI_POWER_ON:
2702                     err = hci_power_control_on();
2703                     if (err) {
2704                         log_error("hci_power_control_on() error %d", err);
2705                         return err;
2706                     }
2707                     hci_power_transition_to_initializing();
2708                     break;
2709                 case HCI_POWER_OFF:
2710                     // do nothing
2711                     break;
2712                 case HCI_POWER_SLEEP:
2713                     // do nothing (with SLEEP == OFF)
2714                     break;
2715             }
2716             break;
2717 
2718         case HCI_STATE_INITIALIZING:
2719             switch (power_mode){
2720                 case HCI_POWER_ON:
2721                     // do nothing
2722                     break;
2723                 case HCI_POWER_OFF:
2724                     // no connections yet, just turn it off
2725                     hci_power_control_off();
2726                     break;
2727                 case HCI_POWER_SLEEP:
2728                     // no connections yet, just turn it off
2729                     hci_power_control_sleep();
2730                     break;
2731             }
2732             break;
2733 
2734         case HCI_STATE_WORKING:
2735             switch (power_mode){
2736                 case HCI_POWER_ON:
2737                     // do nothing
2738                     break;
2739                 case HCI_POWER_OFF:
2740                     // see hci_run
2741                     hci_stack->state = HCI_STATE_HALTING;
2742                     break;
2743                 case HCI_POWER_SLEEP:
2744                     // see hci_run
2745                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2746                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2747                     break;
2748             }
2749             break;
2750 
2751         case HCI_STATE_HALTING:
2752             switch (power_mode){
2753                 case HCI_POWER_ON:
2754                     hci_power_transition_to_initializing();
2755                     break;
2756                 case HCI_POWER_OFF:
2757                     // do nothing
2758                     break;
2759                 case HCI_POWER_SLEEP:
2760                     // see hci_run
2761                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2762                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2763                     break;
2764             }
2765             break;
2766 
2767         case HCI_STATE_FALLING_ASLEEP:
2768             switch (power_mode){
2769                 case HCI_POWER_ON:
2770 
2771 #ifdef HAVE_PLATFORM_IPHONE_OS
2772                     // nothing to do, if H4 supports power management
2773                     if (btstack_control_iphone_power_management_enabled()){
2774                         hci_stack->state = HCI_STATE_INITIALIZING;
2775                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
2776                         break;
2777                     }
2778 #endif
2779                     hci_power_transition_to_initializing();
2780                     break;
2781                 case HCI_POWER_OFF:
2782                     // see hci_run
2783                     hci_stack->state = HCI_STATE_HALTING;
2784                     break;
2785                 case HCI_POWER_SLEEP:
2786                     // do nothing
2787                     break;
2788             }
2789             break;
2790 
2791         case HCI_STATE_SLEEPING:
2792             switch (power_mode){
2793                 case HCI_POWER_ON:
2794 
2795 #ifdef HAVE_PLATFORM_IPHONE_OS
2796                     // nothing to do, if H4 supports power management
2797                     if (btstack_control_iphone_power_management_enabled()){
2798                         hci_stack->state = HCI_STATE_INITIALIZING;
2799                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
2800                         hci_update_scan_enable();
2801                         break;
2802                     }
2803 #endif
2804                     err = hci_power_control_wake();
2805                     if (err) return err;
2806                     hci_power_transition_to_initializing();
2807                     break;
2808                 case HCI_POWER_OFF:
2809                     hci_stack->state = HCI_STATE_HALTING;
2810                     break;
2811                 case HCI_POWER_SLEEP:
2812                     // do nothing
2813                     break;
2814             }
2815             break;
2816     }
2817 
2818     // create internal event
2819 	hci_emit_state();
2820 
2821 	// trigger next/first action
2822 	hci_run();
2823 
2824     return 0;
2825 }
2826 
2827 
2828 #ifdef ENABLE_CLASSIC
2829 
2830 static void hci_update_scan_enable(void){
2831     // 2 = page scan, 1 = inq scan
2832     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
2833     hci_run();
2834 }
2835 
2836 void gap_discoverable_control(uint8_t enable){
2837     if (enable) enable = 1; // normalize argument
2838 
2839     if (hci_stack->discoverable == enable){
2840         hci_emit_discoverable_enabled(hci_stack->discoverable);
2841         return;
2842     }
2843 
2844     hci_stack->discoverable = enable;
2845     hci_update_scan_enable();
2846 }
2847 
2848 void gap_connectable_control(uint8_t enable){
2849     if (enable) enable = 1; // normalize argument
2850 
2851     // don't emit event
2852     if (hci_stack->connectable == enable) return;
2853 
2854     hci_stack->connectable = enable;
2855     hci_update_scan_enable();
2856 }
2857 #endif
2858 
2859 void gap_local_bd_addr(bd_addr_t address_buffer){
2860     memcpy(address_buffer, hci_stack->local_bd_addr, 6);
2861 }
2862 
2863 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2864 static void hci_host_num_completed_packets(void){
2865 
2866     // create packet manually as arrays are not supported and num_commands should not get reduced
2867     hci_reserve_packet_buffer();
2868     uint8_t * packet = hci_get_outgoing_packet_buffer();
2869 
2870     uint16_t size = 0;
2871     uint16_t num_handles = 0;
2872     packet[size++] = 0x35;
2873     packet[size++] = 0x0c;
2874     size++;  // skip param len
2875     size++;  // skip num handles
2876 
2877     // add { handle, packets } entries
2878     btstack_linked_item_t * it;
2879     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
2880         hci_connection_t * connection = (hci_connection_t *) it;
2881         if (connection->num_packets_completed){
2882             little_endian_store_16(packet, size, connection->con_handle);
2883             size += 2;
2884             little_endian_store_16(packet, size, connection->num_packets_completed);
2885             size += 2;
2886             //
2887             num_handles++;
2888             connection->num_packets_completed = 0;
2889         }
2890     }
2891 
2892     packet[2] = size - 3;
2893     packet[3] = num_handles;
2894 
2895     hci_stack->host_completed_packets = 0;
2896 
2897     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
2898     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
2899 
2900     // release packet buffer for synchronous transport implementations
2901     if (hci_transport_synchronous()){
2902         hci_stack->hci_packet_buffer_reserved = 0;
2903     }
2904 }
2905 #endif
2906 
2907 static void hci_run(void){
2908 
2909     // log_info("hci_run: entered");
2910     btstack_linked_item_t * it;
2911 
2912     // send continuation fragments first, as they block the prepared packet buffer
2913     if (hci_stack->acl_fragmentation_total_size > 0) {
2914         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
2915         hci_connection_t *connection = hci_connection_for_handle(con_handle);
2916         if (connection) {
2917             if (hci_can_send_prepared_acl_packet_now(con_handle)){
2918                 hci_send_acl_packet_fragments(connection);
2919                 return;
2920             }
2921         } else {
2922             // connection gone -> discard further fragments
2923             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
2924             hci_stack->acl_fragmentation_total_size = 0;
2925             hci_stack->acl_fragmentation_pos = 0;
2926         }
2927     }
2928 
2929 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2930     // send host num completed packets next as they don't require num_cmd_packets > 0
2931     if (!hci_can_send_comand_packet_transport()) return;
2932     if (hci_stack->host_completed_packets){
2933         hci_host_num_completed_packets();
2934         return;
2935     }
2936 #endif
2937 
2938     if (!hci_can_send_command_packet_now()) return;
2939 
2940     // global/non-connection oriented commands
2941 
2942 #ifdef ENABLE_CLASSIC
2943     // decline incoming connections
2944     if (hci_stack->decline_reason){
2945         uint8_t reason = hci_stack->decline_reason;
2946         hci_stack->decline_reason = 0;
2947         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
2948         return;
2949     }
2950     // send scan enable
2951     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
2952         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
2953         hci_stack->new_scan_enable_value = 0xff;
2954         return;
2955     }
2956     // start/stop inquiry
2957     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN && hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX){
2958         uint8_t duration = hci_stack->inquiry_state;
2959         hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
2960         hci_send_cmd(&hci_inquiry, HCI_INQUIRY_LAP, duration, 0);
2961         return;
2962     }
2963     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
2964         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
2965         hci_send_cmd(&hci_inquiry_cancel);
2966         return;
2967     }
2968     // remote name request
2969     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
2970         hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
2971         hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
2972             hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
2973         return;
2974     }
2975     // pairing
2976     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
2977         uint8_t state = hci_stack->gap_pairing_state;
2978         hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
2979         switch (state){
2980             case GAP_PAIRING_STATE_SEND_PIN:
2981                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, strlen(hci_stack->gap_pairing_pin), hci_stack->gap_pairing_pin);
2982                 break;
2983             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
2984                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
2985                 break;
2986             case GAP_PAIRING_STATE_SEND_PASSKEY:
2987                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_passkey);
2988                 break;
2989             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
2990                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
2991                 break;
2992             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
2993                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
2994                 break;
2995             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
2996                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
2997                 break;
2998             default:
2999                 break;
3000         }
3001         return;
3002     }
3003 #endif
3004 
3005 #ifdef ENABLE_BLE
3006     // advertisements, active scanning, and creating connections requires randaom address to be set if using private address
3007     if ((hci_stack->state == HCI_STATE_WORKING)
3008     && (hci_stack->le_own_addr_type == BD_ADDR_TYPE_LE_PUBLIC || hci_stack->le_random_address_set)){
3009 
3010 #ifdef ENABLE_LE_CENTRAL
3011         // handle le scan
3012         switch(hci_stack->le_scanning_state){
3013             case LE_START_SCAN:
3014                 hci_stack->le_scanning_state = LE_SCANNING;
3015                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
3016                 return;
3017 
3018             case LE_STOP_SCAN:
3019                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
3020                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
3021                 return;
3022             default:
3023                 break;
3024         }
3025         if (hci_stack->le_scan_type != 0xff){
3026             // defaults: active scanning, accept all advertisement packets
3027             int scan_type = hci_stack->le_scan_type;
3028             hci_stack->le_scan_type = 0xff;
3029             hci_send_cmd(&hci_le_set_scan_parameters, scan_type, hci_stack->le_scan_interval, hci_stack->le_scan_window, hci_stack->le_own_addr_type, 0);
3030             return;
3031         }
3032 #endif
3033 #ifdef ENABLE_LE_PERIPHERAL
3034         // le advertisement control
3035         if (hci_stack->le_advertisements_todo){
3036             log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo );
3037         }
3038         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){
3039             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE;
3040             hci_send_cmd(&hci_le_set_advertise_enable, 0);
3041             return;
3042         }
3043         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
3044             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3045             hci_send_cmd(&hci_le_set_advertising_parameters,
3046                  hci_stack->le_advertisements_interval_min,
3047                  hci_stack->le_advertisements_interval_max,
3048                  hci_stack->le_advertisements_type,
3049                  hci_stack->le_own_addr_type,
3050                  hci_stack->le_advertisements_direct_address_type,
3051                  hci_stack->le_advertisements_direct_address,
3052                  hci_stack->le_advertisements_channel_map,
3053                  hci_stack->le_advertisements_filter_policy);
3054             return;
3055         }
3056         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
3057             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3058             uint8_t adv_data_clean[31];
3059             memset(adv_data_clean, 0, sizeof(adv_data_clean));
3060             memcpy(adv_data_clean, hci_stack->le_advertisements_data, hci_stack->le_advertisements_data_len);
3061             hci_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len);
3062             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
3063             return;
3064         }
3065         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
3066             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
3067             uint8_t scan_data_clean[31];
3068             memset(scan_data_clean, 0, sizeof(scan_data_clean));
3069             memcpy(scan_data_clean, hci_stack->le_scan_response_data, hci_stack->le_scan_response_data_len);
3070             hci_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len);
3071             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, hci_stack->le_scan_response_data);
3072             return;
3073         }
3074         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){
3075             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE;
3076             hci_send_cmd(&hci_le_set_advertise_enable, 1);
3077             return;
3078         }
3079 #endif
3080 
3081 #ifdef ENABLE_LE_CENTRAL
3082         //
3083         // LE Whitelist Management
3084         //
3085 
3086         // check if whitelist needs modification
3087         btstack_linked_list_iterator_t lit;
3088         int modification_pending = 0;
3089         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3090         while (btstack_linked_list_iterator_has_next(&lit)){
3091             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3092             if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
3093                 modification_pending = 1;
3094                 break;
3095             }
3096         }
3097 
3098         if (modification_pending){
3099             // stop connnecting if modification pending
3100             if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){
3101                 hci_send_cmd(&hci_le_create_connection_cancel);
3102                 return;
3103             }
3104 
3105             // add/remove entries
3106             btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3107             while (btstack_linked_list_iterator_has_next(&lit)){
3108                 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3109                 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
3110                     entry->state = LE_WHITELIST_ON_CONTROLLER;
3111                     hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
3112                     return;
3113 
3114                 }
3115                 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
3116                     bd_addr_t address;
3117                     bd_addr_type_t address_type = entry->address_type;
3118                     memcpy(address, entry->address, 6);
3119                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3120                     btstack_memory_whitelist_entry_free(entry);
3121                     hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
3122                     return;
3123                 }
3124             }
3125         }
3126 
3127         // start connecting
3128         if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE &&
3129             !btstack_linked_list_empty(&hci_stack->le_whitelist)){
3130             bd_addr_t null_addr;
3131             memset(null_addr, 0, 6);
3132             hci_send_cmd(&hci_le_create_connection,
3133                 hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
3134                 hci_stack->le_connection_scan_window,    // scan interval: 30 ms
3135                  1,         // use whitelist
3136                  0,         // peer address type
3137                  null_addr, // peer bd addr
3138                  hci_stack->le_own_addr_type, // our addr type:
3139                  hci_stack->le_connection_interval_min,    // conn interval min
3140                  hci_stack->le_connection_interval_max,    // conn interval max
3141                  hci_stack->le_connection_latency,         // conn latency
3142                  hci_stack->le_supervision_timeout,        // conn latency
3143                  hci_stack->le_minimum_ce_length,          // min ce length
3144                  hci_stack->le_maximum_ce_length           // max ce length
3145                 );
3146             return;
3147         }
3148 #endif
3149     }
3150 #endif
3151 
3152     // send pending HCI commands
3153     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3154         hci_connection_t * connection = (hci_connection_t *) it;
3155 
3156         switch(connection->state){
3157             case SEND_CREATE_CONNECTION:
3158                 switch(connection->address_type){
3159 #ifdef ENABLE_CLASSIC
3160                     case BD_ADDR_TYPE_CLASSIC:
3161                         log_info("sending hci_create_connection");
3162                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
3163                         break;
3164 #endif
3165                     default:
3166 #ifdef ENABLE_BLE
3167 #ifdef ENABLE_LE_CENTRAL
3168                         log_info("sending hci_le_create_connection");
3169                         hci_send_cmd(&hci_le_create_connection,
3170                              hci_stack->le_connection_scan_interval,    // conn scan interval
3171                              hci_stack->le_connection_scan_window,      // conn scan windows
3172                              0,         // don't use whitelist
3173                              connection->address_type, // peer address type
3174                              connection->address,      // peer bd addr
3175                              hci_stack->le_own_addr_type, // our addr type:
3176                              hci_stack->le_connection_interval_min,    // conn interval min
3177                              hci_stack->le_connection_interval_max,    // conn interval max
3178                              hci_stack->le_connection_latency,         // conn latency
3179                              hci_stack->le_supervision_timeout,        // conn latency
3180                              hci_stack->le_minimum_ce_length,          // min ce length
3181                              hci_stack->le_maximum_ce_length          // max ce length
3182                              );
3183                         connection->state = SENT_CREATE_CONNECTION;
3184 #endif
3185 #endif
3186                         break;
3187                 }
3188                 return;
3189 
3190 #ifdef ENABLE_CLASSIC
3191             case RECEIVED_CONNECTION_REQUEST:
3192                 log_info("sending hci_accept_connection_request, remote eSCO %u", connection->remote_supported_feature_eSCO);
3193                 connection->state = ACCEPTED_CONNECTION_REQUEST;
3194                 connection->role  = HCI_ROLE_SLAVE;
3195                 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
3196                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
3197                 }
3198                 return;
3199 #endif
3200 
3201 #ifdef ENABLE_BLE
3202 #ifdef ENABLE_LE_CENTRAL
3203             case SEND_CANCEL_CONNECTION:
3204                 connection->state = SENT_CANCEL_CONNECTION;
3205                 hci_send_cmd(&hci_le_create_connection_cancel);
3206                 return;
3207 #endif
3208 #endif
3209             case SEND_DISCONNECT:
3210                 connection->state = SENT_DISCONNECT;
3211                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
3212                 return;
3213 
3214             default:
3215                 break;
3216         }
3217 
3218 #ifdef ENABLE_CLASSIC
3219         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
3220             log_info("responding to link key request");
3221             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
3222             link_key_t link_key;
3223             link_key_type_t link_key_type;
3224             if ( hci_stack->link_key_db
3225               && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type)
3226               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
3227                connection->link_key_type = link_key_type;
3228                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
3229             } else {
3230                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
3231             }
3232             return;
3233         }
3234 
3235         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
3236             log_info("denying to pin request");
3237             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
3238             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
3239             return;
3240         }
3241 
3242         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
3243             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
3244             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
3245             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
3246                 // tweak authentication requirements
3247                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
3248                 if (connection->bonding_flags & BONDING_DEDICATED){
3249                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
3250                 }
3251                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
3252                     authreq |= 1;
3253                 }
3254                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
3255             } else {
3256                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
3257             }
3258             return;
3259         }
3260 
3261         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
3262             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
3263             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
3264             return;
3265         }
3266 
3267         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
3268             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
3269             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
3270             return;
3271         }
3272 
3273         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
3274             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
3275             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
3276             return;
3277         }
3278 
3279         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
3280             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
3281             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
3282             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
3283             return;
3284         }
3285 
3286         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
3287             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
3288             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
3289             return;
3290         }
3291 
3292         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
3293             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
3294             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
3295             return;
3296         }
3297 #endif
3298 
3299         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
3300             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
3301             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
3302             return;
3303         }
3304 
3305 #ifdef ENABLE_BLE
3306         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
3307             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3308 
3309             uint16_t connection_interval_min = connection->le_conn_interval_min;
3310             connection->le_conn_interval_min = 0;
3311             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
3312                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
3313                 0x0000, 0xffff);
3314         }
3315 #endif
3316     }
3317 
3318     hci_connection_t * connection;
3319     switch (hci_stack->state){
3320         case HCI_STATE_INITIALIZING:
3321             hci_initializing_run();
3322             break;
3323 
3324         case HCI_STATE_HALTING:
3325 
3326             log_info("HCI_STATE_HALTING");
3327 
3328             // free whitelist entries
3329 #ifdef ENABLE_BLE
3330 #ifdef ENABLE_LE_CENTRAL
3331             {
3332                 btstack_linked_list_iterator_t lit;
3333                 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3334                 while (btstack_linked_list_iterator_has_next(&lit)){
3335                     whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3336                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3337                     btstack_memory_whitelist_entry_free(entry);
3338                 }
3339             }
3340 #endif
3341 #endif
3342             // close all open connections
3343             connection =  (hci_connection_t *) hci_stack->connections;
3344             if (connection){
3345                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
3346                 if (!hci_can_send_command_packet_now()) return;
3347 
3348                 // check state
3349                 if (connection->state == SENT_DISCONNECT) return;
3350                 connection->state = SENT_DISCONNECT;
3351 
3352                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
3353 
3354                 // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
3355                 hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
3356 
3357                 // ... which would be ignored anyway as we shutdown (free) the connection now
3358                 hci_shutdown_connection(connection);
3359 
3360                 // finally, send the disconnect command
3361                 hci_send_cmd(&hci_disconnect, con_handle, 0x13);  // remote closed connection
3362                 return;
3363             }
3364             log_info("HCI_STATE_HALTING, calling off");
3365 
3366             // switch mode
3367             hci_power_control_off();
3368 
3369             log_info("HCI_STATE_HALTING, emitting state");
3370             hci_emit_state();
3371             log_info("HCI_STATE_HALTING, done");
3372             break;
3373 
3374         case HCI_STATE_FALLING_ASLEEP:
3375             switch(hci_stack->substate) {
3376                 case HCI_FALLING_ASLEEP_DISCONNECT:
3377                     log_info("HCI_STATE_FALLING_ASLEEP");
3378                     // close all open connections
3379                     connection =  (hci_connection_t *) hci_stack->connections;
3380 
3381 #ifdef HAVE_PLATFORM_IPHONE_OS
3382                     // don't close connections, if H4 supports power management
3383                     if (btstack_control_iphone_power_management_enabled()){
3384                         connection = NULL;
3385                     }
3386 #endif
3387                     if (connection){
3388 
3389                         // send disconnect
3390                         if (!hci_can_send_command_packet_now()) return;
3391 
3392                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
3393                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
3394 
3395                         // send disconnected event right away - causes higher layer connections to get closed, too.
3396                         hci_shutdown_connection(connection);
3397                         return;
3398                     }
3399 
3400                     if (hci_classic_supported()){
3401                         // disable page and inquiry scan
3402                         if (!hci_can_send_command_packet_now()) return;
3403 
3404                         log_info("HCI_STATE_HALTING, disabling inq scans");
3405                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
3406 
3407                         // continue in next sub state
3408                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
3409                         break;
3410                     }
3411                     // no break - fall through for ble-only chips
3412 
3413                 case HCI_FALLING_ASLEEP_COMPLETE:
3414                     log_info("HCI_STATE_HALTING, calling sleep");
3415 #ifdef HAVE_PLATFORM_IPHONE_OS
3416                     // don't actually go to sleep, if H4 supports power management
3417                     if (btstack_control_iphone_power_management_enabled()){
3418                         // SLEEP MODE reached
3419                         hci_stack->state = HCI_STATE_SLEEPING;
3420                         hci_emit_state();
3421                         break;
3422                     }
3423 #endif
3424                     // switch mode
3425                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
3426                     hci_emit_state();
3427                     break;
3428 
3429                 default:
3430                     break;
3431             }
3432             break;
3433 
3434         default:
3435             break;
3436     }
3437 }
3438 
3439 int hci_send_cmd_packet(uint8_t *packet, int size){
3440     // house-keeping
3441 
3442     if (IS_COMMAND(packet, hci_write_loopback_mode)){
3443         hci_stack->loopback_mode = packet[3];
3444     }
3445 
3446 #ifdef ENABLE_CLASSIC
3447     bd_addr_t addr;
3448     hci_connection_t * conn;
3449 
3450     // create_connection?
3451     if (IS_COMMAND(packet, hci_create_connection)){
3452         reverse_bd_addr(&packet[3], addr);
3453         log_info("Create_connection to %s", bd_addr_to_str(addr));
3454 
3455         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3456         if (!conn){
3457             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3458             if (!conn){
3459                 // notify client that alloc failed
3460                 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3461                 return 0; // don't sent packet to controller
3462             }
3463             conn->state = SEND_CREATE_CONNECTION;
3464         }
3465         log_info("conn state %u", conn->state);
3466         switch (conn->state){
3467             // if connection active exists
3468             case OPEN:
3469                 // and OPEN, emit connection complete command, don't send to controller
3470                 hci_emit_connection_complete(addr, conn->con_handle, 0);
3471                 return 0;
3472             case SEND_CREATE_CONNECTION:
3473                 // connection created by hci, e.g. dedicated bonding
3474                 break;
3475             default:
3476                 // otherwise, just ignore as it is already in the open process
3477                 return 0;
3478         }
3479         conn->state = SENT_CREATE_CONNECTION;
3480     }
3481 
3482     if (IS_COMMAND(packet, hci_link_key_request_reply)){
3483         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
3484     }
3485     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
3486         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
3487     }
3488 
3489     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
3490         if (hci_stack->link_key_db){
3491             reverse_bd_addr(&packet[3], addr);
3492             hci_stack->link_key_db->delete_link_key(addr);
3493         }
3494     }
3495 
3496     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
3497     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
3498         reverse_bd_addr(&packet[3], addr);
3499         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3500         if (conn){
3501             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
3502         }
3503     }
3504 
3505     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
3506     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
3507     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
3508     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
3509         reverse_bd_addr(&packet[3], addr);
3510         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3511         if (conn){
3512             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
3513         }
3514     }
3515 
3516 #ifdef ENABLE_SCO_OVER_HCI
3517     // setup_synchronous_connection? Voice setting at offset 22
3518     if (IS_COMMAND(packet, hci_setup_synchronous_connection)){
3519         // TODO: compare to current setting if sco connection already active
3520         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
3521     }
3522     // accept_synchronus_connection? Voice setting at offset 18
3523     if (IS_COMMAND(packet, hci_accept_synchronous_connection)){
3524         // TODO: compare to current setting if sco connection already active
3525         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
3526     }
3527 #endif
3528 #endif
3529 
3530 #ifdef ENABLE_BLE
3531 #ifdef ENABLE_LE_PERIPHERAL
3532     if (IS_COMMAND(packet, hci_le_set_random_address)){
3533         hci_stack->le_random_address_set = 1;
3534         reverse_bd_addr(&packet[3], hci_stack->le_random_address);
3535     }
3536     if (IS_COMMAND(packet, hci_le_set_advertise_enable)){
3537         hci_stack->le_advertisements_active = packet[3];
3538     }
3539 #endif
3540 #ifdef ENABLE_LE_CENTRAL
3541     if (IS_COMMAND(packet, hci_le_create_connection)){
3542         // white list used?
3543         uint8_t initiator_filter_policy = packet[7];
3544         switch (initiator_filter_policy){
3545             case 0:
3546                 // whitelist not used
3547                 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
3548                 break;
3549             case 1:
3550                 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
3551                 break;
3552             default:
3553                 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
3554                 break;
3555         }
3556     }
3557     if (IS_COMMAND(packet, hci_le_create_connection_cancel)){
3558         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3559     }
3560 #endif
3561 #endif
3562 
3563     hci_stack->num_cmd_packets--;
3564 
3565     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3566     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3567 
3568     // release packet buffer for synchronous transport implementations
3569     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
3570         hci_stack->hci_packet_buffer_reserved = 0;
3571     }
3572 
3573     return err;
3574 }
3575 
3576 // disconnect because of security block
3577 void hci_disconnect_security_block(hci_con_handle_t con_handle){
3578     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3579     if (!connection) return;
3580     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3581 }
3582 
3583 
3584 // Configure Secure Simple Pairing
3585 
3586 #ifdef ENABLE_CLASSIC
3587 
3588 // enable will enable SSP during init
3589 void gap_ssp_set_enable(int enable){
3590     hci_stack->ssp_enable = enable;
3591 }
3592 
3593 static int hci_local_ssp_activated(void){
3594     return gap_ssp_supported() && hci_stack->ssp_enable;
3595 }
3596 
3597 // if set, BTstack will respond to io capability request using authentication requirement
3598 void gap_ssp_set_io_capability(int io_capability){
3599     hci_stack->ssp_io_capability = io_capability;
3600 }
3601 void gap_ssp_set_authentication_requirement(int authentication_requirement){
3602     hci_stack->ssp_authentication_requirement = authentication_requirement;
3603 }
3604 
3605 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
3606 void gap_ssp_set_auto_accept(int auto_accept){
3607     hci_stack->ssp_auto_accept = auto_accept;
3608 }
3609 #endif
3610 
3611 // va_list part of hci_send_cmd
3612 int hci_send_cmd_va_arg(const hci_cmd_t *cmd, va_list argptr){
3613     if (!hci_can_send_command_packet_now()){
3614         log_error("hci_send_cmd called but cannot send packet now");
3615         return 0;
3616     }
3617 
3618     // for HCI INITIALIZATION
3619     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
3620     hci_stack->last_cmd_opcode = cmd->opcode;
3621 
3622     hci_reserve_packet_buffer();
3623     uint8_t * packet = hci_stack->hci_packet_buffer;
3624     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
3625     return hci_send_cmd_packet(packet, size);
3626 }
3627 
3628 /**
3629  * pre: numcmds >= 0 - it's allowed to send a command to the controller
3630  */
3631 int hci_send_cmd(const hci_cmd_t *cmd, ...){
3632     va_list argptr;
3633     va_start(argptr, cmd);
3634     int res = hci_send_cmd_va_arg(cmd, argptr);
3635     va_end(argptr);
3636     return res;
3637 }
3638 
3639 // Create various non-HCI events.
3640 // TODO: generalize, use table similar to hci_create_command
3641 
3642 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
3643     // dump packet
3644     if (dump) {
3645         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
3646     }
3647 
3648     // dispatch to all event handlers
3649     btstack_linked_list_iterator_t it;
3650     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
3651     while (btstack_linked_list_iterator_has_next(&it)){
3652         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
3653         entry->callback(HCI_EVENT_PACKET, 0, event, size);
3654     }
3655 }
3656 
3657 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
3658     if (!hci_stack->acl_packet_handler) return;
3659     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
3660 }
3661 
3662 #ifdef ENABLE_CLASSIC
3663 static void hci_notify_if_sco_can_send_now(void){
3664     // notify SCO sender if waiting
3665     if (!hci_stack->sco_waiting_for_can_send_now) return;
3666     if (hci_can_send_sco_packet_now()){
3667         hci_stack->sco_waiting_for_can_send_now = 0;
3668         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
3669         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
3670         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
3671     }
3672 }
3673 
3674 // parsing end emitting has been merged to reduce code size
3675 static void gap_inquiry_explode(uint8_t * packet){
3676     uint8_t event[15+GAP_INQUIRY_MAX_NAME_LEN];
3677 
3678     uint8_t * eir_data;
3679     ad_context_t context;
3680     const uint8_t * name;
3681     uint8_t         name_len;
3682 
3683     int event_type = hci_event_packet_get_type(packet);
3684     int num_reserved_fields = event_type == HCI_EVENT_INQUIRY_RESULT ? 2 : 1;    // 2 for old event, 1 otherwise
3685     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
3686 
3687     // event[1] is set at the end
3688     int i;
3689     for (i=0; i<num_responses;i++){
3690         memset(event, 0, sizeof(event));
3691         event[0] = GAP_EVENT_INQUIRY_RESULT;
3692         uint8_t event_size = 18;    // if name is not set by EIR
3693 
3694         memcpy(&event[2],  &packet[3 +                                             i*6], 6); // bd_addr
3695         event[8] =          packet[3 + num_responses*(6)                         + i*1];     // page_scan_repetition_mode
3696         memcpy(&event[9],  &packet[3 + num_responses*(6+1+num_reserved_fields)   + i*3], 3); // class of device
3697         memcpy(&event[12], &packet[3 + num_responses*(6+1+num_reserved_fields+3) + i*2], 2); // clock offset
3698 
3699         switch (event_type){
3700             case HCI_EVENT_INQUIRY_RESULT:
3701                 // 14,15,16,17 = 0, size 18
3702                 break;
3703             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
3704                 event[14] = 1;
3705                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
3706                 // 16,17 = 0, size 18
3707                 break;
3708             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
3709                 event[14] = 1;
3710                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
3711                 // for EIR packets, there is only one reponse in it
3712                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
3713                 name = NULL;
3714                 // EIR data is 240 bytes in EIR event
3715                 for (ad_iterator_init(&context, 240, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
3716                     uint8_t data_type    = ad_iterator_get_data_type(&context);
3717                     uint8_t data_size    = ad_iterator_get_data_len(&context);
3718                     const uint8_t * data = ad_iterator_get_data(&context);
3719                     // Prefer Complete Local Name over Shortend Local Name
3720                     switch (data_type){
3721                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
3722                             if (name) continue;
3723                             /* explicit fall-through */
3724                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
3725                             name = data;
3726                             name_len = data_size;
3727                             break;
3728                         default:
3729                             break;
3730                     }
3731                 }
3732                 if (name){
3733                     event[16] = 1;
3734                     // truncate name if needed
3735                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
3736                     event[17] = len;
3737                     memcpy(&event[18], name, len);
3738                     event_size += len;
3739                 }
3740                 break;
3741         }
3742         event[1] = event_size - 2;
3743         hci_emit_event(event, event_size, 1);
3744     }
3745 }
3746 #endif
3747 
3748 void hci_emit_state(void){
3749     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
3750     uint8_t event[3];
3751     event[0] = BTSTACK_EVENT_STATE;
3752     event[1] = sizeof(event) - 2;
3753     event[2] = hci_stack->state;
3754     hci_emit_event(event, sizeof(event), 1);
3755 }
3756 
3757 #ifdef ENABLE_CLASSIC
3758 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3759     uint8_t event[13];
3760     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
3761     event[1] = sizeof(event) - 2;
3762     event[2] = status;
3763     little_endian_store_16(event, 3, con_handle);
3764     reverse_bd_addr(address, &event[5]);
3765     event[11] = 1; // ACL connection
3766     event[12] = 0; // encryption disabled
3767     hci_emit_event(event, sizeof(event), 1);
3768 }
3769 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
3770     if (disable_l2cap_timeouts) return;
3771     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
3772     uint8_t event[4];
3773     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
3774     event[1] = sizeof(event) - 2;
3775     little_endian_store_16(event, 2, conn->con_handle);
3776     hci_emit_event(event, sizeof(event), 1);
3777 }
3778 #endif
3779 
3780 #ifdef ENABLE_BLE
3781 #ifdef ENABLE_LE_CENTRAL
3782 static void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3783     uint8_t event[21];
3784     event[0] = HCI_EVENT_LE_META;
3785     event[1] = sizeof(event) - 2;
3786     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
3787     event[3] = status;
3788     little_endian_store_16(event, 4, con_handle);
3789     event[6] = 0; // TODO: role
3790     event[7] = address_type;
3791     reverse_bd_addr(address, &event[8]);
3792     little_endian_store_16(event, 14, 0); // interval
3793     little_endian_store_16(event, 16, 0); // latency
3794     little_endian_store_16(event, 18, 0); // supervision timeout
3795     event[20] = 0; // master clock accuracy
3796     hci_emit_event(event, sizeof(event), 1);
3797 }
3798 #endif
3799 #endif
3800 
3801 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
3802     uint8_t event[6];
3803     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
3804     event[1] = sizeof(event) - 2;
3805     event[2] = 0; // status = OK
3806     little_endian_store_16(event, 3, con_handle);
3807     event[5] = reason;
3808     hci_emit_event(event, sizeof(event), 1);
3809 }
3810 
3811 static void hci_emit_nr_connections_changed(void){
3812     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
3813     uint8_t event[3];
3814     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
3815     event[1] = sizeof(event) - 2;
3816     event[2] = nr_hci_connections();
3817     hci_emit_event(event, sizeof(event), 1);
3818 }
3819 
3820 static void hci_emit_hci_open_failed(void){
3821     log_info("BTSTACK_EVENT_POWERON_FAILED");
3822     uint8_t event[2];
3823     event[0] = BTSTACK_EVENT_POWERON_FAILED;
3824     event[1] = sizeof(event) - 2;
3825     hci_emit_event(event, sizeof(event), 1);
3826 }
3827 
3828 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
3829     log_info("hci_emit_dedicated_bonding_result %u ", status);
3830     uint8_t event[9];
3831     int pos = 0;
3832     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
3833     event[pos++] = sizeof(event) - 2;
3834     event[pos++] = status;
3835     reverse_bd_addr(address, &event[pos]);
3836     hci_emit_event(event, sizeof(event), 1);
3837 }
3838 
3839 
3840 #ifdef ENABLE_CLASSIC
3841 
3842 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
3843     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
3844     uint8_t event[5];
3845     int pos = 0;
3846     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
3847     event[pos++] = sizeof(event) - 2;
3848     little_endian_store_16(event, 2, con_handle);
3849     pos += 2;
3850     event[pos++] = level;
3851     hci_emit_event(event, sizeof(event), 1);
3852 }
3853 
3854 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
3855     if (!connection) return LEVEL_0;
3856     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
3857     return gap_security_level_for_link_key_type(connection->link_key_type);
3858 }
3859 
3860 static void hci_emit_discoverable_enabled(uint8_t enabled){
3861     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
3862     uint8_t event[3];
3863     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
3864     event[1] = sizeof(event) - 2;
3865     event[2] = enabled;
3866     hci_emit_event(event, sizeof(event), 1);
3867 }
3868 
3869 #ifdef ENABLE_CLASSIC
3870 // query if remote side supports eSCO
3871 int hci_remote_esco_supported(hci_con_handle_t con_handle){
3872     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3873     if (!connection) return 0;
3874     return connection->remote_supported_feature_eSCO;
3875 }
3876 
3877 // query if remote side supports SSP
3878 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
3879     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3880     if (!connection) return 0;
3881     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
3882 }
3883 
3884 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
3885     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
3886 }
3887 #endif
3888 
3889 // GAP API
3890 /**
3891  * @bbrief enable/disable bonding. default is enabled
3892  * @praram enabled
3893  */
3894 void gap_set_bondable_mode(int enable){
3895     hci_stack->bondable = enable ? 1 : 0;
3896 }
3897 /**
3898  * @brief Get bondable mode.
3899  * @return 1 if bondable
3900  */
3901 int gap_get_bondable_mode(void){
3902     return hci_stack->bondable;
3903 }
3904 
3905 /**
3906  * @brief map link keys to security levels
3907  */
3908 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
3909     switch (link_key_type){
3910         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
3911             return LEVEL_4;
3912         case COMBINATION_KEY:
3913         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
3914             return LEVEL_3;
3915         default:
3916             return LEVEL_2;
3917     }
3918 }
3919 
3920 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
3921     log_info("gap_mitm_protection_required_for_security_level %u", level);
3922     return level > LEVEL_2;
3923 }
3924 
3925 /**
3926  * @brief get current security level
3927  */
3928 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
3929     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3930     if (!connection) return LEVEL_0;
3931     return gap_security_level_for_connection(connection);
3932 }
3933 
3934 /**
3935  * @brief request connection to device to
3936  * @result GAP_AUTHENTICATION_RESULT
3937  */
3938 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
3939     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3940     if (!connection){
3941         hci_emit_security_level(con_handle, LEVEL_0);
3942         return;
3943     }
3944     gap_security_level_t current_level = gap_security_level(con_handle);
3945     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
3946     if (current_level >= requested_level){
3947         hci_emit_security_level(con_handle, current_level);
3948         return;
3949     }
3950 
3951     connection->requested_security_level = requested_level;
3952 
3953 #if 0
3954     // sending encryption request without a link key results in an error.
3955     // TODO: figure out how to use it properly
3956 
3957     // would enabling ecnryption suffice (>= LEVEL_2)?
3958     if (hci_stack->link_key_db){
3959         link_key_type_t link_key_type;
3960         link_key_t      link_key;
3961         if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){
3962             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
3963                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
3964                 return;
3965             }
3966         }
3967     }
3968 #endif
3969 
3970     // try to authenticate connection
3971     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
3972     hci_run();
3973 }
3974 
3975 /**
3976  * @brief start dedicated bonding with device. disconnect after bonding
3977  * @param device
3978  * @param request MITM protection
3979  * @result GAP_DEDICATED_BONDING_COMPLETE
3980  */
3981 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
3982 
3983     // create connection state machine
3984     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
3985 
3986     if (!connection){
3987         return BTSTACK_MEMORY_ALLOC_FAILED;
3988     }
3989 
3990     // delete linkn key
3991     gap_drop_link_key_for_bd_addr(device);
3992 
3993     // configure LEVEL_2/3, dedicated bonding
3994     connection->state = SEND_CREATE_CONNECTION;
3995     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
3996     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
3997     connection->bonding_flags = BONDING_DEDICATED;
3998 
3999     // wait for GAP Security Result and send GAP Dedicated Bonding complete
4000 
4001     // handle: connnection failure (connection complete != ok)
4002     // handle: authentication failure
4003     // handle: disconnect on done
4004 
4005     hci_run();
4006 
4007     return 0;
4008 }
4009 #endif
4010 
4011 void gap_set_local_name(const char * local_name){
4012     hci_stack->local_name = local_name;
4013 }
4014 
4015 
4016 #ifdef ENABLE_BLE
4017 
4018 #ifdef ENABLE_LE_CENTRAL
4019 void gap_start_scan(void){
4020     if (hci_stack->le_scanning_state == LE_SCANNING) return;
4021     hci_stack->le_scanning_state = LE_START_SCAN;
4022     hci_run();
4023 }
4024 
4025 void gap_stop_scan(void){
4026     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return;
4027     hci_stack->le_scanning_state = LE_STOP_SCAN;
4028     hci_run();
4029 }
4030 
4031 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
4032     hci_stack->le_scan_type     = scan_type;
4033     hci_stack->le_scan_interval = scan_interval;
4034     hci_stack->le_scan_window   = scan_window;
4035     hci_run();
4036 }
4037 
4038 uint8_t gap_connect(bd_addr_t addr, bd_addr_type_t addr_type){
4039     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
4040     if (!conn){
4041         log_info("gap_connect: no connection exists yet, creating context");
4042         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
4043         if (!conn){
4044             // notify client that alloc failed
4045             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
4046             log_info("gap_connect: failed to alloc hci_connection_t");
4047             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
4048         }
4049         conn->state = SEND_CREATE_CONNECTION;
4050         log_info("gap_connect: send create connection next");
4051         hci_run();
4052         return 0;
4053     }
4054 
4055     if (!hci_is_le_connection(conn) ||
4056         conn->state == SEND_CREATE_CONNECTION ||
4057         conn->state == SENT_CREATE_CONNECTION) {
4058         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
4059         log_error("gap_connect: classic connection or connect is already being created");
4060         return GATT_CLIENT_IN_WRONG_STATE;
4061     }
4062 
4063     log_info("gap_connect: context exists with state %u", conn->state);
4064     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0);
4065     hci_run();
4066     return 0;
4067 }
4068 
4069 // @assumption: only a single outgoing LE Connection exists
4070 static hci_connection_t * gap_get_outgoing_connection(void){
4071     btstack_linked_item_t *it;
4072     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
4073         hci_connection_t * conn = (hci_connection_t *) it;
4074         if (!hci_is_le_connection(conn)) continue;
4075         switch (conn->state){
4076             case SEND_CREATE_CONNECTION:
4077             case SENT_CREATE_CONNECTION:
4078             case SENT_CANCEL_CONNECTION:
4079                 return conn;
4080             default:
4081                 break;
4082         };
4083     }
4084     return NULL;
4085 }
4086 
4087 uint8_t gap_connect_cancel(void){
4088     hci_connection_t * conn = gap_get_outgoing_connection();
4089     if (!conn) return 0;
4090     switch (conn->state){
4091         case SEND_CREATE_CONNECTION:
4092             // skip sending create connection and emit event instead
4093             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
4094             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
4095             btstack_memory_hci_connection_free( conn );
4096             break;
4097         case SENT_CREATE_CONNECTION:
4098             // request to send cancel connection
4099             conn->state = SEND_CANCEL_CONNECTION;
4100             hci_run();
4101             break;
4102         default:
4103             break;
4104     }
4105     return 0;
4106 }
4107 #endif
4108 
4109 #ifdef ENABLE_LE_CENTRAL
4110 /**
4111  * @brief Set connection parameters for outgoing connections
4112  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
4113  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
4114  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
4115  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
4116  * @param conn_latency, default: 4
4117  * @param supervision_timeout (unit: 10ms), default: 720 ms
4118  * @param min_ce_length (unit: 0.625ms), default: 10 ms
4119  * @param max_ce_length (unit: 0.625ms), default: 30 ms
4120  */
4121 
4122 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
4123     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
4124     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
4125     hci_stack->le_connection_scan_interval = conn_scan_interval;
4126     hci_stack->le_connection_scan_window = conn_scan_window;
4127     hci_stack->le_connection_interval_min = conn_interval_min;
4128     hci_stack->le_connection_interval_max = conn_interval_max;
4129     hci_stack->le_connection_latency = conn_latency;
4130     hci_stack->le_supervision_timeout = supervision_timeout;
4131     hci_stack->le_minimum_ce_length = min_ce_length;
4132     hci_stack->le_maximum_ce_length = max_ce_length;
4133 }
4134 #endif
4135 
4136 /**
4137  * @brief Updates the connection parameters for a given LE connection
4138  * @param handle
4139  * @param conn_interval_min (unit: 1.25ms)
4140  * @param conn_interval_max (unit: 1.25ms)
4141  * @param conn_latency
4142  * @param supervision_timeout (unit: 10ms)
4143  * @returns 0 if ok
4144  */
4145 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4146     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4147     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4148     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4149     connection->le_conn_interval_min = conn_interval_min;
4150     connection->le_conn_interval_max = conn_interval_max;
4151     connection->le_conn_latency = conn_latency;
4152     connection->le_supervision_timeout = supervision_timeout;
4153     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
4154     hci_run();
4155     return 0;
4156 }
4157 
4158 /**
4159  * @brief Request an update of the connection parameter for a given LE connection
4160  * @param handle
4161  * @param conn_interval_min (unit: 1.25ms)
4162  * @param conn_interval_max (unit: 1.25ms)
4163  * @param conn_latency
4164  * @param supervision_timeout (unit: 10ms)
4165  * @returns 0 if ok
4166  */
4167 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4168     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4169     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4170     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4171     connection->le_conn_interval_min = conn_interval_min;
4172     connection->le_conn_interval_max = conn_interval_max;
4173     connection->le_conn_latency = conn_latency;
4174     connection->le_supervision_timeout = supervision_timeout;
4175     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
4176     hci_run();
4177     return 0;
4178 }
4179 
4180 #ifdef ENABLE_LE_PERIPHERAL
4181 
4182 static void gap_advertisments_changed(void){
4183     // disable advertisements before updating adv, scan data, or adv params
4184     if (hci_stack->le_advertisements_active){
4185         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
4186     }
4187     hci_run();
4188 }
4189 
4190 /**
4191  * @brief Set Advertisement Data
4192  * @param advertising_data_length
4193  * @param advertising_data (max 31 octets)
4194  * @note data is not copied, pointer has to stay valid
4195  */
4196 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
4197     hci_stack->le_advertisements_data_len = advertising_data_length;
4198     hci_stack->le_advertisements_data = advertising_data;
4199     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4200     gap_advertisments_changed();
4201 }
4202 
4203 /**
4204  * @brief Set Scan Response Data
4205  * @param advertising_data_length
4206  * @param advertising_data (max 31 octets)
4207  * @note data is not copied, pointer has to stay valid
4208  */
4209 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
4210     hci_stack->le_scan_response_data_len = scan_response_data_length;
4211     hci_stack->le_scan_response_data = scan_response_data;
4212     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
4213     gap_advertisments_changed();
4214 }
4215 
4216 /**
4217  * @brief Set Advertisement Parameters
4218  * @param adv_int_min
4219  * @param adv_int_max
4220  * @param adv_type
4221  * @param direct_address_type
4222  * @param direct_address
4223  * @param channel_map
4224  * @param filter_policy
4225  *
4226  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
4227  */
4228  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
4229     uint8_t direct_address_typ, bd_addr_t direct_address,
4230     uint8_t channel_map, uint8_t filter_policy) {
4231 
4232     hci_stack->le_advertisements_interval_min = adv_int_min;
4233     hci_stack->le_advertisements_interval_max = adv_int_max;
4234     hci_stack->le_advertisements_type = adv_type;
4235     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
4236     hci_stack->le_advertisements_channel_map = channel_map;
4237     hci_stack->le_advertisements_filter_policy = filter_policy;
4238     memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6);
4239 
4240     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4241     gap_advertisments_changed();
4242  }
4243 
4244 /**
4245  * @brief Enable/Disable Advertisements
4246  * @param enabled
4247  */
4248 void gap_advertisements_enable(int enabled){
4249     hci_stack->le_advertisements_enabled = enabled;
4250     if (enabled && !hci_stack->le_advertisements_active){
4251         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
4252     }
4253     if (!enabled && hci_stack->le_advertisements_active){
4254         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE;
4255     }
4256     hci_run();
4257 }
4258 
4259 #endif
4260 
4261 void hci_le_set_own_address_type(uint8_t own_address_type){
4262     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
4263     if (own_address_type == hci_stack->le_own_addr_type) return;
4264     hci_stack->le_own_addr_type = own_address_type;
4265 
4266 #ifdef ENABLE_LE_PERIPHERAL
4267     // update advertisement parameters, too
4268     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4269     gap_advertisments_changed();
4270 #endif
4271 #ifdef ENABLE_LE_CENTRAL
4272     // note: we don't update scan parameters or modify ongoing connection attempts
4273 #endif
4274 }
4275 
4276 #endif
4277 
4278 uint8_t gap_disconnect(hci_con_handle_t handle){
4279     hci_connection_t * conn = hci_connection_for_handle(handle);
4280     if (!conn){
4281         hci_emit_disconnection_complete(handle, 0);
4282         return 0;
4283     }
4284     conn->state = SEND_DISCONNECT;
4285     hci_run();
4286     return 0;
4287 }
4288 
4289 /**
4290  * @brief Get connection type
4291  * @param con_handle
4292  * @result connection_type
4293  */
4294 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
4295     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4296     if (!conn) return GAP_CONNECTION_INVALID;
4297     switch (conn->address_type){
4298         case BD_ADDR_TYPE_LE_PUBLIC:
4299         case BD_ADDR_TYPE_LE_RANDOM:
4300             return GAP_CONNECTION_LE;
4301         case BD_ADDR_TYPE_SCO:
4302             return GAP_CONNECTION_SCO;
4303         case BD_ADDR_TYPE_CLASSIC:
4304             return GAP_CONNECTION_ACL;
4305         default:
4306             return GAP_CONNECTION_INVALID;
4307     }
4308 }
4309 
4310 #ifdef ENABLE_BLE
4311 
4312 #ifdef ENABLE_LE_CENTRAL
4313 /**
4314  * @brief Auto Connection Establishment - Start Connecting to device
4315  * @param address_typ
4316  * @param address
4317  * @returns 0 if ok
4318  */
4319 int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){
4320     // check capacity
4321     int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist);
4322     if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
4323     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
4324     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
4325     entry->address_type = address_type;
4326     memcpy(entry->address, address, 6);
4327     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
4328     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
4329     hci_run();
4330     return 0;
4331 }
4332 
4333 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){
4334     btstack_linked_list_iterator_t it;
4335     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4336     while (btstack_linked_list_iterator_has_next(&it)){
4337         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4338         if (entry->address_type != address_type) continue;
4339         if (memcmp(entry->address, address, 6) != 0) continue;
4340         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4341             // remove from controller if already present
4342             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4343             continue;
4344         }
4345         // direclty remove entry from whitelist
4346         btstack_linked_list_iterator_remove(&it);
4347         btstack_memory_whitelist_entry_free(entry);
4348     }
4349 }
4350 
4351 /**
4352  * @brief Auto Connection Establishment - Stop Connecting to device
4353  * @param address_typ
4354  * @param address
4355  * @returns 0 if ok
4356  */
4357 int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){
4358     hci_remove_from_whitelist(address_type, address);
4359     hci_run();
4360     return 0;
4361 }
4362 
4363 /**
4364  * @brief Auto Connection Establishment - Stop everything
4365  * @note  Convenience function to stop all active auto connection attempts
4366  */
4367 void gap_auto_connection_stop_all(void){
4368     btstack_linked_list_iterator_t it;
4369     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4370     while (btstack_linked_list_iterator_has_next(&it)){
4371         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4372         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4373             // remove from controller if already present
4374             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4375             continue;
4376         }
4377         // directly remove entry from whitelist
4378         btstack_linked_list_iterator_remove(&it);
4379         btstack_memory_whitelist_entry_free(entry);
4380     }
4381     hci_run();
4382 }
4383 #endif
4384 #endif
4385 
4386 #ifdef ENABLE_CLASSIC
4387 /**
4388  * @brief Set Extended Inquiry Response data
4389  * @param eir_data size 240 bytes, is not copied make sure memory is accessible during stack startup
4390  * @note has to be done before stack starts up
4391  */
4392 void gap_set_extended_inquiry_response(const uint8_t * data){
4393     hci_stack->eir_data = data;
4394 }
4395 
4396 /**
4397  * @brief Start GAP Classic Inquiry
4398  * @param duration in 1.28s units
4399  * @return 0 if ok
4400  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
4401  */
4402 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
4403     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4404     if (duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN || duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX){
4405         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
4406     }
4407     hci_stack->inquiry_state = duration_in_1280ms_units;
4408     hci_run();
4409     return 0;
4410 }
4411 
4412 /**
4413  * @brief Stop GAP Classic Inquiry
4414  * @returns 0 if ok
4415  */
4416 int gap_inquiry_stop(void){
4417     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN || hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX) {
4418         // emit inquiry complete event, before it even started
4419         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
4420         hci_emit_event(event, sizeof(event), 1);
4421         return 0;
4422     }
4423     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
4424     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
4425     hci_run();
4426     return 0;
4427 }
4428 
4429 
4430 /**
4431  * @brief Remote Name Request
4432  * @param addr
4433  * @param page_scan_repetition_mode
4434  * @param clock_offset only used when bit 15 is set
4435  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
4436  */
4437 int gap_remote_name_request(bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
4438     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4439     memcpy(hci_stack->remote_name_addr, addr, 6);
4440     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
4441     hci_stack->remote_name_clock_offset = clock_offset;
4442     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
4443     hci_run();
4444     return 0;
4445 }
4446 
4447 static int gap_pairing_set_state_and_run(bd_addr_t addr, uint8_t state){
4448     hci_stack->gap_pairing_state = state;
4449     memcpy(hci_stack->gap_pairing_addr, addr, 6);
4450     hci_run();
4451     return 0;
4452 }
4453 
4454 /**
4455  * @brief Legacy Pairing Pin Code Response
4456  * @param addr
4457  * @param pin
4458  * @return 0 if ok
4459  */
4460 int gap_pin_code_response(bd_addr_t addr, const char * pin){
4461     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4462     hci_stack->gap_pairing_pin = pin;
4463     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
4464 }
4465 
4466 /**
4467  * @brief Abort Legacy Pairing
4468  * @param addr
4469  * @param pin
4470  * @return 0 if ok
4471  */
4472 int gap_pin_code_negative(bd_addr_t addr){
4473     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4474     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
4475 }
4476 
4477 /**
4478  * @brief SSP Passkey Response
4479  * @param addr
4480  * @param passkey
4481  * @return 0 if ok
4482  */
4483 int gap_ssp_passkey_response(bd_addr_t addr, uint32_t passkey){
4484     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4485     hci_stack->gap_pairing_passkey = passkey;
4486     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
4487 }
4488 
4489 /**
4490  * @brief Abort SSP Passkey Entry/Pairing
4491  * @param addr
4492  * @param pin
4493  * @return 0 if ok
4494  */
4495 int gap_ssp_passkey_negative(bd_addr_t addr){
4496     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4497     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
4498 }
4499 
4500 /**
4501  * @brief Accept SSP Numeric Comparison
4502  * @param addr
4503  * @param passkey
4504  * @return 0 if ok
4505  */
4506 int gap_ssp_confirmation_response(bd_addr_t addr){
4507     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4508     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
4509 }
4510 
4511 /**
4512  * @brief Abort SSP Numeric Comparison/Pairing
4513  * @param addr
4514  * @param pin
4515  * @return 0 if ok
4516  */
4517 int gap_ssp_confirmation_negative(bd_addr_t addr){
4518     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4519     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
4520 }
4521 
4522 /**
4523  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
4524  * @param inquiry_mode see bluetooth_defines.h
4525  */
4526 void hci_set_inquiry_mode(inquiry_mode_t mode){
4527     hci_stack->inquiry_mode = mode;
4528 }
4529 
4530 /**
4531  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
4532  */
4533 void hci_set_sco_voice_setting(uint16_t voice_setting){
4534     hci_stack->sco_voice_setting = voice_setting;
4535 }
4536 
4537 /**
4538  * @brief Get SCO Voice Setting
4539  * @return current voice setting
4540  */
4541 uint16_t hci_get_sco_voice_setting(void){
4542     return hci_stack->sco_voice_setting;
4543 }
4544 
4545 /** @brief Get SCO packet length for current SCO Voice setting
4546  *  @note  Using SCO packets of the exact length is required for USB transfer
4547  *  @return Length of SCO packets in bytes (not audio frames)
4548  */
4549 int hci_get_sco_packet_length(void){
4550     // see Core Spec for H2 USB Transfer.
4551     if (hci_stack->sco_voice_setting & 0x0020) return 51;
4552     return 27;
4553 }
4554 
4555 /**
4556 * @brief Sets the master/slave policy
4557 * @param policy (0: attempt to become master, 1: let connecting device decide)
4558 */
4559 void hci_set_master_slave_policy(uint8_t policy){
4560     hci_stack->master_slave_policy = policy;
4561 }
4562 
4563 #endif
4564 
4565 HCI_STATE hci_get_state(void){
4566     return hci_stack->state;
4567 }
4568 
4569 
4570 /**
4571  * @brief Set callback for Bluetooth Hardware Error
4572  */
4573 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
4574     hci_stack->hardware_error_callback = fn;
4575 }
4576 
4577 void hci_disconnect_all(void){
4578     btstack_linked_list_iterator_t it;
4579     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
4580     while (btstack_linked_list_iterator_has_next(&it)){
4581         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
4582         if (con->state == SENT_DISCONNECT) continue;
4583         con->state = SEND_DISCONNECT;
4584     }
4585     hci_run();
4586 }
4587 
4588 uint16_t hci_get_manufacturer(void){
4589     return hci_stack->manufacturer;
4590 }
4591 
4592 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4593     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
4594     if (!hci_con) return NULL;
4595     return &hci_con->sm_connection;
4596 }
4597 
4598 #ifdef ENABLE_BLE
4599 
4600 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
4601 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
4602 
4603 int gap_encryption_key_size(hci_con_handle_t con_handle){
4604     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4605     if (!sm_conn) return 0;     // wrong connection
4606     if (!sm_conn->sm_connection_encrypted) return 0;
4607     return sm_conn->sm_actual_encryption_key_size;
4608 }
4609 
4610 int gap_authenticated(hci_con_handle_t con_handle){
4611     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4612     if (!sm_conn) return 0;     // wrong connection
4613     if (!sm_conn->sm_connection_encrypted) return 0; // unencrypted connection cannot be authenticated
4614     return sm_conn->sm_connection_authenticated;
4615 }
4616 
4617 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
4618     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4619     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
4620     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
4621     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
4622     return sm_conn->sm_connection_authorization_state;
4623 }
4624 #endif
4625