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