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