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