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