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