xref: /btstack/src/hci.c (revision 8c41f31fe1a202d98c79d9360d2188a836d32c4b)
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             log_info("Supported commands %x", hci_stack->local_supported_commands[0] & 0x30);
1658             if ((hci_stack->local_supported_commands[0] & 0x30) == 0x30){
1659                 hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1660                 return;
1661             }
1662             // explicit fall through to reduce repetitions
1663 #endif
1664 
1665 #ifdef ENABLE_LE_CENTRAL
1666             hci_stack->substate = HCI_INIT_READ_WHITE_LIST_SIZE;
1667 #else
1668             hci_init_done();
1669 #endif
1670             return;
1671 #endif
1672 
1673 #ifdef ENABLE_SCO_OVER_HCI
1674         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1675             // skip write synchronous flow control if not supported
1676             if (hci_stack->local_supported_commands[0] & 0x04) break;
1677             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1678             // explicit fall through to reduce repetitions
1679 
1680         case HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1681             // skip write default erroneous data reporting if not supported
1682             if (hci_stack->local_supported_commands[0] & 0x08) break;
1683             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1684             // explicit fall through to reduce repetitions
1685 
1686         case HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1687             // skip bcm set sco pcm config on non-Broadcom chipsets
1688             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) break;
1689             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1690             // explicit fall through to reduce repetitions
1691 
1692         case HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT:
1693             if (!hci_le_supported()){
1694                 // SKIP LE init for Classic only configuration
1695                 hci_init_done();
1696                 return;
1697             }
1698             break;
1699 
1700 #else /* !ENABLE_SCO_OVER_HCI */
1701 
1702         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1703 #ifdef ENABLE_BLE
1704             if (hci_le_supported()){
1705                 hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE;
1706                 return;
1707             }
1708 #endif
1709             // SKIP LE init for Classic only configuration
1710             hci_init_done();
1711             return;
1712 #endif /* ENABLE_SCO_OVER_HCI */
1713 
1714         // Response to command before init done state -> init done
1715         case (HCI_INIT_DONE-1):
1716             hci_init_done();
1717             return;
1718 
1719         default:
1720             break;
1721     }
1722     hci_initializing_next_state();
1723 }
1724 
1725 static void event_handler(uint8_t *packet, int size){
1726 
1727     uint16_t event_length = packet[1];
1728 
1729     // assert packet is complete
1730     if (size != event_length + 2){
1731         log_error("hci.c: event_handler called with event packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
1732         return;
1733     }
1734 
1735     bd_addr_t addr;
1736     bd_addr_type_t addr_type;
1737     hci_con_handle_t handle;
1738     hci_connection_t * conn;
1739     int i;
1740 #ifdef ENABLE_CLASSIC
1741     uint8_t link_type;
1742 #endif
1743 
1744     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
1745 
1746     switch (hci_event_packet_get_type(packet)) {
1747 
1748         case HCI_EVENT_COMMAND_COMPLETE:
1749             // get num cmd packets - limit to 1 to reduce complexity
1750             hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
1751 
1752             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_name)){
1753                 if (packet[5]) break;
1754                 // terminate, name 248 chars
1755                 packet[6+248] = 0;
1756                 log_info("local name: %s", &packet[6]);
1757             }
1758             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_buffer_size)){
1759                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
1760                 if (hci_stack->state == HCI_STATE_INITIALIZING){
1761                     uint16_t acl_len = little_endian_read_16(packet, 6);
1762                     uint16_t sco_len = packet[8];
1763 
1764                     // determine usable ACL/SCO payload size
1765                     hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
1766                     hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
1767 
1768                     hci_stack->acl_packets_total_num  = little_endian_read_16(packet, 9);
1769                     hci_stack->sco_packets_total_num  = little_endian_read_16(packet, 11);
1770 
1771                     log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
1772                              acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
1773                              hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
1774                 }
1775             }
1776 #ifdef ENABLE_BLE
1777             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_buffer_size)){
1778                 hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
1779                 hci_stack->le_acl_packets_total_num  = packet[8];
1780                 // determine usable ACL payload size
1781                 if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
1782                     hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
1783                 }
1784                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
1785             }
1786 #endif
1787 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1788             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_maximum_data_length)){
1789                 hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
1790                 hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
1791                 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);
1792             }
1793 #endif
1794 #ifdef ENABLE_LE_CENTRAL
1795             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_white_list_size)){
1796                 hci_stack->le_whitelist_capacity = packet[6];
1797                 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
1798             }
1799 #endif
1800             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
1801                 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1],
1802 				hci_stack->local_bd_addr);
1803                 log_info("Local Address, Status: 0x%02x: Addr: %s",
1804                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
1805 #ifdef ENABLE_CLASSIC
1806                 if (hci_stack->link_key_db){
1807                     hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
1808                 }
1809 #endif
1810             }
1811 #ifdef ENABLE_CLASSIC
1812             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
1813                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1814             }
1815             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_inquiry_cancel)){
1816                 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
1817                     hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
1818                     uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
1819                     hci_emit_event(event, sizeof(event), 1);
1820                 }
1821             }
1822 #endif
1823 
1824             // Note: HCI init checks
1825             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_features)){
1826                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
1827 
1828 #ifdef ENABLE_CLASSIC
1829                 // determine usable ACL packet types based on host buffer size and supported features
1830                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
1831                 log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
1832 #endif
1833                 // Classic/LE
1834                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1835             }
1836             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_version_information)){
1837                 // hci_stack->hci_version    = little_endian_read_16(packet, 4);
1838                 // hci_stack->hci_revision   = little_endian_read_16(packet, 6);
1839                 // hci_stack->lmp_version    = little_endian_read_16(packet, 8);
1840                 hci_stack->manufacturer   = little_endian_read_16(packet, 10);
1841                 // hci_stack->lmp_subversion = little_endian_read_16(packet, 12);
1842                 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
1843             }
1844             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
1845                 hci_stack->local_supported_commands[0] =
1846                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+14] & 0x80) >> 7 |  // bit 0 = Octet 14, bit 7
1847                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+24] & 0x40) >> 5 |  // bit 1 = Octet 24, bit 6
1848                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+10] & 0x10) >> 2 |  // bit 2 = Octet 10, bit 4
1849                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+18] & 0x08)      |  // bit 3 = Octet 18, bit 3
1850                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+34] & 0x01) << 4 |  // bit 4 = Octet 34, bit 0
1851                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+35] & 0x08) << 2;   // bit 5 = Octet 35, bit 3
1852                     log_info("Local supported commands summary 0x%02x", hci_stack->local_supported_commands[0]);
1853             }
1854 #ifdef ENABLE_CLASSIC
1855             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_synchronous_flow_control_enable)){
1856                 if (packet[5] == 0){
1857                     hci_stack->synchronous_flow_control_enabled = 1;
1858                 }
1859             }
1860 #endif
1861             break;
1862 
1863         case HCI_EVENT_COMMAND_STATUS:
1864             // get num cmd packets - limit to 1 to reduce complexity
1865             hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
1866             break;
1867 
1868         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
1869             int offset = 3;
1870             for (i=0; i<packet[2];i++){
1871                 handle = little_endian_read_16(packet, offset);
1872                 offset += 2;
1873                 uint16_t num_packets = little_endian_read_16(packet, offset);
1874                 offset += 2;
1875 
1876                 conn = hci_connection_for_handle(handle);
1877                 if (!conn){
1878                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
1879                     continue;
1880                 }
1881 
1882                 if (conn->address_type == BD_ADDR_TYPE_SCO){
1883 #ifdef ENABLE_CLASSIC
1884                     if (conn->num_sco_packets_sent >= num_packets){
1885                         conn->num_sco_packets_sent -= num_packets;
1886                     } else {
1887                         log_error("hci_number_completed_packets, more sco slots freed then sent.");
1888                         conn->num_sco_packets_sent = 0;
1889                     }
1890                     hci_notify_if_sco_can_send_now();
1891 #endif
1892                 } else {
1893                     if (conn->num_acl_packets_sent >= num_packets){
1894                         conn->num_acl_packets_sent -= num_packets;
1895                     } else {
1896                         log_error("hci_number_completed_packets, more acl slots freed then sent.");
1897                         conn->num_acl_packets_sent = 0;
1898                     }
1899                 }
1900                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
1901             }
1902             break;
1903         }
1904 
1905 #ifdef ENABLE_CLASSIC
1906         case HCI_EVENT_INQUIRY_COMPLETE:
1907             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
1908                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
1909                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
1910                 hci_emit_event(event, sizeof(event), 1);
1911             }
1912             break;
1913         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
1914             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
1915                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
1916             }
1917             break;
1918         case HCI_EVENT_CONNECTION_REQUEST:
1919             reverse_bd_addr(&packet[2], addr);
1920             // TODO: eval COD 8-10
1921             link_type = packet[11];
1922             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
1923             addr_type = link_type == 1 ? BD_ADDR_TYPE_CLASSIC : BD_ADDR_TYPE_SCO;
1924             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1925             if (!conn) {
1926                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1927             }
1928             if (!conn) {
1929                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
1930                 hci_stack->decline_reason = 0x0d;
1931                 bd_addr_copy(hci_stack->decline_addr, addr);
1932                 break;
1933             }
1934             conn->role  = HCI_ROLE_SLAVE;
1935             conn->state = RECEIVED_CONNECTION_REQUEST;
1936             // store info about eSCO
1937             if (link_type == 0x02){
1938                 conn->remote_supported_feature_eSCO = 1;
1939             }
1940             hci_run();
1941             break;
1942 
1943         case HCI_EVENT_CONNECTION_COMPLETE:
1944             // Connection management
1945             reverse_bd_addr(&packet[5], addr);
1946             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1947             addr_type = BD_ADDR_TYPE_CLASSIC;
1948             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1949             if (conn) {
1950                 if (!packet[2]){
1951                     conn->state = OPEN;
1952                     conn->con_handle = little_endian_read_16(packet, 3);
1953                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
1954 
1955                     // restart timer
1956                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1957                     btstack_run_loop_add_timer(&conn->timeout);
1958 
1959                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1960 
1961                     hci_emit_nr_connections_changed();
1962                 } else {
1963                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
1964                     uint8_t status = packet[2];
1965                     bd_addr_t bd_address;
1966                     memcpy(&bd_address, conn->address, 6);
1967 
1968                     // connection failed, remove entry
1969                     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1970                     btstack_memory_hci_connection_free( conn );
1971 
1972                     // notify client if dedicated bonding
1973                     if (notify_dedicated_bonding_failed){
1974                         log_info("hci notify_dedicated_bonding_failed");
1975                         hci_emit_dedicated_bonding_result(bd_address, status);
1976                     }
1977 
1978                     // if authentication error, also delete link key
1979                     if (packet[2] == 0x05) {
1980                         gap_drop_link_key_for_bd_addr(addr);
1981                     }
1982                 }
1983             }
1984             break;
1985 
1986         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
1987             reverse_bd_addr(&packet[5], addr);
1988             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1989             if (packet[2]){
1990                 // connection failed
1991                 break;
1992             }
1993             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1994             if (!conn) {
1995                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1996             }
1997             if (!conn) {
1998                 break;
1999             }
2000             conn->state = OPEN;
2001             conn->con_handle = little_endian_read_16(packet, 3);
2002 
2003 #ifdef ENABLE_SCO_OVER_HCI
2004             // update SCO
2005             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
2006                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
2007             }
2008 #endif
2009             break;
2010 
2011         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2012             handle = little_endian_read_16(packet, 3);
2013             conn = hci_connection_for_handle(handle);
2014             if (!conn) break;
2015             if (!packet[2]){
2016                 uint8_t * features = &packet[5];
2017                 if (features[6] & (1 << 3)){
2018                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
2019                 }
2020                 if (features[3] & (1<<7)){
2021                     conn->remote_supported_feature_eSCO = 1;
2022                 }
2023             }
2024             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
2025             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x, eSCO %u", conn->bonding_flags, conn->remote_supported_feature_eSCO);
2026             if (conn->bonding_flags & BONDING_DEDICATED){
2027                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2028             }
2029             break;
2030 
2031         case HCI_EVENT_LINK_KEY_REQUEST:
2032             log_info("HCI_EVENT_LINK_KEY_REQUEST");
2033             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
2034             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
2035             if (hci_stack->bondable && !hci_stack->link_key_db) break;
2036             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
2037             hci_run();
2038             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
2039             return;
2040 
2041         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
2042             reverse_bd_addr(&packet[2], addr);
2043             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2044             if (!conn) break;
2045             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
2046             link_key_type_t link_key_type = (link_key_type_t)packet[24];
2047             // Change Connection Encryption keeps link key type
2048             if (link_key_type != CHANGED_COMBINATION_KEY){
2049                 conn->link_key_type = link_key_type;
2050             }
2051             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
2052             // still forward event to allow dismiss of pairing dialog
2053             break;
2054         }
2055 
2056         case HCI_EVENT_PIN_CODE_REQUEST:
2057             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
2058             // non-bondable mode: pin code negative reply will be sent
2059             if (!hci_stack->bondable){
2060                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
2061                 hci_run();
2062                 return;
2063             }
2064             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
2065             if (!hci_stack->link_key_db) break;
2066             hci_event_pin_code_request_get_bd_addr(packet, addr);
2067             hci_stack->link_key_db->delete_link_key(addr);
2068             break;
2069 
2070         case HCI_EVENT_IO_CAPABILITY_REQUEST:
2071             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
2072             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
2073             break;
2074 
2075         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
2076             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2077             if (!hci_stack->ssp_auto_accept) break;
2078             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
2079             break;
2080 
2081         case HCI_EVENT_USER_PASSKEY_REQUEST:
2082             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2083             if (!hci_stack->ssp_auto_accept) break;
2084             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
2085             break;
2086 #endif
2087 
2088         case HCI_EVENT_ENCRYPTION_CHANGE:
2089             handle = little_endian_read_16(packet, 3);
2090             conn = hci_connection_for_handle(handle);
2091             if (!conn) break;
2092             if (packet[2] == 0) {
2093                 if (packet[5]){
2094                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
2095                 } else {
2096                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
2097                 }
2098             }
2099 #ifdef ENABLE_CLASSIC
2100             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2101 #endif
2102             break;
2103 
2104 #ifdef ENABLE_CLASSIC
2105         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
2106             handle = little_endian_read_16(packet, 3);
2107             conn = hci_connection_for_handle(handle);
2108             if (!conn) break;
2109 
2110             // dedicated bonding: send result and disconnect
2111             if (conn->bonding_flags & BONDING_DEDICATED){
2112                 conn->bonding_flags &= ~BONDING_DEDICATED;
2113                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2114                 conn->bonding_status = packet[2];
2115                 break;
2116             }
2117 
2118             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
2119                 // link key sufficient for requested security
2120                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2121                 break;
2122             }
2123             // not enough
2124             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2125             break;
2126 #endif
2127 
2128         // HCI_EVENT_DISCONNECTION_COMPLETE
2129         // has been split, to first notify stack before shutting connection down
2130         // see end of function, too.
2131         case HCI_EVENT_DISCONNECTION_COMPLETE:
2132             if (packet[2]) break;   // status != 0
2133             handle = little_endian_read_16(packet, 3);
2134             // drop outgoing ACL fragments if it is for closed connection
2135             if (hci_stack->acl_fragmentation_total_size > 0) {
2136                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
2137                     log_info("hci: drop fragmented ACL data for closed connection");
2138                      hci_stack->acl_fragmentation_total_size = 0;
2139                      hci_stack->acl_fragmentation_pos = 0;
2140                 }
2141             }
2142 
2143             // re-enable advertisements for le connections if active
2144             conn = hci_connection_for_handle(handle);
2145             if (!conn) break;
2146 #ifdef ENABLE_BLE
2147 #ifdef ENABLE_LE_PERIPHERAL
2148             if (hci_is_le_connection(conn) && hci_stack->le_advertisements_enabled){
2149                 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
2150             }
2151 #endif
2152 #endif
2153             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
2154             break;
2155 
2156         case HCI_EVENT_HARDWARE_ERROR:
2157             log_error("Hardware Error: 0x%02x", packet[2]);
2158             if (hci_stack->hardware_error_callback){
2159                 (*hci_stack->hardware_error_callback)(packet[2]);
2160             } else {
2161                 // if no special requests, just reboot stack
2162                 hci_power_control_off();
2163                 hci_power_control_on();
2164             }
2165             break;
2166 
2167 #ifdef ENABLE_CLASSIC
2168         case HCI_EVENT_ROLE_CHANGE:
2169             if (packet[2]) break;   // status != 0
2170             reverse_bd_addr(&packet[3], addr);
2171             addr_type = BD_ADDR_TYPE_CLASSIC;
2172             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2173             if (!conn) break;
2174             conn->role = packet[9];
2175             break;
2176 #endif
2177 
2178         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2179             // release packet buffer only for asynchronous transport and if there are not further fragements
2180             if (hci_transport_synchronous()) {
2181                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
2182                 return; // instead of break: to avoid re-entering hci_run()
2183             }
2184             if (hci_stack->acl_fragmentation_total_size) break;
2185             hci_release_packet_buffer();
2186 
2187             // L2CAP receives this event via the hci_emit_event below
2188 
2189 #ifdef ENABLE_CLASSIC
2190             // For SCO, we do the can_send_now_check here
2191             hci_notify_if_sco_can_send_now();
2192 #endif
2193             break;
2194 
2195 #ifdef ENABLE_CLASSIC
2196         case HCI_EVENT_SCO_CAN_SEND_NOW:
2197             // For SCO, we do the can_send_now_check here
2198             hci_notify_if_sco_can_send_now();
2199             return;
2200 
2201         // explode inquriy results for easier consumption
2202         case HCI_EVENT_INQUIRY_RESULT:
2203         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
2204         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
2205             gap_inquiry_explode(packet);
2206             break;
2207 #endif
2208 
2209 #ifdef ENABLE_BLE
2210         case HCI_EVENT_LE_META:
2211             switch (packet[2]){
2212 #ifdef ENABLE_LE_CENTRAL
2213                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
2214                     // log_info("advertising report received");
2215                     if (!hci_stack->le_scanning_enabled) break;
2216                     le_handle_advertisement_report(packet, size);
2217                     break;
2218 #endif
2219                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
2220                     // Connection management
2221                     reverse_bd_addr(&packet[8], addr);
2222                     addr_type = (bd_addr_type_t)packet[7];
2223                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
2224                     conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2225 
2226 #ifdef ENABLE_LE_CENTRAL
2227                     // if auto-connect, remove from whitelist in both roles
2228                     if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){
2229                         hci_remove_from_whitelist(addr_type, addr);
2230                     }
2231                     // handle error: error is reported only to the initiator -> outgoing connection
2232                     if (packet[3]){
2233 
2234                         // handle cancelled outgoing connection
2235                         // "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
2236                         //  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
2237                         //  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
2238                         if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
2239                             conn = gap_get_outgoing_connection();
2240                         }
2241 
2242                         // outgoing connection establishment is done
2243                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2244                         // remove entry
2245                         if (conn){
2246                             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2247                             btstack_memory_hci_connection_free( conn );
2248                         }
2249                         break;
2250                     }
2251 #endif
2252                     // on success, both hosts receive connection complete event
2253                     if (packet[6] == HCI_ROLE_MASTER){
2254 #ifdef ENABLE_LE_CENTRAL
2255                         // if we're master, it was an outgoing connection and we're done with it
2256                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2257 #endif
2258                     } else {
2259 #ifdef ENABLE_LE_PERIPHERAL
2260                         // if we're slave, it was an incoming connection, advertisements have stopped
2261                         hci_stack->le_advertisements_active = 0;
2262                         // try to re-enable them
2263                         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
2264 #endif
2265                     }
2266                     // LE connections are auto-accepted, so just create a connection if there isn't one already
2267                     if (!conn){
2268                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2269                     }
2270                     // no memory, sorry.
2271                     if (!conn){
2272                         break;
2273                     }
2274 
2275                     conn->state = OPEN;
2276                     conn->role  = packet[6];
2277                     conn->con_handle = little_endian_read_16(packet, 4);
2278 
2279                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
2280 
2281                     // restart timer
2282                     // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2283                     // btstack_run_loop_add_timer(&conn->timeout);
2284 
2285                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2286 
2287                     hci_emit_nr_connections_changed();
2288                     break;
2289 
2290             // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
2291 
2292                 default:
2293                     break;
2294             }
2295             break;
2296 #endif
2297         default:
2298             break;
2299     }
2300 
2301     // handle BT initialization
2302     if (hci_stack->state == HCI_STATE_INITIALIZING){
2303         hci_initializing_event_handler(packet, size);
2304     }
2305 
2306     // help with BT sleep
2307     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
2308         && hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE
2309         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
2310         hci_initializing_next_state();
2311     }
2312 
2313     // notify upper stack
2314 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
2315 
2316     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
2317     if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){
2318         if (!packet[2]){
2319             handle = little_endian_read_16(packet, 3);
2320             hci_connection_t * aConn = hci_connection_for_handle(handle);
2321             if (aConn) {
2322                 uint8_t status = aConn->bonding_status;
2323                 uint16_t flags = aConn->bonding_flags;
2324                 bd_addr_t bd_address;
2325                 memcpy(&bd_address, aConn->address, 6);
2326                 hci_shutdown_connection(aConn);
2327                 // connection struct is gone, don't access anymore
2328                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
2329                     hci_emit_dedicated_bonding_result(bd_address, status);
2330                 }
2331             }
2332         }
2333     }
2334 
2335 	// execute main loop
2336 	hci_run();
2337 }
2338 
2339 #ifdef ENABLE_CLASSIC
2340 static void sco_handler(uint8_t * packet, uint16_t size){
2341     if (!hci_stack->sco_packet_handler) return;
2342     hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
2343 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2344     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
2345     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
2346     if (conn){
2347         conn->num_packets_completed++;
2348         hci_stack->host_completed_packets = 1;
2349         hci_run();
2350     }
2351 #endif
2352 }
2353 #endif
2354 
2355 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
2356     hci_dump_packet(packet_type, 1, packet, size);
2357     switch (packet_type) {
2358         case HCI_EVENT_PACKET:
2359             event_handler(packet, size);
2360             break;
2361         case HCI_ACL_DATA_PACKET:
2362             acl_handler(packet, size);
2363             break;
2364 #ifdef ENABLE_CLASSIC
2365         case HCI_SCO_DATA_PACKET:
2366             sco_handler(packet, size);
2367             break;
2368 #endif
2369         default:
2370             break;
2371     }
2372 }
2373 
2374 /**
2375  * @brief Add event packet handler.
2376  */
2377 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
2378     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
2379 }
2380 
2381 
2382 /** Register HCI packet handlers */
2383 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
2384     hci_stack->acl_packet_handler = handler;
2385 }
2386 
2387 #ifdef ENABLE_CLASSIC
2388 /**
2389  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
2390  */
2391 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
2392     hci_stack->sco_packet_handler = handler;
2393 }
2394 #endif
2395 
2396 static void hci_state_reset(void){
2397     // no connections yet
2398     hci_stack->connections = NULL;
2399 
2400     // keep discoverable/connectable as this has been requested by the client(s)
2401     // hci_stack->discoverable = 0;
2402     // hci_stack->connectable = 0;
2403     // hci_stack->bondable = 1;
2404     // hci_stack->own_addr_type = 0;
2405 
2406     // buffer is free
2407     hci_stack->hci_packet_buffer_reserved = 0;
2408 
2409     // no pending cmds
2410     hci_stack->decline_reason = 0;
2411     hci_stack->new_scan_enable_value = 0xff;
2412 
2413     // LE
2414 #ifdef ENABLE_BLE
2415     memset(hci_stack->le_random_address, 0, 6);
2416     hci_stack->le_random_address_set = 0;
2417 #endif
2418 #ifdef ENABLE_LE_CENTRAL
2419     hci_stack->le_scanning_active  = 0;
2420     hci_stack->le_scan_type = 0xff;
2421     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2422     hci_stack->le_whitelist = 0;
2423     hci_stack->le_whitelist_capacity = 0;
2424 #endif
2425 }
2426 
2427 #ifdef ENABLE_CLASSIC
2428 /**
2429  * @brief Configure Bluetooth hardware control. Has to be called before power on.
2430  */
2431 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
2432     // store and open remote device db
2433     hci_stack->link_key_db = link_key_db;
2434     if (hci_stack->link_key_db) {
2435         hci_stack->link_key_db->open();
2436     }
2437 }
2438 #endif
2439 
2440 void hci_init(const hci_transport_t *transport, const void *config){
2441 
2442 #ifdef HAVE_MALLOC
2443     if (!hci_stack) {
2444         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
2445     }
2446 #else
2447     hci_stack = &hci_stack_static;
2448 #endif
2449     memset(hci_stack, 0, sizeof(hci_stack_t));
2450 
2451     // reference to use transport layer implementation
2452     hci_stack->hci_transport = transport;
2453 
2454     // reference to used config
2455     hci_stack->config = config;
2456 
2457     // setup pointer for outgoing packet buffer
2458     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
2459 
2460     // max acl payload size defined in config.h
2461     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
2462 
2463     // register packet handlers with transport
2464     transport->register_packet_handler(&packet_handler);
2465 
2466     hci_stack->state = HCI_STATE_OFF;
2467 
2468     // class of device
2469     hci_stack->class_of_device = 0x007a020c; // Smartphone
2470 
2471     // bondable by default
2472     hci_stack->bondable = 1;
2473 
2474 #ifdef ENABLE_CLASSIC
2475     // classic name
2476     hci_stack->local_name = default_classic_name;
2477 
2478     // Master slave policy
2479     hci_stack->master_slave_policy = 1;
2480 #endif
2481 
2482     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
2483     hci_stack->ssp_enable = 1;
2484     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
2485     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
2486     hci_stack->ssp_auto_accept = 1;
2487 
2488     // voice setting - signed 16 bit pcm data with CVSD over the air
2489     hci_stack->sco_voice_setting = 0x60;
2490 
2491 #ifdef ENABLE_LE_CENTRAL
2492     // connection parameter to use for outgoing connections
2493     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
2494     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
2495     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
2496     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
2497     hci_stack->le_connection_latency      = 4;         // 4
2498     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
2499     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
2500     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
2501 #endif
2502 
2503     // connection parameter range used to answer connection parameter update requests in l2cap
2504     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
2505     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
2506     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
2507     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
2508     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
2509     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
2510 
2511     hci_state_reset();
2512 }
2513 
2514 /**
2515  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
2516  */
2517 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
2518     hci_stack->chipset = chipset_driver;
2519 
2520     // reset chipset driver - init is also called on power_up
2521     if (hci_stack->chipset && hci_stack->chipset->init){
2522         hci_stack->chipset->init(hci_stack->config);
2523     }
2524 }
2525 
2526 /**
2527  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
2528  */
2529 void hci_set_control(const btstack_control_t *hardware_control){
2530     // references to used control implementation
2531     hci_stack->control = hardware_control;
2532     // init with transport config
2533     hardware_control->init(hci_stack->config);
2534 }
2535 
2536 void hci_close(void){
2537     // close remote device db
2538     if (hci_stack->link_key_db) {
2539         hci_stack->link_key_db->close();
2540     }
2541 
2542     btstack_linked_list_iterator_t lit;
2543     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
2544     while (btstack_linked_list_iterator_has_next(&lit)){
2545         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
2546         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
2547         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
2548         hci_shutdown_connection(connection);
2549     }
2550 
2551     hci_power_control(HCI_POWER_OFF);
2552 
2553 #ifdef HAVE_MALLOC
2554     free(hci_stack);
2555 #endif
2556     hci_stack = NULL;
2557 }
2558 
2559 #ifdef ENABLE_CLASSIC
2560 void gap_set_class_of_device(uint32_t class_of_device){
2561     hci_stack->class_of_device = class_of_device;
2562 }
2563 
2564 void hci_disable_l2cap_timeout_check(void){
2565     disable_l2cap_timeouts = 1;
2566 }
2567 #endif
2568 
2569 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
2570 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
2571 void hci_set_bd_addr(bd_addr_t addr){
2572     memcpy(hci_stack->custom_bd_addr, addr, 6);
2573     hci_stack->custom_bd_addr_set = 1;
2574 }
2575 #endif
2576 
2577 // State-Module-Driver overview
2578 // state                    module  low-level
2579 // HCI_STATE_OFF             off      close
2580 // HCI_STATE_INITIALIZING,   on       open
2581 // HCI_STATE_WORKING,        on       open
2582 // HCI_STATE_HALTING,        on       open
2583 // HCI_STATE_SLEEPING,    off/sleep   close
2584 // HCI_STATE_FALLING_ASLEEP  on       open
2585 
2586 static int hci_power_control_on(void){
2587 
2588     // power on
2589     int err = 0;
2590     if (hci_stack->control && hci_stack->control->on){
2591         err = (*hci_stack->control->on)();
2592     }
2593     if (err){
2594         log_error( "POWER_ON failed");
2595         hci_emit_hci_open_failed();
2596         return err;
2597     }
2598 
2599     // int chipset driver
2600     if (hci_stack->chipset && hci_stack->chipset->init){
2601         hci_stack->chipset->init(hci_stack->config);
2602     }
2603 
2604     // init transport
2605     if (hci_stack->hci_transport->init){
2606         hci_stack->hci_transport->init(hci_stack->config);
2607     }
2608 
2609     // open transport
2610     err = hci_stack->hci_transport->open();
2611     if (err){
2612         log_error( "HCI_INIT failed, turning Bluetooth off again");
2613         if (hci_stack->control && hci_stack->control->off){
2614             (*hci_stack->control->off)();
2615         }
2616         hci_emit_hci_open_failed();
2617         return err;
2618     }
2619     return 0;
2620 }
2621 
2622 static void hci_power_control_off(void){
2623 
2624     log_info("hci_power_control_off");
2625 
2626     // close low-level device
2627     hci_stack->hci_transport->close();
2628 
2629     log_info("hci_power_control_off - hci_transport closed");
2630 
2631     // power off
2632     if (hci_stack->control && hci_stack->control->off){
2633         (*hci_stack->control->off)();
2634     }
2635 
2636     log_info("hci_power_control_off - control closed");
2637 
2638     hci_stack->state = HCI_STATE_OFF;
2639 }
2640 
2641 static void hci_power_control_sleep(void){
2642 
2643     log_info("hci_power_control_sleep");
2644 
2645 #if 0
2646     // don't close serial port during sleep
2647 
2648     // close low-level device
2649     hci_stack->hci_transport->close(hci_stack->config);
2650 #endif
2651 
2652     // sleep mode
2653     if (hci_stack->control && hci_stack->control->sleep){
2654         (*hci_stack->control->sleep)();
2655     }
2656 
2657     hci_stack->state = HCI_STATE_SLEEPING;
2658 }
2659 
2660 static int hci_power_control_wake(void){
2661 
2662     log_info("hci_power_control_wake");
2663 
2664     // wake on
2665     if (hci_stack->control && hci_stack->control->wake){
2666         (*hci_stack->control->wake)();
2667     }
2668 
2669 #if 0
2670     // open low-level device
2671     int err = hci_stack->hci_transport->open(hci_stack->config);
2672     if (err){
2673         log_error( "HCI_INIT failed, turning Bluetooth off again");
2674         if (hci_stack->control && hci_stack->control->off){
2675             (*hci_stack->control->off)();
2676         }
2677         hci_emit_hci_open_failed();
2678         return err;
2679     }
2680 #endif
2681 
2682     return 0;
2683 }
2684 
2685 static void hci_power_transition_to_initializing(void){
2686     // set up state machine
2687     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
2688     hci_stack->hci_packet_buffer_reserved = 0;
2689     hci_stack->state = HCI_STATE_INITIALIZING;
2690     hci_stack->substate = HCI_INIT_SEND_RESET;
2691 }
2692 
2693 int hci_power_control(HCI_POWER_MODE power_mode){
2694 
2695     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
2696 
2697     int err = 0;
2698     switch (hci_stack->state){
2699 
2700         case HCI_STATE_OFF:
2701             switch (power_mode){
2702                 case HCI_POWER_ON:
2703                     err = hci_power_control_on();
2704                     if (err) {
2705                         log_error("hci_power_control_on() error %d", err);
2706                         return err;
2707                     }
2708                     hci_power_transition_to_initializing();
2709                     break;
2710                 case HCI_POWER_OFF:
2711                     // do nothing
2712                     break;
2713                 case HCI_POWER_SLEEP:
2714                     // do nothing (with SLEEP == OFF)
2715                     break;
2716             }
2717             break;
2718 
2719         case HCI_STATE_INITIALIZING:
2720             switch (power_mode){
2721                 case HCI_POWER_ON:
2722                     // do nothing
2723                     break;
2724                 case HCI_POWER_OFF:
2725                     // no connections yet, just turn it off
2726                     hci_power_control_off();
2727                     break;
2728                 case HCI_POWER_SLEEP:
2729                     // no connections yet, just turn it off
2730                     hci_power_control_sleep();
2731                     break;
2732             }
2733             break;
2734 
2735         case HCI_STATE_WORKING:
2736             switch (power_mode){
2737                 case HCI_POWER_ON:
2738                     // do nothing
2739                     break;
2740                 case HCI_POWER_OFF:
2741                     // see hci_run
2742                     hci_stack->state = HCI_STATE_HALTING;
2743                     break;
2744                 case HCI_POWER_SLEEP:
2745                     // see hci_run
2746                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2747                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2748                     break;
2749             }
2750             break;
2751 
2752         case HCI_STATE_HALTING:
2753             switch (power_mode){
2754                 case HCI_POWER_ON:
2755                     hci_power_transition_to_initializing();
2756                     break;
2757                 case HCI_POWER_OFF:
2758                     // do nothing
2759                     break;
2760                 case HCI_POWER_SLEEP:
2761                     // see hci_run
2762                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2763                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2764                     break;
2765             }
2766             break;
2767 
2768         case HCI_STATE_FALLING_ASLEEP:
2769             switch (power_mode){
2770                 case HCI_POWER_ON:
2771 
2772 #ifdef HAVE_PLATFORM_IPHONE_OS
2773                     // nothing to do, if H4 supports power management
2774                     if (btstack_control_iphone_power_management_enabled()){
2775                         hci_stack->state = HCI_STATE_INITIALIZING;
2776                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
2777                         break;
2778                     }
2779 #endif
2780                     hci_power_transition_to_initializing();
2781                     break;
2782                 case HCI_POWER_OFF:
2783                     // see hci_run
2784                     hci_stack->state = HCI_STATE_HALTING;
2785                     break;
2786                 case HCI_POWER_SLEEP:
2787                     // do nothing
2788                     break;
2789             }
2790             break;
2791 
2792         case HCI_STATE_SLEEPING:
2793             switch (power_mode){
2794                 case HCI_POWER_ON:
2795 
2796 #ifdef HAVE_PLATFORM_IPHONE_OS
2797                     // nothing to do, if H4 supports power management
2798                     if (btstack_control_iphone_power_management_enabled()){
2799                         hci_stack->state = HCI_STATE_INITIALIZING;
2800                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
2801                         hci_update_scan_enable();
2802                         break;
2803                     }
2804 #endif
2805                     err = hci_power_control_wake();
2806                     if (err) return err;
2807                     hci_power_transition_to_initializing();
2808                     break;
2809                 case HCI_POWER_OFF:
2810                     hci_stack->state = HCI_STATE_HALTING;
2811                     break;
2812                 case HCI_POWER_SLEEP:
2813                     // do nothing
2814                     break;
2815             }
2816             break;
2817     }
2818 
2819     // create internal event
2820 	hci_emit_state();
2821 
2822 	// trigger next/first action
2823 	hci_run();
2824 
2825     return 0;
2826 }
2827 
2828 
2829 #ifdef ENABLE_CLASSIC
2830 
2831 static void hci_update_scan_enable(void){
2832     // 2 = page scan, 1 = inq scan
2833     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
2834     hci_run();
2835 }
2836 
2837 void gap_discoverable_control(uint8_t enable){
2838     if (enable) enable = 1; // normalize argument
2839 
2840     if (hci_stack->discoverable == enable){
2841         hci_emit_discoverable_enabled(hci_stack->discoverable);
2842         return;
2843     }
2844 
2845     hci_stack->discoverable = enable;
2846     hci_update_scan_enable();
2847 }
2848 
2849 void gap_connectable_control(uint8_t enable){
2850     if (enable) enable = 1; // normalize argument
2851 
2852     // don't emit event
2853     if (hci_stack->connectable == enable) return;
2854 
2855     hci_stack->connectable = enable;
2856     hci_update_scan_enable();
2857 }
2858 #endif
2859 
2860 void gap_local_bd_addr(bd_addr_t address_buffer){
2861     memcpy(address_buffer, hci_stack->local_bd_addr, 6);
2862 }
2863 
2864 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2865 static void hci_host_num_completed_packets(void){
2866 
2867     // create packet manually as arrays are not supported and num_commands should not get reduced
2868     hci_reserve_packet_buffer();
2869     uint8_t * packet = hci_get_outgoing_packet_buffer();
2870 
2871     uint16_t size = 0;
2872     uint16_t num_handles = 0;
2873     packet[size++] = 0x35;
2874     packet[size++] = 0x0c;
2875     size++;  // skip param len
2876     size++;  // skip num handles
2877 
2878     // add { handle, packets } entries
2879     btstack_linked_item_t * it;
2880     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
2881         hci_connection_t * connection = (hci_connection_t *) it;
2882         if (connection->num_packets_completed){
2883             little_endian_store_16(packet, size, connection->con_handle);
2884             size += 2;
2885             little_endian_store_16(packet, size, connection->num_packets_completed);
2886             size += 2;
2887             //
2888             num_handles++;
2889             connection->num_packets_completed = 0;
2890         }
2891     }
2892 
2893     packet[2] = size - 3;
2894     packet[3] = num_handles;
2895 
2896     hci_stack->host_completed_packets = 0;
2897 
2898     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
2899     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
2900 
2901     // release packet buffer for synchronous transport implementations
2902     if (hci_transport_synchronous()){
2903         hci_stack->hci_packet_buffer_reserved = 0;
2904     }
2905 }
2906 #endif
2907 
2908 static void hci_run(void){
2909 
2910     // log_info("hci_run: entered");
2911     btstack_linked_item_t * it;
2912 
2913     // send continuation fragments first, as they block the prepared packet buffer
2914     if (hci_stack->acl_fragmentation_total_size > 0) {
2915         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
2916         hci_connection_t *connection = hci_connection_for_handle(con_handle);
2917         if (connection) {
2918             if (hci_can_send_prepared_acl_packet_now(con_handle)){
2919                 hci_send_acl_packet_fragments(connection);
2920                 return;
2921             }
2922         } else {
2923             // connection gone -> discard further fragments
2924             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
2925             hci_stack->acl_fragmentation_total_size = 0;
2926             hci_stack->acl_fragmentation_pos = 0;
2927         }
2928     }
2929 
2930 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2931     // send host num completed packets next as they don't require num_cmd_packets > 0
2932     if (!hci_can_send_comand_packet_transport()) return;
2933     if (hci_stack->host_completed_packets){
2934         hci_host_num_completed_packets();
2935         return;
2936     }
2937 #endif
2938 
2939     if (!hci_can_send_command_packet_now()) return;
2940 
2941     // global/non-connection oriented commands
2942 
2943 #ifdef ENABLE_CLASSIC
2944     // decline incoming connections
2945     if (hci_stack->decline_reason){
2946         uint8_t reason = hci_stack->decline_reason;
2947         hci_stack->decline_reason = 0;
2948         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
2949         return;
2950     }
2951     // send scan enable
2952     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
2953         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
2954         hci_stack->new_scan_enable_value = 0xff;
2955         return;
2956     }
2957     // start/stop inquiry
2958     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN && hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX){
2959         uint8_t duration = hci_stack->inquiry_state;
2960         hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
2961         hci_send_cmd(&hci_inquiry, HCI_INQUIRY_LAP, duration, 0);
2962         return;
2963     }
2964     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
2965         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
2966         hci_send_cmd(&hci_inquiry_cancel);
2967         return;
2968     }
2969     // remote name request
2970     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
2971         hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
2972         hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
2973             hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
2974         return;
2975     }
2976     // pairing
2977     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
2978         uint8_t state = hci_stack->gap_pairing_state;
2979         hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
2980         switch (state){
2981             case GAP_PAIRING_STATE_SEND_PIN:
2982                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, strlen(hci_stack->gap_pairing_pin), hci_stack->gap_pairing_pin);
2983                 break;
2984             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
2985                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
2986                 break;
2987             case GAP_PAIRING_STATE_SEND_PASSKEY:
2988                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_passkey);
2989                 break;
2990             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
2991                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
2992                 break;
2993             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
2994                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
2995                 break;
2996             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
2997                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
2998                 break;
2999             default:
3000                 break;
3001         }
3002         return;
3003     }
3004 #endif
3005 
3006 #ifdef ENABLE_BLE
3007     // advertisements, active scanning, and creating connections requires randaom address to be set if using private address
3008     if ((hci_stack->state == HCI_STATE_WORKING)
3009     && (hci_stack->le_own_addr_type == BD_ADDR_TYPE_LE_PUBLIC || hci_stack->le_random_address_set)){
3010 
3011 #ifdef ENABLE_LE_CENTRAL
3012         // handle le scan
3013         if ((hci_stack->le_scanning_enabled != hci_stack->le_scanning_active)){
3014             hci_stack->le_scanning_active = hci_stack->le_scanning_enabled;
3015             hci_send_cmd(&hci_le_set_scan_enable, hci_stack->le_scanning_enabled, 0);
3016             return;
3017         }
3018         if (hci_stack->le_scan_type != 0xff){
3019             // defaults: active scanning, accept all advertisement packets
3020             int scan_type = hci_stack->le_scan_type;
3021             hci_stack->le_scan_type = 0xff;
3022             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);
3023             return;
3024         }
3025 #endif
3026 #ifdef ENABLE_LE_PERIPHERAL
3027         // le advertisement control
3028         if (hci_stack->le_advertisements_todo){
3029             log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo );
3030         }
3031         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){
3032             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE;
3033             hci_send_cmd(&hci_le_set_advertise_enable, 0);
3034             return;
3035         }
3036         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
3037             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3038             hci_send_cmd(&hci_le_set_advertising_parameters,
3039                  hci_stack->le_advertisements_interval_min,
3040                  hci_stack->le_advertisements_interval_max,
3041                  hci_stack->le_advertisements_type,
3042                  hci_stack->le_own_addr_type,
3043                  hci_stack->le_advertisements_direct_address_type,
3044                  hci_stack->le_advertisements_direct_address,
3045                  hci_stack->le_advertisements_channel_map,
3046                  hci_stack->le_advertisements_filter_policy);
3047             return;
3048         }
3049         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
3050             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3051             uint8_t adv_data_clean[31];
3052             memset(adv_data_clean, 0, sizeof(adv_data_clean));
3053             memcpy(adv_data_clean, hci_stack->le_advertisements_data, hci_stack->le_advertisements_data_len);
3054             hci_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len);
3055             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
3056             return;
3057         }
3058         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
3059             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
3060             uint8_t scan_data_clean[31];
3061             memset(scan_data_clean, 0, sizeof(scan_data_clean));
3062             memcpy(scan_data_clean, hci_stack->le_scan_response_data, hci_stack->le_scan_response_data_len);
3063             hci_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len);
3064             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, hci_stack->le_scan_response_data);
3065             return;
3066         }
3067         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){
3068             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE;
3069             hci_send_cmd(&hci_le_set_advertise_enable, 1);
3070             return;
3071         }
3072 #endif
3073 
3074 #ifdef ENABLE_LE_CENTRAL
3075         //
3076         // LE Whitelist Management
3077         //
3078 
3079         // check if whitelist needs modification
3080         btstack_linked_list_iterator_t lit;
3081         int modification_pending = 0;
3082         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3083         while (btstack_linked_list_iterator_has_next(&lit)){
3084             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3085             if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
3086                 modification_pending = 1;
3087                 break;
3088             }
3089         }
3090 
3091         if (modification_pending){
3092             // stop connnecting if modification pending
3093             if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){
3094                 hci_send_cmd(&hci_le_create_connection_cancel);
3095                 return;
3096             }
3097 
3098             // add/remove entries
3099             btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3100             while (btstack_linked_list_iterator_has_next(&lit)){
3101                 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3102                 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
3103                     entry->state = LE_WHITELIST_ON_CONTROLLER;
3104                     hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
3105                     return;
3106 
3107                 }
3108                 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
3109                     bd_addr_t address;
3110                     bd_addr_type_t address_type = entry->address_type;
3111                     memcpy(address, entry->address, 6);
3112                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3113                     btstack_memory_whitelist_entry_free(entry);
3114                     hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
3115                     return;
3116                 }
3117             }
3118         }
3119 
3120         // start connecting
3121         if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE &&
3122             !btstack_linked_list_empty(&hci_stack->le_whitelist)){
3123             bd_addr_t null_addr;
3124             memset(null_addr, 0, 6);
3125             hci_send_cmd(&hci_le_create_connection,
3126                 hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
3127                 hci_stack->le_connection_scan_window,    // scan interval: 30 ms
3128                  1,         // use whitelist
3129                  0,         // peer address type
3130                  null_addr, // peer bd addr
3131                  hci_stack->le_own_addr_type, // our addr type:
3132                  hci_stack->le_connection_interval_min,    // conn interval min
3133                  hci_stack->le_connection_interval_max,    // conn interval max
3134                  hci_stack->le_connection_latency,         // conn latency
3135                  hci_stack->le_supervision_timeout,        // conn latency
3136                  hci_stack->le_minimum_ce_length,          // min ce length
3137                  hci_stack->le_maximum_ce_length           // max ce length
3138                 );
3139             return;
3140         }
3141 #endif
3142     }
3143 #endif
3144 
3145     // send pending HCI commands
3146     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3147         hci_connection_t * connection = (hci_connection_t *) it;
3148 
3149         switch(connection->state){
3150             case SEND_CREATE_CONNECTION:
3151                 switch(connection->address_type){
3152 #ifdef ENABLE_CLASSIC
3153                     case BD_ADDR_TYPE_CLASSIC:
3154                         log_info("sending hci_create_connection");
3155                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
3156                         break;
3157 #endif
3158                     default:
3159 #ifdef ENABLE_BLE
3160 #ifdef ENABLE_LE_CENTRAL
3161                         log_info("sending hci_le_create_connection");
3162                         hci_send_cmd(&hci_le_create_connection,
3163                              hci_stack->le_connection_scan_interval,    // conn scan interval
3164                              hci_stack->le_connection_scan_window,      // conn scan windows
3165                              0,         // don't use whitelist
3166                              connection->address_type, // peer address type
3167                              connection->address,      // peer bd addr
3168                              hci_stack->le_own_addr_type, // our addr type:
3169                              hci_stack->le_connection_interval_min,    // conn interval min
3170                              hci_stack->le_connection_interval_max,    // conn interval max
3171                              hci_stack->le_connection_latency,         // conn latency
3172                              hci_stack->le_supervision_timeout,        // conn latency
3173                              hci_stack->le_minimum_ce_length,          // min ce length
3174                              hci_stack->le_maximum_ce_length          // max ce length
3175                              );
3176                         connection->state = SENT_CREATE_CONNECTION;
3177 #endif
3178 #endif
3179                         break;
3180                 }
3181                 return;
3182 
3183 #ifdef ENABLE_CLASSIC
3184             case RECEIVED_CONNECTION_REQUEST:
3185                 log_info("sending hci_accept_connection_request, remote eSCO %u", connection->remote_supported_feature_eSCO);
3186                 connection->state = ACCEPTED_CONNECTION_REQUEST;
3187                 connection->role  = HCI_ROLE_SLAVE;
3188                 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
3189                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
3190                 }
3191                 return;
3192 #endif
3193 
3194 #ifdef ENABLE_BLE
3195 #ifdef ENABLE_LE_CENTRAL
3196             case SEND_CANCEL_CONNECTION:
3197                 connection->state = SENT_CANCEL_CONNECTION;
3198                 hci_send_cmd(&hci_le_create_connection_cancel);
3199                 return;
3200 #endif
3201 #endif
3202             case SEND_DISCONNECT:
3203                 connection->state = SENT_DISCONNECT;
3204                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
3205                 return;
3206 
3207             default:
3208                 break;
3209         }
3210 
3211 #ifdef ENABLE_CLASSIC
3212         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
3213             log_info("responding to link key request");
3214             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
3215             link_key_t link_key;
3216             link_key_type_t link_key_type;
3217             if ( hci_stack->link_key_db
3218               && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type)
3219               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
3220                connection->link_key_type = link_key_type;
3221                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
3222             } else {
3223                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
3224             }
3225             return;
3226         }
3227 
3228         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
3229             log_info("denying to pin request");
3230             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
3231             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
3232             return;
3233         }
3234 
3235         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
3236             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
3237             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
3238             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
3239                 // tweak authentication requirements
3240                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
3241                 if (connection->bonding_flags & BONDING_DEDICATED){
3242                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
3243                 }
3244                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
3245                     authreq |= 1;
3246                 }
3247                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
3248             } else {
3249                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
3250             }
3251             return;
3252         }
3253 
3254         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
3255             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
3256             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
3257             return;
3258         }
3259 
3260         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
3261             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
3262             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
3263             return;
3264         }
3265 
3266         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
3267             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
3268             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
3269             return;
3270         }
3271 
3272         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
3273             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
3274             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
3275             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
3276             return;
3277         }
3278 
3279         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
3280             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
3281             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
3282             return;
3283         }
3284 
3285         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
3286             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
3287             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
3288             return;
3289         }
3290 #endif
3291 
3292         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
3293             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
3294             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
3295             return;
3296         }
3297 
3298 #ifdef ENABLE_BLE
3299         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
3300             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3301 
3302             uint16_t connection_interval_min = connection->le_conn_interval_min;
3303             connection->le_conn_interval_min = 0;
3304             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
3305                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
3306                 0x0000, 0xffff);
3307         }
3308 #endif
3309     }
3310 
3311     hci_connection_t * connection;
3312     switch (hci_stack->state){
3313         case HCI_STATE_INITIALIZING:
3314             hci_initializing_run();
3315             break;
3316 
3317         case HCI_STATE_HALTING:
3318 
3319             log_info("HCI_STATE_HALTING");
3320 
3321             // free whitelist entries
3322 #ifdef ENABLE_BLE
3323 #ifdef ENABLE_LE_CENTRAL
3324             {
3325                 btstack_linked_list_iterator_t lit;
3326                 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3327                 while (btstack_linked_list_iterator_has_next(&lit)){
3328                     whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3329                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3330                     btstack_memory_whitelist_entry_free(entry);
3331                 }
3332             }
3333 #endif
3334 #endif
3335             // close all open connections
3336             connection =  (hci_connection_t *) hci_stack->connections;
3337             if (connection){
3338                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
3339                 if (!hci_can_send_command_packet_now()) return;
3340 
3341                 // check state
3342                 if (connection->state == SENT_DISCONNECT) return;
3343                 connection->state = SENT_DISCONNECT;
3344 
3345                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
3346 
3347                 // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
3348                 hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
3349 
3350                 // ... which would be ignored anyway as we shutdown (free) the connection now
3351                 hci_shutdown_connection(connection);
3352 
3353                 // finally, send the disconnect command
3354                 hci_send_cmd(&hci_disconnect, con_handle, 0x13);  // remote closed connection
3355                 return;
3356             }
3357             log_info("HCI_STATE_HALTING, calling off");
3358 
3359             // switch mode
3360             hci_power_control_off();
3361 
3362             log_info("HCI_STATE_HALTING, emitting state");
3363             hci_emit_state();
3364             log_info("HCI_STATE_HALTING, done");
3365             break;
3366 
3367         case HCI_STATE_FALLING_ASLEEP:
3368             switch(hci_stack->substate) {
3369                 case HCI_FALLING_ASLEEP_DISCONNECT:
3370                     log_info("HCI_STATE_FALLING_ASLEEP");
3371                     // close all open connections
3372                     connection =  (hci_connection_t *) hci_stack->connections;
3373 
3374 #ifdef HAVE_PLATFORM_IPHONE_OS
3375                     // don't close connections, if H4 supports power management
3376                     if (btstack_control_iphone_power_management_enabled()){
3377                         connection = NULL;
3378                     }
3379 #endif
3380                     if (connection){
3381 
3382                         // send disconnect
3383                         if (!hci_can_send_command_packet_now()) return;
3384 
3385                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
3386                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
3387 
3388                         // send disconnected event right away - causes higher layer connections to get closed, too.
3389                         hci_shutdown_connection(connection);
3390                         return;
3391                     }
3392 
3393                     if (hci_classic_supported()){
3394                         // disable page and inquiry scan
3395                         if (!hci_can_send_command_packet_now()) return;
3396 
3397                         log_info("HCI_STATE_HALTING, disabling inq scans");
3398                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
3399 
3400                         // continue in next sub state
3401                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
3402                         break;
3403                     }
3404                     // no break - fall through for ble-only chips
3405 
3406                 case HCI_FALLING_ASLEEP_COMPLETE:
3407                     log_info("HCI_STATE_HALTING, calling sleep");
3408 #ifdef HAVE_PLATFORM_IPHONE_OS
3409                     // don't actually go to sleep, if H4 supports power management
3410                     if (btstack_control_iphone_power_management_enabled()){
3411                         // SLEEP MODE reached
3412                         hci_stack->state = HCI_STATE_SLEEPING;
3413                         hci_emit_state();
3414                         break;
3415                     }
3416 #endif
3417                     // switch mode
3418                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
3419                     hci_emit_state();
3420                     break;
3421 
3422                 default:
3423                     break;
3424             }
3425             break;
3426 
3427         default:
3428             break;
3429     }
3430 }
3431 
3432 int hci_send_cmd_packet(uint8_t *packet, int size){
3433     // house-keeping
3434 
3435     if (IS_COMMAND(packet, hci_write_loopback_mode)){
3436         hci_stack->loopback_mode = packet[3];
3437     }
3438 
3439 #ifdef ENABLE_CLASSIC
3440     bd_addr_t addr;
3441     hci_connection_t * conn;
3442 
3443     // create_connection?
3444     if (IS_COMMAND(packet, hci_create_connection)){
3445         reverse_bd_addr(&packet[3], addr);
3446         log_info("Create_connection to %s", bd_addr_to_str(addr));
3447 
3448         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3449         if (!conn){
3450             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3451             if (!conn){
3452                 // notify client that alloc failed
3453                 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3454                 return 0; // don't sent packet to controller
3455             }
3456             conn->state = SEND_CREATE_CONNECTION;
3457         }
3458         log_info("conn state %u", conn->state);
3459         switch (conn->state){
3460             // if connection active exists
3461             case OPEN:
3462                 // and OPEN, emit connection complete command, don't send to controller
3463                 hci_emit_connection_complete(addr, conn->con_handle, 0);
3464                 return 0;
3465             case SEND_CREATE_CONNECTION:
3466                 // connection created by hci, e.g. dedicated bonding
3467                 break;
3468             default:
3469                 // otherwise, just ignore as it is already in the open process
3470                 return 0;
3471         }
3472         conn->state = SENT_CREATE_CONNECTION;
3473     }
3474 
3475     if (IS_COMMAND(packet, hci_link_key_request_reply)){
3476         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
3477     }
3478     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
3479         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
3480     }
3481 
3482     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
3483         if (hci_stack->link_key_db){
3484             reverse_bd_addr(&packet[3], addr);
3485             hci_stack->link_key_db->delete_link_key(addr);
3486         }
3487     }
3488 
3489     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
3490     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
3491         reverse_bd_addr(&packet[3], addr);
3492         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3493         if (conn){
3494             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
3495         }
3496     }
3497 
3498     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
3499     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
3500     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
3501     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
3502         reverse_bd_addr(&packet[3], addr);
3503         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3504         if (conn){
3505             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
3506         }
3507     }
3508 
3509 #ifdef ENABLE_SCO_OVER_HCI
3510     // setup_synchronous_connection? Voice setting at offset 22
3511     if (IS_COMMAND(packet, hci_setup_synchronous_connection)){
3512         // TODO: compare to current setting if sco connection already active
3513         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
3514     }
3515     // accept_synchronus_connection? Voice setting at offset 18
3516     if (IS_COMMAND(packet, hci_accept_synchronous_connection)){
3517         // TODO: compare to current setting if sco connection already active
3518         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
3519     }
3520 #endif
3521 #endif
3522 
3523 #ifdef ENABLE_BLE
3524 #ifdef ENABLE_LE_PERIPHERAL
3525     if (IS_COMMAND(packet, hci_le_set_random_address)){
3526         hci_stack->le_random_address_set = 1;
3527         reverse_bd_addr(&packet[3], hci_stack->le_random_address);
3528     }
3529     if (IS_COMMAND(packet, hci_le_set_advertise_enable)){
3530         hci_stack->le_advertisements_active = packet[3];
3531     }
3532 #endif
3533 #ifdef ENABLE_LE_CENTRAL
3534     if (IS_COMMAND(packet, hci_le_create_connection)){
3535         // white list used?
3536         uint8_t initiator_filter_policy = packet[7];
3537         switch (initiator_filter_policy){
3538             case 0:
3539                 // whitelist not used
3540                 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
3541                 break;
3542             case 1:
3543                 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
3544                 break;
3545             default:
3546                 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
3547                 break;
3548         }
3549     }
3550     if (IS_COMMAND(packet, hci_le_create_connection_cancel)){
3551         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3552     }
3553 #endif
3554 #endif
3555 
3556     hci_stack->num_cmd_packets--;
3557 
3558     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3559     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3560 
3561     // release packet buffer for synchronous transport implementations
3562     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
3563         hci_stack->hci_packet_buffer_reserved = 0;
3564     }
3565 
3566     return err;
3567 }
3568 
3569 // disconnect because of security block
3570 void hci_disconnect_security_block(hci_con_handle_t con_handle){
3571     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3572     if (!connection) return;
3573     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3574 }
3575 
3576 
3577 // Configure Secure Simple Pairing
3578 
3579 #ifdef ENABLE_CLASSIC
3580 
3581 // enable will enable SSP during init
3582 void gap_ssp_set_enable(int enable){
3583     hci_stack->ssp_enable = enable;
3584 }
3585 
3586 static int hci_local_ssp_activated(void){
3587     return gap_ssp_supported() && hci_stack->ssp_enable;
3588 }
3589 
3590 // if set, BTstack will respond to io capability request using authentication requirement
3591 void gap_ssp_set_io_capability(int io_capability){
3592     hci_stack->ssp_io_capability = io_capability;
3593 }
3594 void gap_ssp_set_authentication_requirement(int authentication_requirement){
3595     hci_stack->ssp_authentication_requirement = authentication_requirement;
3596 }
3597 
3598 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
3599 void gap_ssp_set_auto_accept(int auto_accept){
3600     hci_stack->ssp_auto_accept = auto_accept;
3601 }
3602 #endif
3603 
3604 // va_list part of hci_send_cmd
3605 int hci_send_cmd_va_arg(const hci_cmd_t *cmd, va_list argptr){
3606     if (!hci_can_send_command_packet_now()){
3607         log_error("hci_send_cmd called but cannot send packet now");
3608         return 0;
3609     }
3610 
3611     // for HCI INITIALIZATION
3612     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
3613     hci_stack->last_cmd_opcode = cmd->opcode;
3614 
3615     hci_reserve_packet_buffer();
3616     uint8_t * packet = hci_stack->hci_packet_buffer;
3617     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
3618     return hci_send_cmd_packet(packet, size);
3619 }
3620 
3621 /**
3622  * pre: numcmds >= 0 - it's allowed to send a command to the controller
3623  */
3624 int hci_send_cmd(const hci_cmd_t *cmd, ...){
3625     va_list argptr;
3626     va_start(argptr, cmd);
3627     int res = hci_send_cmd_va_arg(cmd, argptr);
3628     va_end(argptr);
3629     return res;
3630 }
3631 
3632 // Create various non-HCI events.
3633 // TODO: generalize, use table similar to hci_create_command
3634 
3635 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
3636     // dump packet
3637     if (dump) {
3638         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
3639     }
3640 
3641     // dispatch to all event handlers
3642     btstack_linked_list_iterator_t it;
3643     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
3644     while (btstack_linked_list_iterator_has_next(&it)){
3645         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
3646         entry->callback(HCI_EVENT_PACKET, 0, event, size);
3647     }
3648 }
3649 
3650 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
3651     if (!hci_stack->acl_packet_handler) return;
3652     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
3653 }
3654 
3655 #ifdef ENABLE_CLASSIC
3656 static void hci_notify_if_sco_can_send_now(void){
3657     // notify SCO sender if waiting
3658     if (!hci_stack->sco_waiting_for_can_send_now) return;
3659     if (hci_can_send_sco_packet_now()){
3660         hci_stack->sco_waiting_for_can_send_now = 0;
3661         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
3662         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
3663         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
3664     }
3665 }
3666 
3667 // parsing end emitting has been merged to reduce code size
3668 static void gap_inquiry_explode(uint8_t * packet){
3669     uint8_t event[15+GAP_INQUIRY_MAX_NAME_LEN];
3670 
3671     uint8_t * eir_data;
3672     ad_context_t context;
3673     const uint8_t * name;
3674     uint8_t         name_len;
3675 
3676     int event_type = hci_event_packet_get_type(packet);
3677     int num_reserved_fields = event_type == HCI_EVENT_INQUIRY_RESULT ? 2 : 1;    // 2 for old event, 1 otherwise
3678     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
3679 
3680     // event[1] is set at the end
3681     int i;
3682     for (i=0; i<num_responses;i++){
3683         memset(event, 0, sizeof(event));
3684         event[0] = GAP_EVENT_INQUIRY_RESULT;
3685         uint8_t event_size = 18;    // if name is not set by EIR
3686 
3687         memcpy(&event[2],  &packet[3 +                                             i*6], 6); // bd_addr
3688         event[8] =          packet[3 + num_responses*(6)                         + i*1];     // page_scan_repetition_mode
3689         memcpy(&event[9],  &packet[3 + num_responses*(6+1+num_reserved_fields)   + i*3], 3); // class of device
3690         memcpy(&event[12], &packet[3 + num_responses*(6+1+num_reserved_fields+3) + i*2], 2); // clock offset
3691 
3692         switch (event_type){
3693             case HCI_EVENT_INQUIRY_RESULT:
3694                 // 14,15,16,17 = 0, size 18
3695                 break;
3696             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
3697                 event[14] = 1;
3698                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
3699                 // 16,17 = 0, size 18
3700                 break;
3701             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
3702                 event[14] = 1;
3703                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
3704                 // for EIR packets, there is only one reponse in it
3705                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
3706                 name = NULL;
3707                 // EIR data is 240 bytes in EIR event
3708                 for (ad_iterator_init(&context, 240, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
3709                     uint8_t data_type    = ad_iterator_get_data_type(&context);
3710                     uint8_t data_size    = ad_iterator_get_data_len(&context);
3711                     const uint8_t * data = ad_iterator_get_data(&context);
3712                     // Prefer Complete Local Name over Shortend Local Name
3713                     switch (data_type){
3714                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
3715                             if (name) continue;
3716                             /* explicit fall-through */
3717                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
3718                             name = data;
3719                             name_len = data_size;
3720                             break;
3721                         default:
3722                             break;
3723                     }
3724                 }
3725                 if (name){
3726                     event[16] = 1;
3727                     // truncate name if needed
3728                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
3729                     event[17] = len;
3730                     memcpy(&event[18], name, len);
3731                     event_size += len;
3732                 }
3733                 break;
3734         }
3735         event[1] = event_size - 2;
3736         hci_emit_event(event, event_size, 1);
3737     }
3738 }
3739 #endif
3740 
3741 void hci_emit_state(void){
3742     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
3743     uint8_t event[3];
3744     event[0] = BTSTACK_EVENT_STATE;
3745     event[1] = sizeof(event) - 2;
3746     event[2] = hci_stack->state;
3747     hci_emit_event(event, sizeof(event), 1);
3748 }
3749 
3750 #ifdef ENABLE_CLASSIC
3751 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3752     uint8_t event[13];
3753     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
3754     event[1] = sizeof(event) - 2;
3755     event[2] = status;
3756     little_endian_store_16(event, 3, con_handle);
3757     reverse_bd_addr(address, &event[5]);
3758     event[11] = 1; // ACL connection
3759     event[12] = 0; // encryption disabled
3760     hci_emit_event(event, sizeof(event), 1);
3761 }
3762 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
3763     if (disable_l2cap_timeouts) return;
3764     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
3765     uint8_t event[4];
3766     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
3767     event[1] = sizeof(event) - 2;
3768     little_endian_store_16(event, 2, conn->con_handle);
3769     hci_emit_event(event, sizeof(event), 1);
3770 }
3771 #endif
3772 
3773 #ifdef ENABLE_BLE
3774 #ifdef ENABLE_LE_CENTRAL
3775 static void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3776     uint8_t event[21];
3777     event[0] = HCI_EVENT_LE_META;
3778     event[1] = sizeof(event) - 2;
3779     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
3780     event[3] = status;
3781     little_endian_store_16(event, 4, con_handle);
3782     event[6] = 0; // TODO: role
3783     event[7] = address_type;
3784     reverse_bd_addr(address, &event[8]);
3785     little_endian_store_16(event, 14, 0); // interval
3786     little_endian_store_16(event, 16, 0); // latency
3787     little_endian_store_16(event, 18, 0); // supervision timeout
3788     event[20] = 0; // master clock accuracy
3789     hci_emit_event(event, sizeof(event), 1);
3790 }
3791 #endif
3792 #endif
3793 
3794 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
3795     uint8_t event[6];
3796     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
3797     event[1] = sizeof(event) - 2;
3798     event[2] = 0; // status = OK
3799     little_endian_store_16(event, 3, con_handle);
3800     event[5] = reason;
3801     hci_emit_event(event, sizeof(event), 1);
3802 }
3803 
3804 static void hci_emit_nr_connections_changed(void){
3805     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
3806     uint8_t event[3];
3807     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
3808     event[1] = sizeof(event) - 2;
3809     event[2] = nr_hci_connections();
3810     hci_emit_event(event, sizeof(event), 1);
3811 }
3812 
3813 static void hci_emit_hci_open_failed(void){
3814     log_info("BTSTACK_EVENT_POWERON_FAILED");
3815     uint8_t event[2];
3816     event[0] = BTSTACK_EVENT_POWERON_FAILED;
3817     event[1] = sizeof(event) - 2;
3818     hci_emit_event(event, sizeof(event), 1);
3819 }
3820 
3821 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
3822     log_info("hci_emit_dedicated_bonding_result %u ", status);
3823     uint8_t event[9];
3824     int pos = 0;
3825     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
3826     event[pos++] = sizeof(event) - 2;
3827     event[pos++] = status;
3828     reverse_bd_addr(address, &event[pos]);
3829     hci_emit_event(event, sizeof(event), 1);
3830 }
3831 
3832 
3833 #ifdef ENABLE_CLASSIC
3834 
3835 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
3836     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
3837     uint8_t event[5];
3838     int pos = 0;
3839     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
3840     event[pos++] = sizeof(event) - 2;
3841     little_endian_store_16(event, 2, con_handle);
3842     pos += 2;
3843     event[pos++] = level;
3844     hci_emit_event(event, sizeof(event), 1);
3845 }
3846 
3847 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
3848     if (!connection) return LEVEL_0;
3849     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
3850     return gap_security_level_for_link_key_type(connection->link_key_type);
3851 }
3852 
3853 static void hci_emit_discoverable_enabled(uint8_t enabled){
3854     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
3855     uint8_t event[3];
3856     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
3857     event[1] = sizeof(event) - 2;
3858     event[2] = enabled;
3859     hci_emit_event(event, sizeof(event), 1);
3860 }
3861 
3862 #ifdef ENABLE_CLASSIC
3863 // query if remote side supports eSCO
3864 int hci_remote_esco_supported(hci_con_handle_t con_handle){
3865     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3866     if (!connection) return 0;
3867     return connection->remote_supported_feature_eSCO;
3868 }
3869 
3870 // query if remote side supports SSP
3871 int hci_remote_ssp_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->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
3875 }
3876 
3877 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
3878     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
3879 }
3880 #endif
3881 
3882 // GAP API
3883 /**
3884  * @bbrief enable/disable bonding. default is enabled
3885  * @praram enabled
3886  */
3887 void gap_set_bondable_mode(int enable){
3888     hci_stack->bondable = enable ? 1 : 0;
3889 }
3890 /**
3891  * @brief Get bondable mode.
3892  * @return 1 if bondable
3893  */
3894 int gap_get_bondable_mode(void){
3895     return hci_stack->bondable;
3896 }
3897 
3898 /**
3899  * @brief map link keys to security levels
3900  */
3901 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
3902     switch (link_key_type){
3903         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
3904             return LEVEL_4;
3905         case COMBINATION_KEY:
3906         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
3907             return LEVEL_3;
3908         default:
3909             return LEVEL_2;
3910     }
3911 }
3912 
3913 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
3914     log_info("gap_mitm_protection_required_for_security_level %u", level);
3915     return level > LEVEL_2;
3916 }
3917 
3918 /**
3919  * @brief get current security level
3920  */
3921 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
3922     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3923     if (!connection) return LEVEL_0;
3924     return gap_security_level_for_connection(connection);
3925 }
3926 
3927 /**
3928  * @brief request connection to device to
3929  * @result GAP_AUTHENTICATION_RESULT
3930  */
3931 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
3932     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3933     if (!connection){
3934         hci_emit_security_level(con_handle, LEVEL_0);
3935         return;
3936     }
3937     gap_security_level_t current_level = gap_security_level(con_handle);
3938     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
3939     if (current_level >= requested_level){
3940         hci_emit_security_level(con_handle, current_level);
3941         return;
3942     }
3943 
3944     connection->requested_security_level = requested_level;
3945 
3946 #if 0
3947     // sending encryption request without a link key results in an error.
3948     // TODO: figure out how to use it properly
3949 
3950     // would enabling ecnryption suffice (>= LEVEL_2)?
3951     if (hci_stack->link_key_db){
3952         link_key_type_t link_key_type;
3953         link_key_t      link_key;
3954         if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){
3955             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
3956                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
3957                 return;
3958             }
3959         }
3960     }
3961 #endif
3962 
3963     // try to authenticate connection
3964     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
3965     hci_run();
3966 }
3967 
3968 /**
3969  * @brief start dedicated bonding with device. disconnect after bonding
3970  * @param device
3971  * @param request MITM protection
3972  * @result GAP_DEDICATED_BONDING_COMPLETE
3973  */
3974 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
3975 
3976     // create connection state machine
3977     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
3978 
3979     if (!connection){
3980         return BTSTACK_MEMORY_ALLOC_FAILED;
3981     }
3982 
3983     // delete linkn key
3984     gap_drop_link_key_for_bd_addr(device);
3985 
3986     // configure LEVEL_2/3, dedicated bonding
3987     connection->state = SEND_CREATE_CONNECTION;
3988     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
3989     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
3990     connection->bonding_flags = BONDING_DEDICATED;
3991 
3992     // wait for GAP Security Result and send GAP Dedicated Bonding complete
3993 
3994     // handle: connnection failure (connection complete != ok)
3995     // handle: authentication failure
3996     // handle: disconnect on done
3997 
3998     hci_run();
3999 
4000     return 0;
4001 }
4002 #endif
4003 
4004 void gap_set_local_name(const char * local_name){
4005     hci_stack->local_name = local_name;
4006 }
4007 
4008 
4009 #ifdef ENABLE_BLE
4010 
4011 #ifdef ENABLE_LE_CENTRAL
4012 void gap_start_scan(void){
4013     hci_stack->le_scanning_enabled = 1;
4014     hci_run();
4015 }
4016 
4017 void gap_stop_scan(void){
4018     hci_stack->le_scanning_enabled = 0;
4019     hci_run();
4020 }
4021 
4022 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
4023     hci_stack->le_scan_type     = scan_type;
4024     hci_stack->le_scan_interval = scan_interval;
4025     hci_stack->le_scan_window   = scan_window;
4026     hci_run();
4027 }
4028 
4029 uint8_t gap_connect(bd_addr_t addr, bd_addr_type_t addr_type){
4030     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
4031     if (!conn){
4032         log_info("gap_connect: no connection exists yet, creating context");
4033         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
4034         if (!conn){
4035             // notify client that alloc failed
4036             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
4037             log_info("gap_connect: failed to alloc hci_connection_t");
4038             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
4039         }
4040         conn->state = SEND_CREATE_CONNECTION;
4041         log_info("gap_connect: send create connection next");
4042         hci_run();
4043         return 0;
4044     }
4045 
4046     if (!hci_is_le_connection(conn) ||
4047         conn->state == SEND_CREATE_CONNECTION ||
4048         conn->state == SENT_CREATE_CONNECTION) {
4049         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
4050         log_error("gap_connect: classic connection or connect is already being created");
4051         return GATT_CLIENT_IN_WRONG_STATE;
4052     }
4053 
4054     log_info("gap_connect: context exists with state %u", conn->state);
4055     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0);
4056     hci_run();
4057     return 0;
4058 }
4059 
4060 // @assumption: only a single outgoing LE Connection exists
4061 static hci_connection_t * gap_get_outgoing_connection(void){
4062     btstack_linked_item_t *it;
4063     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
4064         hci_connection_t * conn = (hci_connection_t *) it;
4065         if (!hci_is_le_connection(conn)) continue;
4066         switch (conn->state){
4067             case SEND_CREATE_CONNECTION:
4068             case SENT_CREATE_CONNECTION:
4069             case SENT_CANCEL_CONNECTION:
4070                 return conn;
4071             default:
4072                 break;
4073         };
4074     }
4075     return NULL;
4076 }
4077 
4078 uint8_t gap_connect_cancel(void){
4079     hci_connection_t * conn = gap_get_outgoing_connection();
4080     if (!conn) return 0;
4081     switch (conn->state){
4082         case SEND_CREATE_CONNECTION:
4083             // skip sending create connection and emit event instead
4084             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
4085             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
4086             btstack_memory_hci_connection_free( conn );
4087             break;
4088         case SENT_CREATE_CONNECTION:
4089             // request to send cancel connection
4090             conn->state = SEND_CANCEL_CONNECTION;
4091             hci_run();
4092             break;
4093         default:
4094             break;
4095     }
4096     return 0;
4097 }
4098 #endif
4099 
4100 #ifdef ENABLE_LE_CENTRAL
4101 /**
4102  * @brief Set connection parameters for outgoing connections
4103  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
4104  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
4105  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
4106  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
4107  * @param conn_latency, default: 4
4108  * @param supervision_timeout (unit: 10ms), default: 720 ms
4109  * @param min_ce_length (unit: 0.625ms), default: 10 ms
4110  * @param max_ce_length (unit: 0.625ms), default: 30 ms
4111  */
4112 
4113 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
4114     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
4115     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
4116     hci_stack->le_connection_scan_interval = conn_scan_interval;
4117     hci_stack->le_connection_scan_window = conn_scan_window;
4118     hci_stack->le_connection_interval_min = conn_interval_min;
4119     hci_stack->le_connection_interval_max = conn_interval_max;
4120     hci_stack->le_connection_latency = conn_latency;
4121     hci_stack->le_supervision_timeout = supervision_timeout;
4122     hci_stack->le_minimum_ce_length = min_ce_length;
4123     hci_stack->le_maximum_ce_length = max_ce_length;
4124 }
4125 #endif
4126 
4127 /**
4128  * @brief Updates the connection parameters for a given LE connection
4129  * @param handle
4130  * @param conn_interval_min (unit: 1.25ms)
4131  * @param conn_interval_max (unit: 1.25ms)
4132  * @param conn_latency
4133  * @param supervision_timeout (unit: 10ms)
4134  * @returns 0 if ok
4135  */
4136 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4137     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4138     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4139     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4140     connection->le_conn_interval_min = conn_interval_min;
4141     connection->le_conn_interval_max = conn_interval_max;
4142     connection->le_conn_latency = conn_latency;
4143     connection->le_supervision_timeout = supervision_timeout;
4144     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
4145     hci_run();
4146     return 0;
4147 }
4148 
4149 /**
4150  * @brief Request an update of the connection parameter for a given LE connection
4151  * @param handle
4152  * @param conn_interval_min (unit: 1.25ms)
4153  * @param conn_interval_max (unit: 1.25ms)
4154  * @param conn_latency
4155  * @param supervision_timeout (unit: 10ms)
4156  * @returns 0 if ok
4157  */
4158 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4159     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4160     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4161     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4162     connection->le_conn_interval_min = conn_interval_min;
4163     connection->le_conn_interval_max = conn_interval_max;
4164     connection->le_conn_latency = conn_latency;
4165     connection->le_supervision_timeout = supervision_timeout;
4166     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
4167     hci_run();
4168     return 0;
4169 }
4170 
4171 #ifdef ENABLE_LE_PERIPHERAL
4172 
4173 static void gap_advertisments_changed(void){
4174     // disable advertisements before updating adv, scan data, or adv params
4175     if (hci_stack->le_advertisements_active){
4176         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
4177     }
4178     hci_run();
4179 }
4180 
4181 /**
4182  * @brief Set Advertisement Data
4183  * @param advertising_data_length
4184  * @param advertising_data (max 31 octets)
4185  * @note data is not copied, pointer has to stay valid
4186  */
4187 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
4188     hci_stack->le_advertisements_data_len = advertising_data_length;
4189     hci_stack->le_advertisements_data = advertising_data;
4190     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4191     gap_advertisments_changed();
4192 }
4193 
4194 /**
4195  * @brief Set Scan Response Data
4196  * @param advertising_data_length
4197  * @param advertising_data (max 31 octets)
4198  * @note data is not copied, pointer has to stay valid
4199  */
4200 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
4201     hci_stack->le_scan_response_data_len = scan_response_data_length;
4202     hci_stack->le_scan_response_data = scan_response_data;
4203     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
4204     gap_advertisments_changed();
4205 }
4206 
4207 /**
4208  * @brief Set Advertisement Parameters
4209  * @param adv_int_min
4210  * @param adv_int_max
4211  * @param adv_type
4212  * @param direct_address_type
4213  * @param direct_address
4214  * @param channel_map
4215  * @param filter_policy
4216  *
4217  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
4218  */
4219  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
4220     uint8_t direct_address_typ, bd_addr_t direct_address,
4221     uint8_t channel_map, uint8_t filter_policy) {
4222 
4223     hci_stack->le_advertisements_interval_min = adv_int_min;
4224     hci_stack->le_advertisements_interval_max = adv_int_max;
4225     hci_stack->le_advertisements_type = adv_type;
4226     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
4227     hci_stack->le_advertisements_channel_map = channel_map;
4228     hci_stack->le_advertisements_filter_policy = filter_policy;
4229     memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6);
4230 
4231     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4232     gap_advertisments_changed();
4233  }
4234 
4235 /**
4236  * @brief Enable/Disable Advertisements
4237  * @param enabled
4238  */
4239 void gap_advertisements_enable(int enabled){
4240     hci_stack->le_advertisements_enabled = enabled;
4241     if (enabled && !hci_stack->le_advertisements_active){
4242         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
4243     }
4244     if (!enabled && hci_stack->le_advertisements_active){
4245         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE;
4246     }
4247     hci_run();
4248 }
4249 
4250 #endif
4251 
4252 void hci_le_set_own_address_type(uint8_t own_address_type){
4253     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
4254     if (own_address_type == hci_stack->le_own_addr_type) return;
4255     hci_stack->le_own_addr_type = own_address_type;
4256 
4257 #ifdef ENABLE_LE_PERIPHERAL
4258     // update advertisement parameters, too
4259     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4260     gap_advertisments_changed();
4261 #endif
4262 #ifdef ENABLE_LE_CENTRAL
4263     // note: we don't update scan parameters or modify ongoing connection attempts
4264 #endif
4265 }
4266 
4267 #endif
4268 
4269 uint8_t gap_disconnect(hci_con_handle_t handle){
4270     hci_connection_t * conn = hci_connection_for_handle(handle);
4271     if (!conn){
4272         hci_emit_disconnection_complete(handle, 0);
4273         return 0;
4274     }
4275     conn->state = SEND_DISCONNECT;
4276     hci_run();
4277     return 0;
4278 }
4279 
4280 /**
4281  * @brief Get connection type
4282  * @param con_handle
4283  * @result connection_type
4284  */
4285 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
4286     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4287     if (!conn) return GAP_CONNECTION_INVALID;
4288     switch (conn->address_type){
4289         case BD_ADDR_TYPE_LE_PUBLIC:
4290         case BD_ADDR_TYPE_LE_RANDOM:
4291             return GAP_CONNECTION_LE;
4292         case BD_ADDR_TYPE_SCO:
4293             return GAP_CONNECTION_SCO;
4294         case BD_ADDR_TYPE_CLASSIC:
4295             return GAP_CONNECTION_ACL;
4296         default:
4297             return GAP_CONNECTION_INVALID;
4298     }
4299 }
4300 
4301 #ifdef ENABLE_BLE
4302 
4303 #ifdef ENABLE_LE_CENTRAL
4304 /**
4305  * @brief Auto Connection Establishment - Start Connecting to device
4306  * @param address_typ
4307  * @param address
4308  * @returns 0 if ok
4309  */
4310 int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){
4311     // check capacity
4312     int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist);
4313     if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
4314     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
4315     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
4316     entry->address_type = address_type;
4317     memcpy(entry->address, address, 6);
4318     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
4319     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
4320     hci_run();
4321     return 0;
4322 }
4323 
4324 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){
4325     btstack_linked_list_iterator_t it;
4326     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4327     while (btstack_linked_list_iterator_has_next(&it)){
4328         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4329         if (entry->address_type != address_type) continue;
4330         if (memcmp(entry->address, address, 6) != 0) continue;
4331         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4332             // remove from controller if already present
4333             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4334             continue;
4335         }
4336         // direclty remove entry from whitelist
4337         btstack_linked_list_iterator_remove(&it);
4338         btstack_memory_whitelist_entry_free(entry);
4339     }
4340 }
4341 
4342 /**
4343  * @brief Auto Connection Establishment - Stop Connecting to device
4344  * @param address_typ
4345  * @param address
4346  * @returns 0 if ok
4347  */
4348 int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){
4349     hci_remove_from_whitelist(address_type, address);
4350     hci_run();
4351     return 0;
4352 }
4353 
4354 /**
4355  * @brief Auto Connection Establishment - Stop everything
4356  * @note  Convenience function to stop all active auto connection attempts
4357  */
4358 void gap_auto_connection_stop_all(void){
4359     btstack_linked_list_iterator_t it;
4360     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4361     while (btstack_linked_list_iterator_has_next(&it)){
4362         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4363         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4364             // remove from controller if already present
4365             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4366             continue;
4367         }
4368         // directly remove entry from whitelist
4369         btstack_linked_list_iterator_remove(&it);
4370         btstack_memory_whitelist_entry_free(entry);
4371     }
4372     hci_run();
4373 }
4374 #endif
4375 #endif
4376 
4377 #ifdef ENABLE_CLASSIC
4378 /**
4379  * @brief Set Extended Inquiry Response data
4380  * @param eir_data size 240 bytes, is not copied make sure memory is accessible during stack startup
4381  * @note has to be done before stack starts up
4382  */
4383 void gap_set_extended_inquiry_response(const uint8_t * data){
4384     hci_stack->eir_data = data;
4385 }
4386 
4387 /**
4388  * @brief Start GAP Classic Inquiry
4389  * @param duration in 1.28s units
4390  * @return 0 if ok
4391  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
4392  */
4393 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
4394     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4395     if (duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN || duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX){
4396         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
4397     }
4398     hci_stack->inquiry_state = duration_in_1280ms_units;
4399     hci_run();
4400     return 0;
4401 }
4402 
4403 /**
4404  * @brief Stop GAP Classic Inquiry
4405  * @returns 0 if ok
4406  */
4407 int gap_inquiry_stop(void){
4408     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN || hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX) {
4409         // emit inquiry complete event, before it even started
4410         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
4411         hci_emit_event(event, sizeof(event), 1);
4412         return 0;
4413     }
4414     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
4415     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
4416     hci_run();
4417     return 0;
4418 }
4419 
4420 
4421 /**
4422  * @brief Remote Name Request
4423  * @param addr
4424  * @param page_scan_repetition_mode
4425  * @param clock_offset only used when bit 15 is set
4426  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
4427  */
4428 int gap_remote_name_request(bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
4429     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4430     memcpy(hci_stack->remote_name_addr, addr, 6);
4431     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
4432     hci_stack->remote_name_clock_offset = clock_offset;
4433     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
4434     hci_run();
4435     return 0;
4436 }
4437 
4438 static int gap_pairing_set_state_and_run(bd_addr_t addr, uint8_t state){
4439     hci_stack->gap_pairing_state = state;
4440     memcpy(hci_stack->gap_pairing_addr, addr, 6);
4441     hci_run();
4442     return 0;
4443 }
4444 
4445 /**
4446  * @brief Legacy Pairing Pin Code Response
4447  * @param addr
4448  * @param pin
4449  * @return 0 if ok
4450  */
4451 int gap_pin_code_response(bd_addr_t addr, const char * pin){
4452     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4453     hci_stack->gap_pairing_pin = pin;
4454     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
4455 }
4456 
4457 /**
4458  * @brief Abort Legacy Pairing
4459  * @param addr
4460  * @param pin
4461  * @return 0 if ok
4462  */
4463 int gap_pin_code_negative(bd_addr_t addr){
4464     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4465     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
4466 }
4467 
4468 /**
4469  * @brief SSP Passkey Response
4470  * @param addr
4471  * @param passkey
4472  * @return 0 if ok
4473  */
4474 int gap_ssp_passkey_response(bd_addr_t addr, uint32_t passkey){
4475     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4476     hci_stack->gap_pairing_passkey = passkey;
4477     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
4478 }
4479 
4480 /**
4481  * @brief Abort SSP Passkey Entry/Pairing
4482  * @param addr
4483  * @param pin
4484  * @return 0 if ok
4485  */
4486 int gap_ssp_passkey_negative(bd_addr_t addr){
4487     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4488     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
4489 }
4490 
4491 /**
4492  * @brief Accept SSP Numeric Comparison
4493  * @param addr
4494  * @param passkey
4495  * @return 0 if ok
4496  */
4497 int gap_ssp_confirmation_response(bd_addr_t addr){
4498     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4499     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
4500 }
4501 
4502 /**
4503  * @brief Abort SSP Numeric Comparison/Pairing
4504  * @param addr
4505  * @param pin
4506  * @return 0 if ok
4507  */
4508 int gap_ssp_confirmation_negative(bd_addr_t addr){
4509     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4510     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
4511 }
4512 
4513 /**
4514  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
4515  * @param inquiry_mode see bluetooth_defines.h
4516  */
4517 void hci_set_inquiry_mode(inquiry_mode_t mode){
4518     hci_stack->inquiry_mode = mode;
4519 }
4520 
4521 /**
4522  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
4523  */
4524 void hci_set_sco_voice_setting(uint16_t voice_setting){
4525     hci_stack->sco_voice_setting = voice_setting;
4526 }
4527 
4528 /**
4529  * @brief Get SCO Voice Setting
4530  * @return current voice setting
4531  */
4532 uint16_t hci_get_sco_voice_setting(void){
4533     return hci_stack->sco_voice_setting;
4534 }
4535 
4536 /** @brief Get SCO packet length for current SCO Voice setting
4537  *  @note  Using SCO packets of the exact length is required for USB transfer
4538  *  @return Length of SCO packets in bytes (not audio frames)
4539  */
4540 int hci_get_sco_packet_length(void){
4541     // see Core Spec for H2 USB Transfer.
4542     if (hci_stack->sco_voice_setting & 0x0020) return 51;
4543     return 27;
4544 }
4545 
4546 /**
4547 * @brief Sets the master/slave policy
4548 * @param policy (0: attempt to become master, 1: let connecting device decide)
4549 */
4550 void hci_set_master_slave_policy(uint8_t policy){
4551     hci_stack->master_slave_policy = policy;
4552 }
4553 
4554 #endif
4555 
4556 HCI_STATE hci_get_state(void){
4557     return hci_stack->state;
4558 }
4559 
4560 
4561 /**
4562  * @brief Set callback for Bluetooth Hardware Error
4563  */
4564 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
4565     hci_stack->hardware_error_callback = fn;
4566 }
4567 
4568 void hci_disconnect_all(void){
4569     btstack_linked_list_iterator_t it;
4570     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
4571     while (btstack_linked_list_iterator_has_next(&it)){
4572         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
4573         if (con->state == SENT_DISCONNECT) continue;
4574         con->state = SEND_DISCONNECT;
4575     }
4576     hci_run();
4577 }
4578 
4579 uint16_t hci_get_manufacturer(void){
4580     return hci_stack->manufacturer;
4581 }
4582 
4583 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4584     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
4585     if (!hci_con) return NULL;
4586     return &hci_con->sm_connection;
4587 }
4588 
4589 #ifdef ENABLE_BLE
4590 
4591 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
4592 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
4593 
4594 int gap_encryption_key_size(hci_con_handle_t con_handle){
4595     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4596     if (!sm_conn) return 0;     // wrong connection
4597     if (!sm_conn->sm_connection_encrypted) return 0;
4598     return sm_conn->sm_actual_encryption_key_size;
4599 }
4600 
4601 int gap_authenticated(hci_con_handle_t con_handle){
4602     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4603     if (!sm_conn) return 0;     // wrong connection
4604     if (!sm_conn->sm_connection_encrypted) return 0; // unencrypted connection cannot be authenticated
4605     return sm_conn->sm_connection_authenticated;
4606 }
4607 
4608 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
4609     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4610     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
4611     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
4612     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
4613     return sm_conn->sm_connection_authorization_state;
4614 }
4615 #endif
4616