xref: /btstack/src/hci.c (revision 6f28d2ee268a9002ddd66f24f1645a8e73473ae1)
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 = 0;
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 6
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     // trigger send
2545     conn->sco_tx_count++;
2546     conn->sco_tx_ready = 1;
2547     hci_notify_if_sco_can_send_now();
2548 
2549     // schedule next
2550     sco_schedule_tx(conn);
2551 }
2552 
2553 static void sco_schedule_tx(hci_connection_t * conn){
2554     // find next time to send
2555     uint32_t now = btstack_run_loop_get_time_ms();
2556     uint32_t tx_ms;
2557     int time_delta_ms;
2558     while (1){
2559         // packet delay: count(rx) - count(tx)
2560         int packet_offset = (int8_t) (conn->sco_tx_count - conn->sco_rx_count);
2561         tx_ms = conn->sco_rx_ms + ((packet_offset * 15) >> 1) + SCO_TX_AFTER_RX_MS;
2562         time_delta_ms = (int) (tx_ms - now);
2563         if (time_delta_ms > 3){    // arbitrary threshold
2564             break;
2565         }
2566         // skip packet
2567         conn->sco_tx_count++;
2568     }
2569     //
2570     log_info("SCO TX at %u in %u", (int) tx_ms, time_delta_ms);
2571     btstack_run_loop_set_timer(&conn->timeout, time_delta_ms);
2572     btstack_run_loop_set_timer_context(&conn->timeout, (void *) (uintptr_t) conn->con_handle);
2573     btstack_run_loop_set_timer_handler(&conn->timeout, &sco_tx_timeout_handler);
2574     btstack_run_loop_add_timer(&conn->timeout);
2575 }
2576 
2577 static void sco_handler(uint8_t * packet, uint16_t size){
2578     // lookup connection struct
2579     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
2580     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
2581     if (!conn) return;
2582 
2583     int notify_sco = 0;
2584 
2585     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
2586     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
2587         if (size == 83 && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
2588             packet[2] = 0x3c;
2589             memmove(&packet[3], &packet[23], 63);
2590             size = 63;
2591         }
2592     }
2593 
2594     // 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);
2595     if (hci_stack->synchronous_flow_control_enabled == 0){
2596         uint32_t now = btstack_run_loop_get_time_ms();
2597         if (conn->sco_rx_valid){
2598             conn->sco_rx_count++;
2599             // expected arrival timme
2600             conn->sco_rx_ms += 8;
2601             int delta = (int) (now - conn->sco_rx_ms);
2602             if (delta < 0){
2603                 log_info("SCO NOW < EXP, use new value");
2604                 conn->sco_rx_ms = now;
2605             } else if (delta == 0){
2606                 log_info("SCO NOW = EXP");
2607             } else {
2608                 log_info("SCO NOW > EXP");
2609             }
2610         } else {
2611             // use first timestamp as is
2612             conn->sco_rx_ms = now;
2613             conn->sco_rx_valid = 1;
2614             log_info("SCO first rx");
2615             sco_schedule_tx(conn);
2616         }
2617     }
2618 
2619     // deliver to app
2620     if (hci_stack->sco_packet_handler) {
2621         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
2622     }
2623 
2624     // notify app if it can send again
2625     if (notify_sco){
2626         hci_notify_if_sco_can_send_now();
2627     }
2628 
2629 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2630     conn->num_packets_completed++;
2631     hci_stack->host_completed_packets = 1;
2632     hci_run();
2633 #endif
2634 }
2635 #endif
2636 
2637 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
2638     hci_dump_packet(packet_type, 1, packet, size);
2639     switch (packet_type) {
2640         case HCI_EVENT_PACKET:
2641             event_handler(packet, size);
2642             break;
2643         case HCI_ACL_DATA_PACKET:
2644             acl_handler(packet, size);
2645             break;
2646 #ifdef ENABLE_CLASSIC
2647         case HCI_SCO_DATA_PACKET:
2648             sco_handler(packet, size);
2649             break;
2650 #endif
2651         default:
2652             break;
2653     }
2654 }
2655 
2656 /**
2657  * @brief Add event packet handler.
2658  */
2659 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
2660     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
2661 }
2662 
2663 
2664 /** Register HCI packet handlers */
2665 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
2666     hci_stack->acl_packet_handler = handler;
2667 }
2668 
2669 #ifdef ENABLE_CLASSIC
2670 /**
2671  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
2672  */
2673 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
2674     hci_stack->sco_packet_handler = handler;
2675 }
2676 #endif
2677 
2678 static void hci_state_reset(void){
2679     // no connections yet
2680     hci_stack->connections = NULL;
2681 
2682     // keep discoverable/connectable as this has been requested by the client(s)
2683     // hci_stack->discoverable = 0;
2684     // hci_stack->connectable = 0;
2685     // hci_stack->bondable = 1;
2686     // hci_stack->own_addr_type = 0;
2687 
2688     // buffer is free
2689     hci_stack->hci_packet_buffer_reserved = 0;
2690 
2691     // no pending cmds
2692     hci_stack->decline_reason = 0;
2693     hci_stack->new_scan_enable_value = 0xff;
2694 
2695     // LE
2696 #ifdef ENABLE_BLE
2697     memset(hci_stack->le_random_address, 0, 6);
2698     hci_stack->le_random_address_set = 0;
2699 #endif
2700 #ifdef ENABLE_LE_CENTRAL
2701     hci_stack->le_scanning_active  = 0;
2702     hci_stack->le_scan_type = 0xff;
2703     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2704     hci_stack->le_whitelist = 0;
2705     hci_stack->le_whitelist_capacity = 0;
2706 #endif
2707 }
2708 
2709 #ifdef ENABLE_CLASSIC
2710 /**
2711  * @brief Configure Bluetooth hardware control. Has to be called before power on.
2712  */
2713 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
2714     // store and open remote device db
2715     hci_stack->link_key_db = link_key_db;
2716     if (hci_stack->link_key_db) {
2717         hci_stack->link_key_db->open();
2718     }
2719 }
2720 #endif
2721 
2722 void hci_init(const hci_transport_t *transport, const void *config){
2723 
2724 #ifdef HAVE_MALLOC
2725     if (!hci_stack) {
2726         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
2727     }
2728 #else
2729     hci_stack = &hci_stack_static;
2730 #endif
2731     memset(hci_stack, 0, sizeof(hci_stack_t));
2732 
2733     // reference to use transport layer implementation
2734     hci_stack->hci_transport = transport;
2735 
2736     // reference to used config
2737     hci_stack->config = config;
2738 
2739     // setup pointer for outgoing packet buffer
2740     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
2741 
2742     // max acl payload size defined in config.h
2743     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
2744 
2745     // register packet handlers with transport
2746     transport->register_packet_handler(&packet_handler);
2747 
2748     hci_stack->state = HCI_STATE_OFF;
2749 
2750     // class of device
2751     hci_stack->class_of_device = 0x007a020c; // Smartphone
2752 
2753     // bondable by default
2754     hci_stack->bondable = 1;
2755 
2756 #ifdef ENABLE_CLASSIC
2757     // classic name
2758     hci_stack->local_name = default_classic_name;
2759 
2760     // Master slave policy
2761     hci_stack->master_slave_policy = 1;
2762 #endif
2763 
2764     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
2765     hci_stack->ssp_enable = 1;
2766     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
2767     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
2768     hci_stack->ssp_auto_accept = 1;
2769 
2770     // voice setting - signed 16 bit pcm data with CVSD over the air
2771     hci_stack->sco_voice_setting = 0x60;
2772 
2773 #ifdef ENABLE_LE_CENTRAL
2774     // connection parameter to use for outgoing connections
2775     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
2776     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
2777     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
2778     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
2779     hci_stack->le_connection_latency      = 4;         // 4
2780     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
2781     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
2782     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
2783 #endif
2784 
2785 #ifdef ENABLE_LE_PERIPHERAL
2786     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
2787 #endif
2788 
2789     // connection parameter range used to answer connection parameter update requests in l2cap
2790     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
2791     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
2792     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
2793     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
2794     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
2795     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
2796 
2797     hci_state_reset();
2798 }
2799 
2800 /**
2801  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
2802  */
2803 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
2804     hci_stack->chipset = chipset_driver;
2805 
2806     // reset chipset driver - init is also called on power_up
2807     if (hci_stack->chipset && hci_stack->chipset->init){
2808         hci_stack->chipset->init(hci_stack->config);
2809     }
2810 }
2811 
2812 /**
2813  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
2814  */
2815 void hci_set_control(const btstack_control_t *hardware_control){
2816     // references to used control implementation
2817     hci_stack->control = hardware_control;
2818     // init with transport config
2819     hardware_control->init(hci_stack->config);
2820 }
2821 
2822 void hci_close(void){
2823     // close remote device db
2824     if (hci_stack->link_key_db) {
2825         hci_stack->link_key_db->close();
2826     }
2827 
2828     btstack_linked_list_iterator_t lit;
2829     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
2830     while (btstack_linked_list_iterator_has_next(&lit)){
2831         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
2832         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
2833         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
2834         hci_shutdown_connection(connection);
2835     }
2836 
2837     hci_power_control(HCI_POWER_OFF);
2838 
2839 #ifdef HAVE_MALLOC
2840     free(hci_stack);
2841 #endif
2842     hci_stack = NULL;
2843 }
2844 
2845 #ifdef ENABLE_CLASSIC
2846 void gap_set_class_of_device(uint32_t class_of_device){
2847     hci_stack->class_of_device = class_of_device;
2848 }
2849 
2850 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
2851     hci_stack->default_link_policy_settings = default_link_policy_settings;
2852 }
2853 
2854 void hci_disable_l2cap_timeout_check(void){
2855     disable_l2cap_timeouts = 1;
2856 }
2857 #endif
2858 
2859 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
2860 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
2861 void hci_set_bd_addr(bd_addr_t addr){
2862     memcpy(hci_stack->custom_bd_addr, addr, 6);
2863     hci_stack->custom_bd_addr_set = 1;
2864 }
2865 #endif
2866 
2867 // State-Module-Driver overview
2868 // state                    module  low-level
2869 // HCI_STATE_OFF             off      close
2870 // HCI_STATE_INITIALIZING,   on       open
2871 // HCI_STATE_WORKING,        on       open
2872 // HCI_STATE_HALTING,        on       open
2873 // HCI_STATE_SLEEPING,    off/sleep   close
2874 // HCI_STATE_FALLING_ASLEEP  on       open
2875 
2876 static int hci_power_control_on(void){
2877 
2878     // power on
2879     int err = 0;
2880     if (hci_stack->control && hci_stack->control->on){
2881         err = (*hci_stack->control->on)();
2882     }
2883     if (err){
2884         log_error( "POWER_ON failed");
2885         hci_emit_hci_open_failed();
2886         return err;
2887     }
2888 
2889     // int chipset driver
2890     if (hci_stack->chipset && hci_stack->chipset->init){
2891         hci_stack->chipset->init(hci_stack->config);
2892     }
2893 
2894     // init transport
2895     if (hci_stack->hci_transport->init){
2896         hci_stack->hci_transport->init(hci_stack->config);
2897     }
2898 
2899     // open transport
2900     err = hci_stack->hci_transport->open();
2901     if (err){
2902         log_error( "HCI_INIT failed, turning Bluetooth off again");
2903         if (hci_stack->control && hci_stack->control->off){
2904             (*hci_stack->control->off)();
2905         }
2906         hci_emit_hci_open_failed();
2907         return err;
2908     }
2909     return 0;
2910 }
2911 
2912 static void hci_power_control_off(void){
2913 
2914     log_info("hci_power_control_off");
2915 
2916     // close low-level device
2917     hci_stack->hci_transport->close();
2918 
2919     log_info("hci_power_control_off - hci_transport closed");
2920 
2921     // power off
2922     if (hci_stack->control && hci_stack->control->off){
2923         (*hci_stack->control->off)();
2924     }
2925 
2926     log_info("hci_power_control_off - control closed");
2927 
2928     hci_stack->state = HCI_STATE_OFF;
2929 }
2930 
2931 static void hci_power_control_sleep(void){
2932 
2933     log_info("hci_power_control_sleep");
2934 
2935 #if 0
2936     // don't close serial port during sleep
2937 
2938     // close low-level device
2939     hci_stack->hci_transport->close(hci_stack->config);
2940 #endif
2941 
2942     // sleep mode
2943     if (hci_stack->control && hci_stack->control->sleep){
2944         (*hci_stack->control->sleep)();
2945     }
2946 
2947     hci_stack->state = HCI_STATE_SLEEPING;
2948 }
2949 
2950 static int hci_power_control_wake(void){
2951 
2952     log_info("hci_power_control_wake");
2953 
2954     // wake on
2955     if (hci_stack->control && hci_stack->control->wake){
2956         (*hci_stack->control->wake)();
2957     }
2958 
2959 #if 0
2960     // open low-level device
2961     int err = hci_stack->hci_transport->open(hci_stack->config);
2962     if (err){
2963         log_error( "HCI_INIT failed, turning Bluetooth off again");
2964         if (hci_stack->control && hci_stack->control->off){
2965             (*hci_stack->control->off)();
2966         }
2967         hci_emit_hci_open_failed();
2968         return err;
2969     }
2970 #endif
2971 
2972     return 0;
2973 }
2974 
2975 static void hci_power_transition_to_initializing(void){
2976     // set up state machine
2977     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
2978     hci_stack->hci_packet_buffer_reserved = 0;
2979     hci_stack->state = HCI_STATE_INITIALIZING;
2980     hci_stack->substate = HCI_INIT_SEND_RESET;
2981 }
2982 
2983 int hci_power_control(HCI_POWER_MODE power_mode){
2984 
2985     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
2986 
2987     int err = 0;
2988     switch (hci_stack->state){
2989 
2990         case HCI_STATE_OFF:
2991             switch (power_mode){
2992                 case HCI_POWER_ON:
2993                     err = hci_power_control_on();
2994                     if (err) {
2995                         log_error("hci_power_control_on() error %d", err);
2996                         return err;
2997                     }
2998                     hci_power_transition_to_initializing();
2999                     break;
3000                 case HCI_POWER_OFF:
3001                     // do nothing
3002                     break;
3003                 case HCI_POWER_SLEEP:
3004                     // do nothing (with SLEEP == OFF)
3005                     break;
3006             }
3007             break;
3008 
3009         case HCI_STATE_INITIALIZING:
3010             switch (power_mode){
3011                 case HCI_POWER_ON:
3012                     // do nothing
3013                     break;
3014                 case HCI_POWER_OFF:
3015                     // no connections yet, just turn it off
3016                     hci_power_control_off();
3017                     break;
3018                 case HCI_POWER_SLEEP:
3019                     // no connections yet, just turn it off
3020                     hci_power_control_sleep();
3021                     break;
3022             }
3023             break;
3024 
3025         case HCI_STATE_WORKING:
3026             switch (power_mode){
3027                 case HCI_POWER_ON:
3028                     // do nothing
3029                     break;
3030                 case HCI_POWER_OFF:
3031                     // see hci_run
3032                     hci_stack->state = HCI_STATE_HALTING;
3033                     hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3034                     break;
3035                 case HCI_POWER_SLEEP:
3036                     // see hci_run
3037                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
3038                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
3039                     break;
3040             }
3041             break;
3042 
3043         case HCI_STATE_HALTING:
3044             switch (power_mode){
3045                 case HCI_POWER_ON:
3046                     hci_power_transition_to_initializing();
3047                     break;
3048                 case HCI_POWER_OFF:
3049                     // do nothing
3050                     break;
3051                 case HCI_POWER_SLEEP:
3052                     // see hci_run
3053                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
3054                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
3055                     break;
3056             }
3057             break;
3058 
3059         case HCI_STATE_FALLING_ASLEEP:
3060             switch (power_mode){
3061                 case HCI_POWER_ON:
3062 
3063 #ifdef HAVE_PLATFORM_IPHONE_OS
3064                     // nothing to do, if H4 supports power management
3065                     if (btstack_control_iphone_power_management_enabled()){
3066                         hci_stack->state = HCI_STATE_INITIALIZING;
3067                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
3068                         break;
3069                     }
3070 #endif
3071                     hci_power_transition_to_initializing();
3072                     break;
3073                 case HCI_POWER_OFF:
3074                     // see hci_run
3075                     hci_stack->state = HCI_STATE_HALTING;
3076                     hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3077                     break;
3078                 case HCI_POWER_SLEEP:
3079                     // do nothing
3080                     break;
3081             }
3082             break;
3083 
3084         case HCI_STATE_SLEEPING:
3085             switch (power_mode){
3086                 case HCI_POWER_ON:
3087 
3088 #ifdef HAVE_PLATFORM_IPHONE_OS
3089                     // nothing to do, if H4 supports power management
3090                     if (btstack_control_iphone_power_management_enabled()){
3091                         hci_stack->state = HCI_STATE_INITIALIZING;
3092                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
3093                         hci_update_scan_enable();
3094                         break;
3095                     }
3096 #endif
3097                     err = hci_power_control_wake();
3098                     if (err) return err;
3099                     hci_power_transition_to_initializing();
3100                     break;
3101                 case HCI_POWER_OFF:
3102                     hci_stack->state = HCI_STATE_HALTING;
3103                     hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3104                     break;
3105                 case HCI_POWER_SLEEP:
3106                     // do nothing
3107                     break;
3108             }
3109             break;
3110     }
3111 
3112     // create internal event
3113 	hci_emit_state();
3114 
3115 	// trigger next/first action
3116 	hci_run();
3117 
3118     return 0;
3119 }
3120 
3121 
3122 #ifdef ENABLE_CLASSIC
3123 
3124 static void hci_update_scan_enable(void){
3125     // 2 = page scan, 1 = inq scan
3126     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
3127     hci_run();
3128 }
3129 
3130 void gap_discoverable_control(uint8_t enable){
3131     if (enable) enable = 1; // normalize argument
3132 
3133     if (hci_stack->discoverable == enable){
3134         hci_emit_discoverable_enabled(hci_stack->discoverable);
3135         return;
3136     }
3137 
3138     hci_stack->discoverable = enable;
3139     hci_update_scan_enable();
3140 }
3141 
3142 void gap_connectable_control(uint8_t enable){
3143     if (enable) enable = 1; // normalize argument
3144 
3145     // don't emit event
3146     if (hci_stack->connectable == enable) return;
3147 
3148     hci_stack->connectable = enable;
3149     hci_update_scan_enable();
3150 }
3151 #endif
3152 
3153 void gap_local_bd_addr(bd_addr_t address_buffer){
3154     memcpy(address_buffer, hci_stack->local_bd_addr, 6);
3155 }
3156 
3157 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3158 static void hci_host_num_completed_packets(void){
3159 
3160     // create packet manually as arrays are not supported and num_commands should not get reduced
3161     hci_reserve_packet_buffer();
3162     uint8_t * packet = hci_get_outgoing_packet_buffer();
3163 
3164     uint16_t size = 0;
3165     uint16_t num_handles = 0;
3166     packet[size++] = 0x35;
3167     packet[size++] = 0x0c;
3168     size++;  // skip param len
3169     size++;  // skip num handles
3170 
3171     // add { handle, packets } entries
3172     btstack_linked_item_t * it;
3173     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3174         hci_connection_t * connection = (hci_connection_t *) it;
3175         if (connection->num_packets_completed){
3176             little_endian_store_16(packet, size, connection->con_handle);
3177             size += 2;
3178             little_endian_store_16(packet, size, connection->num_packets_completed);
3179             size += 2;
3180             //
3181             num_handles++;
3182             connection->num_packets_completed = 0;
3183         }
3184     }
3185 
3186     packet[2] = size - 3;
3187     packet[3] = num_handles;
3188 
3189     hci_stack->host_completed_packets = 0;
3190 
3191     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3192     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3193 
3194     // release packet buffer for synchronous transport implementations
3195     if (hci_transport_synchronous()){
3196         hci_release_packet_buffer();
3197         hci_emit_transport_packet_sent();
3198     }
3199 }
3200 #endif
3201 
3202 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
3203     UNUSED(ds);
3204     hci_stack->substate = HCI_HALTING_CLOSE;
3205     // allow packet handlers to defer final shutdown
3206     hci_emit_state();
3207     hci_run();
3208 }
3209 
3210 static void hci_run(void){
3211 
3212     // log_info("hci_run: entered");
3213     btstack_linked_item_t * it;
3214 
3215     // send continuation fragments first, as they block the prepared packet buffer
3216     if (hci_stack->acl_fragmentation_total_size > 0) {
3217         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
3218         hci_connection_t *connection = hci_connection_for_handle(con_handle);
3219         if (connection) {
3220             if (hci_can_send_prepared_acl_packet_now(con_handle)){
3221                 hci_send_acl_packet_fragments(connection);
3222                 return;
3223             }
3224         } else {
3225             // connection gone -> discard further fragments
3226             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
3227             hci_stack->acl_fragmentation_total_size = 0;
3228             hci_stack->acl_fragmentation_pos = 0;
3229         }
3230     }
3231 
3232 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3233     // send host num completed packets next as they don't require num_cmd_packets > 0
3234     if (!hci_can_send_comand_packet_transport()) return;
3235     if (hci_stack->host_completed_packets){
3236         hci_host_num_completed_packets();
3237         return;
3238     }
3239 #endif
3240 
3241     if (!hci_can_send_command_packet_now()) return;
3242 
3243     // global/non-connection oriented commands
3244 
3245 #ifdef ENABLE_CLASSIC
3246     // decline incoming connections
3247     if (hci_stack->decline_reason){
3248         uint8_t reason = hci_stack->decline_reason;
3249         hci_stack->decline_reason = 0;
3250         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
3251         return;
3252     }
3253     // send scan enable
3254     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
3255         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
3256         hci_stack->new_scan_enable_value = 0xff;
3257         return;
3258     }
3259     // start/stop inquiry
3260     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN && hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX){
3261         uint8_t duration = hci_stack->inquiry_state;
3262         hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
3263         hci_send_cmd(&hci_inquiry, GAP_IAC_GENERAL_INQUIRY, duration, 0);
3264         return;
3265     }
3266     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
3267         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
3268         hci_send_cmd(&hci_inquiry_cancel);
3269         return;
3270     }
3271     // remote name request
3272     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
3273         hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
3274         hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
3275             hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
3276         return;
3277     }
3278     // pairing
3279     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
3280         uint8_t state = hci_stack->gap_pairing_state;
3281         hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
3282         switch (state){
3283             case GAP_PAIRING_STATE_SEND_PIN:
3284                 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);
3285                 break;
3286             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
3287                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
3288                 break;
3289             case GAP_PAIRING_STATE_SEND_PASSKEY:
3290                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
3291                 break;
3292             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
3293                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
3294                 break;
3295             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
3296                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
3297                 break;
3298             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
3299                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
3300                 break;
3301             default:
3302                 break;
3303         }
3304         return;
3305     }
3306 #endif
3307 
3308 #ifdef ENABLE_BLE
3309     // advertisements, active scanning, and creating connections requires randaom address to be set if using private address
3310     if ((hci_stack->state == HCI_STATE_WORKING)
3311     && (hci_stack->le_own_addr_type == BD_ADDR_TYPE_LE_PUBLIC || hci_stack->le_random_address_set)){
3312 
3313 #ifdef ENABLE_LE_CENTRAL
3314         // handle le scan
3315         if ((hci_stack->le_scanning_enabled != hci_stack->le_scanning_active)){
3316             hci_stack->le_scanning_active = hci_stack->le_scanning_enabled;
3317             hci_send_cmd(&hci_le_set_scan_enable, hci_stack->le_scanning_enabled, 0);
3318             return;
3319         }
3320         if (hci_stack->le_scan_type != 0xff){
3321             // defaults: active scanning, accept all advertisement packets
3322             int scan_type = hci_stack->le_scan_type;
3323             hci_stack->le_scan_type = 0xff;
3324             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);
3325             return;
3326         }
3327 #endif
3328 #ifdef ENABLE_LE_PERIPHERAL
3329         // le advertisement control
3330         if (hci_stack->le_advertisements_todo){
3331             log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo );
3332         }
3333         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){
3334             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE;
3335             hci_send_cmd(&hci_le_set_advertise_enable, 0);
3336             return;
3337         }
3338         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
3339             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3340             hci_send_cmd(&hci_le_set_advertising_parameters,
3341                  hci_stack->le_advertisements_interval_min,
3342                  hci_stack->le_advertisements_interval_max,
3343                  hci_stack->le_advertisements_type,
3344                  hci_stack->le_own_addr_type,
3345                  hci_stack->le_advertisements_direct_address_type,
3346                  hci_stack->le_advertisements_direct_address,
3347                  hci_stack->le_advertisements_channel_map,
3348                  hci_stack->le_advertisements_filter_policy);
3349             return;
3350         }
3351         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
3352             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3353             uint8_t adv_data_clean[31];
3354             memset(adv_data_clean, 0, sizeof(adv_data_clean));
3355             memcpy(adv_data_clean, hci_stack->le_advertisements_data, hci_stack->le_advertisements_data_len);
3356             hci_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len);
3357             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
3358             return;
3359         }
3360         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
3361             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
3362             uint8_t scan_data_clean[31];
3363             memset(scan_data_clean, 0, sizeof(scan_data_clean));
3364             memcpy(scan_data_clean, hci_stack->le_scan_response_data, hci_stack->le_scan_response_data_len);
3365             hci_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len);
3366             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, hci_stack->le_scan_response_data);
3367             return;
3368         }
3369         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){
3370             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE;
3371             hci_send_cmd(&hci_le_set_advertise_enable, 1);
3372             return;
3373         }
3374 #endif
3375 
3376 #ifdef ENABLE_LE_CENTRAL
3377         //
3378         // LE Whitelist Management
3379         //
3380 
3381         // check if whitelist needs modification
3382         btstack_linked_list_iterator_t lit;
3383         int modification_pending = 0;
3384         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3385         while (btstack_linked_list_iterator_has_next(&lit)){
3386             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3387             if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
3388                 modification_pending = 1;
3389                 break;
3390             }
3391         }
3392 
3393         if (modification_pending){
3394             // stop connnecting if modification pending
3395             if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){
3396                 hci_send_cmd(&hci_le_create_connection_cancel);
3397                 return;
3398             }
3399 
3400             // add/remove entries
3401             btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3402             while (btstack_linked_list_iterator_has_next(&lit)){
3403                 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3404                 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
3405                     entry->state = LE_WHITELIST_ON_CONTROLLER;
3406                     hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
3407                     return;
3408 
3409                 }
3410                 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
3411                     bd_addr_t address;
3412                     bd_addr_type_t address_type = entry->address_type;
3413                     memcpy(address, entry->address, 6);
3414                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3415                     btstack_memory_whitelist_entry_free(entry);
3416                     hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
3417                     return;
3418                 }
3419             }
3420         }
3421 
3422         // start connecting
3423         if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE &&
3424             !btstack_linked_list_empty(&hci_stack->le_whitelist)){
3425             bd_addr_t null_addr;
3426             memset(null_addr, 0, 6);
3427             hci_send_cmd(&hci_le_create_connection,
3428                 hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
3429                 hci_stack->le_connection_scan_window,    // scan interval: 30 ms
3430                  1,         // use whitelist
3431                  0,         // peer address type
3432                  null_addr, // peer bd addr
3433                  hci_stack->le_own_addr_type, // our addr type:
3434                  hci_stack->le_connection_interval_min,    // conn interval min
3435                  hci_stack->le_connection_interval_max,    // conn interval max
3436                  hci_stack->le_connection_latency,         // conn latency
3437                  hci_stack->le_supervision_timeout,        // conn latency
3438                  hci_stack->le_minimum_ce_length,          // min ce length
3439                  hci_stack->le_maximum_ce_length           // max ce length
3440                 );
3441             return;
3442         }
3443 #endif
3444     }
3445 #endif
3446 
3447     // send pending HCI commands
3448     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3449         hci_connection_t * connection = (hci_connection_t *) it;
3450 
3451         switch(connection->state){
3452             case SEND_CREATE_CONNECTION:
3453                 switch(connection->address_type){
3454 #ifdef ENABLE_CLASSIC
3455                     case BD_ADDR_TYPE_CLASSIC:
3456                         log_info("sending hci_create_connection");
3457                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
3458                         break;
3459 #endif
3460                     default:
3461 #ifdef ENABLE_BLE
3462 #ifdef ENABLE_LE_CENTRAL
3463                         // track outgoing connection
3464                         hci_stack->outgoing_addr_type = connection->address_type;
3465                         memcpy(hci_stack->outgoing_addr, connection->address, 6);
3466                         log_info("sending hci_le_create_connection");
3467                         hci_send_cmd(&hci_le_create_connection,
3468                              hci_stack->le_connection_scan_interval,    // conn scan interval
3469                              hci_stack->le_connection_scan_window,      // conn scan windows
3470                              0,         // don't use whitelist
3471                              connection->address_type, // peer address type
3472                              connection->address,      // peer bd addr
3473                              hci_stack->le_own_addr_type, // our addr type:
3474                              hci_stack->le_connection_interval_min,    // conn interval min
3475                              hci_stack->le_connection_interval_max,    // conn interval max
3476                              hci_stack->le_connection_latency,         // conn latency
3477                              hci_stack->le_supervision_timeout,        // conn latency
3478                              hci_stack->le_minimum_ce_length,          // min ce length
3479                              hci_stack->le_maximum_ce_length          // max ce length
3480                              );
3481                         connection->state = SENT_CREATE_CONNECTION;
3482 #endif
3483 #endif
3484                         break;
3485                 }
3486                 return;
3487 
3488 #ifdef ENABLE_CLASSIC
3489             case RECEIVED_CONNECTION_REQUEST:
3490                 connection->role  = HCI_ROLE_SLAVE;
3491                 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
3492                     log_info("sending hci_accept_connection_request, remote eSCO %u", connection->remote_supported_feature_eSCO);
3493                     connection->state = ACCEPTED_CONNECTION_REQUEST;
3494                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
3495                 }
3496                 return;
3497 #endif
3498 
3499 #ifdef ENABLE_BLE
3500 #ifdef ENABLE_LE_CENTRAL
3501             case SEND_CANCEL_CONNECTION:
3502                 connection->state = SENT_CANCEL_CONNECTION;
3503                 hci_send_cmd(&hci_le_create_connection_cancel);
3504                 return;
3505 #endif
3506 #endif
3507             case SEND_DISCONNECT:
3508                 connection->state = SENT_DISCONNECT;
3509                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
3510                 return;
3511 
3512             default:
3513                 break;
3514         }
3515 
3516         // no further commands if connection is about to get shut down
3517         if (connection->state == SENT_DISCONNECT) continue;
3518 
3519 #ifdef ENABLE_CLASSIC
3520         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
3521             log_info("responding to link key request");
3522             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
3523             link_key_t link_key;
3524             link_key_type_t link_key_type;
3525             if ( hci_stack->link_key_db
3526               && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type)
3527               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
3528                connection->link_key_type = link_key_type;
3529                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
3530             } else {
3531                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
3532             }
3533             return;
3534         }
3535 
3536         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
3537             log_info("denying to pin request");
3538             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
3539             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
3540             return;
3541         }
3542 
3543         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
3544             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
3545             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
3546             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
3547                 // tweak authentication requirements
3548                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
3549                 if (connection->bonding_flags & BONDING_DEDICATED){
3550                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
3551                 }
3552                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
3553                     authreq |= 1;
3554                 }
3555                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
3556             } else {
3557                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
3558             }
3559             return;
3560         }
3561 
3562         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
3563             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
3564             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
3565             return;
3566         }
3567 
3568         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
3569             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
3570             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
3571             return;
3572         }
3573 
3574         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
3575             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
3576             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
3577             return;
3578         }
3579 
3580         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
3581             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
3582             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
3583             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
3584             return;
3585         }
3586 
3587         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
3588             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
3589             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
3590             return;
3591         }
3592 
3593         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
3594             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
3595             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
3596             return;
3597         }
3598 #endif
3599 
3600         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
3601             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
3602             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
3603             return;
3604         }
3605 
3606 #ifdef ENABLE_CLASSIC
3607         uint16_t sniff_min_interval;
3608         switch (connection->sniff_min_interval){
3609             case 0:
3610                 break;
3611             case 0xffff:
3612                 connection->sniff_min_interval = 0;
3613                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
3614                 return;
3615             default:
3616                 sniff_min_interval = connection->sniff_min_interval;
3617                 connection->sniff_min_interval = 0;
3618                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
3619                 return;
3620         }
3621 #endif
3622 
3623 #ifdef ENABLE_BLE
3624         switch (connection->le_con_parameter_update_state){
3625             // response to L2CAP CON PARAMETER UPDATE REQUEST
3626             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
3627                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3628                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
3629                     connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
3630                     0x0000, 0xffff);
3631                 return;
3632             case CON_PARAMETER_UPDATE_REPLY:
3633                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3634                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
3635                     connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
3636                     0x0000, 0xffff);
3637                 return;
3638             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
3639                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3640                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, ERROR_CODE_UNSUPPORTED_LMP_PARAMETER_VALUE_UNSUPPORTED_LL_PARAMETER_VALUE);
3641                 return;
3642             default:
3643                 break;
3644         }
3645         if (connection->le_phy_update_all_phys != 0xff){
3646             uint8_t all_phys = connection->le_phy_update_all_phys;
3647             connection->le_phy_update_all_phys = 0xff;
3648             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);
3649             return;
3650         }
3651 #endif
3652     }
3653 
3654     hci_connection_t * connection;
3655     switch (hci_stack->state){
3656         case HCI_STATE_INITIALIZING:
3657             hci_initializing_run();
3658             break;
3659 
3660         case HCI_STATE_HALTING:
3661 
3662             log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
3663             switch (hci_stack->substate){
3664                 case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
3665                 case HCI_HALTING_DISCONNECT_ALL_TIMER:
3666 
3667 #ifdef ENABLE_BLE
3668 #ifdef ENABLE_LE_CENTRAL
3669                     // free whitelist entries
3670                     {
3671                         btstack_linked_list_iterator_t lit;
3672                         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3673                         while (btstack_linked_list_iterator_has_next(&lit)){
3674                             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3675                             btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3676                             btstack_memory_whitelist_entry_free(entry);
3677                         }
3678                     }
3679 #endif
3680 #endif
3681                     // close all open connections
3682                     connection =  (hci_connection_t *) hci_stack->connections;
3683                     if (connection){
3684                         hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
3685                         if (!hci_can_send_command_packet_now()) return;
3686 
3687                         // check state
3688                         if (connection->state == SENT_DISCONNECT) return;
3689                         connection->state = SENT_DISCONNECT;
3690 
3691                         log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
3692 
3693                         // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
3694                         hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
3695 
3696                         // ... which would be ignored anyway as we shutdown (free) the connection now
3697                         hci_shutdown_connection(connection);
3698 
3699                         // finally, send the disconnect command
3700                         hci_send_cmd(&hci_disconnect, con_handle, 0x13);  // remote closed connection
3701                         return;
3702                     }
3703 
3704                     if (hci_stack->substate == HCI_HALTING_DISCONNECT_ALL_TIMER){
3705                         // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
3706                         log_info("HCI_STATE_HALTING: wait 50 ms");
3707                         hci_stack->substate = HCI_HALTING_W4_TIMER;
3708                         btstack_run_loop_set_timer(&hci_stack->timeout, 50);
3709                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
3710                         btstack_run_loop_add_timer(&hci_stack->timeout);
3711                         break;
3712                     }
3713 
3714                     /* explicit fall-through */
3715 
3716                 case HCI_HALTING_CLOSE:
3717                     log_info("HCI_STATE_HALTING, calling off");
3718 
3719                     // switch mode
3720                     hci_power_control_off();
3721 
3722                     log_info("HCI_STATE_HALTING, emitting state");
3723                     hci_emit_state();
3724                     log_info("HCI_STATE_HALTING, done");
3725                     break;
3726 
3727                 case HCI_HALTING_W4_TIMER:
3728                     // keep waiting
3729 
3730                     break;
3731                 default:
3732                     break;
3733             }
3734 
3735             break;
3736 
3737         case HCI_STATE_FALLING_ASLEEP:
3738             switch(hci_stack->substate) {
3739                 case HCI_FALLING_ASLEEP_DISCONNECT:
3740                     log_info("HCI_STATE_FALLING_ASLEEP");
3741                     // close all open connections
3742                     connection =  (hci_connection_t *) hci_stack->connections;
3743 
3744 #ifdef HAVE_PLATFORM_IPHONE_OS
3745                     // don't close connections, if H4 supports power management
3746                     if (btstack_control_iphone_power_management_enabled()){
3747                         connection = NULL;
3748                     }
3749 #endif
3750                     if (connection){
3751 
3752                         // send disconnect
3753                         if (!hci_can_send_command_packet_now()) return;
3754 
3755                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
3756                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
3757 
3758                         // send disconnected event right away - causes higher layer connections to get closed, too.
3759                         hci_shutdown_connection(connection);
3760                         return;
3761                     }
3762 
3763                     if (hci_classic_supported()){
3764                         // disable page and inquiry scan
3765                         if (!hci_can_send_command_packet_now()) return;
3766 
3767                         log_info("HCI_STATE_HALTING, disabling inq scans");
3768                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
3769 
3770                         // continue in next sub state
3771                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
3772                         break;
3773                     }
3774                     // no break - fall through for ble-only chips
3775 
3776                 case HCI_FALLING_ASLEEP_COMPLETE:
3777                     log_info("HCI_STATE_HALTING, calling sleep");
3778 #ifdef HAVE_PLATFORM_IPHONE_OS
3779                     // don't actually go to sleep, if H4 supports power management
3780                     if (btstack_control_iphone_power_management_enabled()){
3781                         // SLEEP MODE reached
3782                         hci_stack->state = HCI_STATE_SLEEPING;
3783                         hci_emit_state();
3784                         break;
3785                     }
3786 #endif
3787                     // switch mode
3788                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
3789                     hci_emit_state();
3790                     break;
3791 
3792                 default:
3793                     break;
3794             }
3795             break;
3796 
3797         default:
3798             break;
3799     }
3800 }
3801 
3802 int hci_send_cmd_packet(uint8_t *packet, int size){
3803     // house-keeping
3804 
3805     if (IS_COMMAND(packet, hci_write_loopback_mode)){
3806         hci_stack->loopback_mode = packet[3];
3807     }
3808 
3809 #ifdef ENABLE_CLASSIC
3810     bd_addr_t addr;
3811     hci_connection_t * conn;
3812 
3813     // create_connection?
3814     if (IS_COMMAND(packet, hci_create_connection)){
3815         reverse_bd_addr(&packet[3], addr);
3816         log_info("Create_connection to %s", bd_addr_to_str(addr));
3817 
3818         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3819         if (!conn){
3820             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3821             if (!conn){
3822                 // notify client that alloc failed
3823                 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3824                 return -1; // packet not sent to controller
3825             }
3826             conn->state = SEND_CREATE_CONNECTION;
3827         }
3828         log_info("conn state %u", conn->state);
3829         switch (conn->state){
3830             // if connection active exists
3831             case OPEN:
3832                 // and OPEN, emit connection complete command
3833                 hci_emit_connection_complete(addr, conn->con_handle, 0);
3834                 return -1; // packet not sent to controller
3835             case SEND_CREATE_CONNECTION:
3836                 // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
3837                 break;
3838             default:
3839                 // otherwise, just ignore as it is already in the open process
3840                 return -1; // packet not sent to controller
3841         }
3842         conn->state = SENT_CREATE_CONNECTION;
3843 
3844         // track outgoing connection
3845         hci_stack->outgoing_addr_type = BD_ADDR_TYPE_CLASSIC;
3846         memcpy(hci_stack->outgoing_addr, addr, 6);
3847     }
3848 
3849     if (IS_COMMAND(packet, hci_link_key_request_reply)){
3850         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
3851     }
3852     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
3853         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
3854     }
3855 
3856     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
3857         if (hci_stack->link_key_db){
3858             reverse_bd_addr(&packet[3], addr);
3859             hci_stack->link_key_db->delete_link_key(addr);
3860         }
3861     }
3862 
3863     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
3864     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
3865         reverse_bd_addr(&packet[3], addr);
3866         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3867         if (conn){
3868             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
3869         }
3870     }
3871 
3872     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
3873     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
3874     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
3875     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
3876         reverse_bd_addr(&packet[3], addr);
3877         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3878         if (conn){
3879             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
3880         }
3881     }
3882 
3883 #ifdef ENABLE_SCO_OVER_HCI
3884     // setup_synchronous_connection? Voice setting at offset 22
3885     if (IS_COMMAND(packet, hci_setup_synchronous_connection)){
3886         // TODO: compare to current setting if sco connection already active
3887         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
3888     }
3889     // accept_synchronus_connection? Voice setting at offset 18
3890     if (IS_COMMAND(packet, hci_accept_synchronous_connection)){
3891         // TODO: compare to current setting if sco connection already active
3892         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
3893     }
3894 #endif
3895 #endif
3896 
3897 #ifdef ENABLE_BLE
3898 #ifdef ENABLE_LE_PERIPHERAL
3899     if (IS_COMMAND(packet, hci_le_set_random_address)){
3900         hci_stack->le_random_address_set = 1;
3901         reverse_bd_addr(&packet[3], hci_stack->le_random_address);
3902     }
3903     if (IS_COMMAND(packet, hci_le_set_advertise_enable)){
3904         hci_stack->le_advertisements_active = packet[3];
3905     }
3906 #endif
3907 #ifdef ENABLE_LE_CENTRAL
3908     if (IS_COMMAND(packet, hci_le_create_connection)){
3909         // white list used?
3910         uint8_t initiator_filter_policy = packet[7];
3911         switch (initiator_filter_policy){
3912             case 0:
3913                 // whitelist not used
3914                 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
3915                 break;
3916             case 1:
3917                 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
3918                 break;
3919             default:
3920                 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
3921                 break;
3922         }
3923     }
3924     if (IS_COMMAND(packet, hci_le_create_connection_cancel)){
3925         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3926     }
3927 #endif
3928 #endif
3929 
3930     hci_stack->num_cmd_packets--;
3931 
3932     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3933     return hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3934 }
3935 
3936 // disconnect because of security block
3937 void hci_disconnect_security_block(hci_con_handle_t con_handle){
3938     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3939     if (!connection) return;
3940     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3941 }
3942 
3943 
3944 // Configure Secure Simple Pairing
3945 
3946 #ifdef ENABLE_CLASSIC
3947 
3948 // enable will enable SSP during init
3949 void gap_ssp_set_enable(int enable){
3950     hci_stack->ssp_enable = enable;
3951 }
3952 
3953 static int hci_local_ssp_activated(void){
3954     return gap_ssp_supported() && hci_stack->ssp_enable;
3955 }
3956 
3957 // if set, BTstack will respond to io capability request using authentication requirement
3958 void gap_ssp_set_io_capability(int io_capability){
3959     hci_stack->ssp_io_capability = io_capability;
3960 }
3961 void gap_ssp_set_authentication_requirement(int authentication_requirement){
3962     hci_stack->ssp_authentication_requirement = authentication_requirement;
3963 }
3964 
3965 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
3966 void gap_ssp_set_auto_accept(int auto_accept){
3967     hci_stack->ssp_auto_accept = auto_accept;
3968 }
3969 #endif
3970 
3971 // va_list part of hci_send_cmd
3972 int hci_send_cmd_va_arg(const hci_cmd_t *cmd, va_list argptr){
3973     if (!hci_can_send_command_packet_now()){
3974         log_error("hci_send_cmd called but cannot send packet now");
3975         return 0;
3976     }
3977 
3978     // for HCI INITIALIZATION
3979     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
3980     hci_stack->last_cmd_opcode = cmd->opcode;
3981 
3982     hci_reserve_packet_buffer();
3983     uint8_t * packet = hci_stack->hci_packet_buffer;
3984     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
3985     int err = hci_send_cmd_packet(packet, size);
3986 
3987     // release packet buffer for synchronous transport implementations
3988     if (hci_transport_synchronous()){
3989         hci_release_packet_buffer();
3990         hci_emit_transport_packet_sent();
3991     }
3992 
3993     return err;
3994 }
3995 
3996 /**
3997  * pre: numcmds >= 0 - it's allowed to send a command to the controller
3998  */
3999 int hci_send_cmd(const hci_cmd_t *cmd, ...){
4000     va_list argptr;
4001     va_start(argptr, cmd);
4002     int res = hci_send_cmd_va_arg(cmd, argptr);
4003     va_end(argptr);
4004     return res;
4005 }
4006 
4007 // Create various non-HCI events.
4008 // TODO: generalize, use table similar to hci_create_command
4009 
4010 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
4011     // dump packet
4012     if (dump) {
4013         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
4014     }
4015 
4016     // dispatch to all event handlers
4017     btstack_linked_list_iterator_t it;
4018     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
4019     while (btstack_linked_list_iterator_has_next(&it)){
4020         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
4021         entry->callback(HCI_EVENT_PACKET, 0, event, size);
4022     }
4023 }
4024 
4025 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
4026     if (!hci_stack->acl_packet_handler) return;
4027     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
4028 }
4029 
4030 #ifdef ENABLE_CLASSIC
4031 static void hci_notify_if_sco_can_send_now(void){
4032     // notify SCO sender if waiting
4033     if (!hci_stack->sco_waiting_for_can_send_now) return;
4034     if (hci_can_send_sco_packet_now()){
4035         hci_stack->sco_waiting_for_can_send_now = 0;
4036         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
4037         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
4038         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
4039     }
4040 }
4041 
4042 // parsing end emitting has been merged to reduce code size
4043 static void gap_inquiry_explode(uint8_t * packet){
4044     uint8_t event[19+GAP_INQUIRY_MAX_NAME_LEN];
4045 
4046     uint8_t * eir_data;
4047     ad_context_t context;
4048     const uint8_t * name;
4049     uint8_t         name_len;
4050 
4051     int event_type = hci_event_packet_get_type(packet);
4052     int num_reserved_fields = event_type == HCI_EVENT_INQUIRY_RESULT ? 2 : 1;    // 2 for old event, 1 otherwise
4053     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
4054 
4055     // event[1] is set at the end
4056     int i;
4057     for (i=0; i<num_responses;i++){
4058         memset(event, 0, sizeof(event));
4059         event[0] = GAP_EVENT_INQUIRY_RESULT;
4060         uint8_t event_size = 18;    // if name is not set by EIR
4061 
4062         memcpy(&event[2],  &packet[3 +                                             i*6], 6); // bd_addr
4063         event[8] =          packet[3 + num_responses*(6)                         + i*1];     // page_scan_repetition_mode
4064         memcpy(&event[9],  &packet[3 + num_responses*(6+1+num_reserved_fields)   + i*3], 3); // class of device
4065         memcpy(&event[12], &packet[3 + num_responses*(6+1+num_reserved_fields+3) + i*2], 2); // clock offset
4066 
4067         switch (event_type){
4068             case HCI_EVENT_INQUIRY_RESULT:
4069                 // 14,15,16,17 = 0, size 18
4070                 break;
4071             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
4072                 event[14] = 1;
4073                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
4074                 // 16,17 = 0, size 18
4075                 break;
4076             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
4077                 event[14] = 1;
4078                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
4079                 // for EIR packets, there is only one reponse in it
4080                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
4081                 name = NULL;
4082                 // EIR data is 240 bytes in EIR event
4083                 for (ad_iterator_init(&context, 240, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
4084                     uint8_t data_type    = ad_iterator_get_data_type(&context);
4085                     uint8_t data_size    = ad_iterator_get_data_len(&context);
4086                     const uint8_t * data = ad_iterator_get_data(&context);
4087                     // Prefer Complete Local Name over Shortend Local Name
4088                     switch (data_type){
4089                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
4090                             if (name) continue;
4091                             /* explicit fall-through */
4092                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
4093                             name = data;
4094                             name_len = data_size;
4095                             break;
4096                         default:
4097                             break;
4098                     }
4099                 }
4100                 if (name){
4101                     event[16] = 1;
4102                     // truncate name if needed
4103                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
4104                     event[17] = len;
4105                     memcpy(&event[18], name, len);
4106                     event_size += len;
4107                 }
4108                 break;
4109         }
4110         event[1] = event_size - 2;
4111         hci_emit_event(event, event_size, 1);
4112     }
4113 }
4114 #endif
4115 
4116 void hci_emit_state(void){
4117     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
4118     uint8_t event[3];
4119     event[0] = BTSTACK_EVENT_STATE;
4120     event[1] = sizeof(event) - 2;
4121     event[2] = hci_stack->state;
4122     hci_emit_event(event, sizeof(event), 1);
4123 }
4124 
4125 #ifdef ENABLE_CLASSIC
4126 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
4127     uint8_t event[13];
4128     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
4129     event[1] = sizeof(event) - 2;
4130     event[2] = status;
4131     little_endian_store_16(event, 3, con_handle);
4132     reverse_bd_addr(address, &event[5]);
4133     event[11] = 1; // ACL connection
4134     event[12] = 0; // encryption disabled
4135     hci_emit_event(event, sizeof(event), 1);
4136 }
4137 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
4138     if (disable_l2cap_timeouts) return;
4139     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
4140     uint8_t event[4];
4141     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
4142     event[1] = sizeof(event) - 2;
4143     little_endian_store_16(event, 2, conn->con_handle);
4144     hci_emit_event(event, sizeof(event), 1);
4145 }
4146 #endif
4147 
4148 #ifdef ENABLE_BLE
4149 #ifdef ENABLE_LE_CENTRAL
4150 static void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
4151     uint8_t event[21];
4152     event[0] = HCI_EVENT_LE_META;
4153     event[1] = sizeof(event) - 2;
4154     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
4155     event[3] = status;
4156     little_endian_store_16(event, 4, con_handle);
4157     event[6] = 0; // TODO: role
4158     event[7] = address_type;
4159     reverse_bd_addr(address, &event[8]);
4160     little_endian_store_16(event, 14, 0); // interval
4161     little_endian_store_16(event, 16, 0); // latency
4162     little_endian_store_16(event, 18, 0); // supervision timeout
4163     event[20] = 0; // master clock accuracy
4164     hci_emit_event(event, sizeof(event), 1);
4165 }
4166 #endif
4167 #endif
4168 
4169 static void hci_emit_transport_packet_sent(void){
4170     // notify upper stack that it might be possible to send again
4171     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
4172     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
4173 }
4174 
4175 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
4176     uint8_t event[6];
4177     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
4178     event[1] = sizeof(event) - 2;
4179     event[2] = 0; // status = OK
4180     little_endian_store_16(event, 3, con_handle);
4181     event[5] = reason;
4182     hci_emit_event(event, sizeof(event), 1);
4183 }
4184 
4185 static void hci_emit_nr_connections_changed(void){
4186     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
4187     uint8_t event[3];
4188     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
4189     event[1] = sizeof(event) - 2;
4190     event[2] = nr_hci_connections();
4191     hci_emit_event(event, sizeof(event), 1);
4192 }
4193 
4194 static void hci_emit_hci_open_failed(void){
4195     log_info("BTSTACK_EVENT_POWERON_FAILED");
4196     uint8_t event[2];
4197     event[0] = BTSTACK_EVENT_POWERON_FAILED;
4198     event[1] = sizeof(event) - 2;
4199     hci_emit_event(event, sizeof(event), 1);
4200 }
4201 
4202 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
4203     log_info("hci_emit_dedicated_bonding_result %u ", status);
4204     uint8_t event[9];
4205     int pos = 0;
4206     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
4207     event[pos++] = sizeof(event) - 2;
4208     event[pos++] = status;
4209     reverse_bd_addr(address, &event[pos]);
4210     hci_emit_event(event, sizeof(event), 1);
4211 }
4212 
4213 
4214 #ifdef ENABLE_CLASSIC
4215 
4216 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
4217     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
4218     uint8_t event[5];
4219     int pos = 0;
4220     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
4221     event[pos++] = sizeof(event) - 2;
4222     little_endian_store_16(event, 2, con_handle);
4223     pos += 2;
4224     event[pos++] = level;
4225     hci_emit_event(event, sizeof(event), 1);
4226 }
4227 
4228 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
4229     if (!connection) return LEVEL_0;
4230     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
4231     return gap_security_level_for_link_key_type(connection->link_key_type);
4232 }
4233 
4234 static void hci_emit_discoverable_enabled(uint8_t enabled){
4235     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
4236     uint8_t event[3];
4237     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
4238     event[1] = sizeof(event) - 2;
4239     event[2] = enabled;
4240     hci_emit_event(event, sizeof(event), 1);
4241 }
4242 
4243 #ifdef ENABLE_CLASSIC
4244 // query if remote side supports eSCO
4245 int hci_remote_esco_supported(hci_con_handle_t con_handle){
4246     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4247     if (!connection) return 0;
4248     return connection->remote_supported_feature_eSCO;
4249 }
4250 
4251 // query if remote side supports SSP
4252 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
4253     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4254     if (!connection) return 0;
4255     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
4256 }
4257 
4258 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
4259     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
4260 }
4261 #endif
4262 
4263 // GAP API
4264 /**
4265  * @bbrief enable/disable bonding. default is enabled
4266  * @praram enabled
4267  */
4268 void gap_set_bondable_mode(int enable){
4269     hci_stack->bondable = enable ? 1 : 0;
4270 }
4271 /**
4272  * @brief Get bondable mode.
4273  * @return 1 if bondable
4274  */
4275 int gap_get_bondable_mode(void){
4276     return hci_stack->bondable;
4277 }
4278 
4279 /**
4280  * @brief map link keys to security levels
4281  */
4282 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
4283     switch (link_key_type){
4284         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
4285             return LEVEL_4;
4286         case COMBINATION_KEY:
4287         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
4288             return LEVEL_3;
4289         default:
4290             return LEVEL_2;
4291     }
4292 }
4293 
4294 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
4295     log_info("gap_mitm_protection_required_for_security_level %u", level);
4296     return level > LEVEL_2;
4297 }
4298 
4299 /**
4300  * @brief get current security level
4301  */
4302 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
4303     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4304     if (!connection) return LEVEL_0;
4305     return gap_security_level_for_connection(connection);
4306 }
4307 
4308 /**
4309  * @brief request connection to device to
4310  * @result GAP_AUTHENTICATION_RESULT
4311  */
4312 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
4313     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4314     if (!connection){
4315         hci_emit_security_level(con_handle, LEVEL_0);
4316         return;
4317     }
4318     gap_security_level_t current_level = gap_security_level(con_handle);
4319     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
4320         requested_level, connection->requested_security_level, current_level);
4321 
4322     // assumption: earlier requested security higher than current level => security request is active
4323     if (current_level < connection->requested_security_level){
4324         if (connection->requested_security_level < requested_level){
4325             // increase requested level as new level is higher
4326 
4327             // TODO: handle re-authentication when done
4328 
4329             connection->requested_security_level = requested_level;
4330         }
4331         return;
4332     }
4333 
4334     // no request active, notify if security sufficient
4335     if (requested_level <= current_level){
4336         hci_emit_security_level(con_handle, current_level);
4337         return;
4338     }
4339 
4340     // start pairing to increase security level
4341     connection->requested_security_level = requested_level;
4342 
4343 #if 0
4344     // sending encryption request without a link key results in an error.
4345     // TODO: figure out how to use it properly
4346 
4347     // would enabling ecnryption suffice (>= LEVEL_2)?
4348     if (hci_stack->link_key_db){
4349         link_key_type_t link_key_type;
4350         link_key_t      link_key;
4351         if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){
4352             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
4353                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
4354                 return;
4355             }
4356         }
4357     }
4358 #endif
4359 
4360     // start to authenticate connection
4361     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
4362     hci_run();
4363 }
4364 
4365 /**
4366  * @brief start dedicated bonding with device. disconnect after bonding
4367  * @param device
4368  * @param request MITM protection
4369  * @result GAP_DEDICATED_BONDING_COMPLETE
4370  */
4371 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
4372 
4373     // create connection state machine
4374     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
4375 
4376     if (!connection){
4377         return BTSTACK_MEMORY_ALLOC_FAILED;
4378     }
4379 
4380     // delete linkn key
4381     gap_drop_link_key_for_bd_addr(device);
4382 
4383     // configure LEVEL_2/3, dedicated bonding
4384     connection->state = SEND_CREATE_CONNECTION;
4385     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
4386     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
4387     connection->bonding_flags = BONDING_DEDICATED;
4388 
4389     // wait for GAP Security Result and send GAP Dedicated Bonding complete
4390 
4391     // handle: connnection failure (connection complete != ok)
4392     // handle: authentication failure
4393     // handle: disconnect on done
4394 
4395     hci_run();
4396 
4397     return 0;
4398 }
4399 #endif
4400 
4401 void gap_set_local_name(const char * local_name){
4402     hci_stack->local_name = local_name;
4403 }
4404 
4405 
4406 #ifdef ENABLE_BLE
4407 
4408 #ifdef ENABLE_LE_CENTRAL
4409 void gap_start_scan(void){
4410     hci_stack->le_scanning_enabled = 1;
4411     hci_run();
4412 }
4413 
4414 void gap_stop_scan(void){
4415     hci_stack->le_scanning_enabled = 0;
4416     hci_run();
4417 }
4418 
4419 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
4420     hci_stack->le_scan_type     = scan_type;
4421     hci_stack->le_scan_interval = scan_interval;
4422     hci_stack->le_scan_window   = scan_window;
4423     hci_run();
4424 }
4425 
4426 uint8_t gap_connect(bd_addr_t addr, bd_addr_type_t addr_type){
4427     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
4428     if (!conn){
4429         log_info("gap_connect: no connection exists yet, creating context");
4430         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
4431         if (!conn){
4432             // notify client that alloc failed
4433             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
4434             log_info("gap_connect: failed to alloc hci_connection_t");
4435             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
4436         }
4437         conn->state = SEND_CREATE_CONNECTION;
4438         log_info("gap_connect: send create connection next");
4439         hci_run();
4440         return 0;
4441     }
4442 
4443     if (!hci_is_le_connection(conn) ||
4444         conn->state == SEND_CREATE_CONNECTION ||
4445         conn->state == SENT_CREATE_CONNECTION) {
4446         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
4447         log_error("gap_connect: classic connection or connect is already being created");
4448         return GATT_CLIENT_IN_WRONG_STATE;
4449     }
4450 
4451     log_info("gap_connect: context exists with state %u", conn->state);
4452     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0);
4453     hci_run();
4454     return 0;
4455 }
4456 
4457 // @assumption: only a single outgoing LE Connection exists
4458 static hci_connection_t * gap_get_outgoing_connection(void){
4459     btstack_linked_item_t *it;
4460     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
4461         hci_connection_t * conn = (hci_connection_t *) it;
4462         if (!hci_is_le_connection(conn)) continue;
4463         switch (conn->state){
4464             case SEND_CREATE_CONNECTION:
4465             case SENT_CREATE_CONNECTION:
4466             case SENT_CANCEL_CONNECTION:
4467                 return conn;
4468             default:
4469                 break;
4470         };
4471     }
4472     return NULL;
4473 }
4474 
4475 uint8_t gap_connect_cancel(void){
4476     hci_connection_t * conn = gap_get_outgoing_connection();
4477     if (!conn) return 0;
4478     switch (conn->state){
4479         case SEND_CREATE_CONNECTION:
4480             // skip sending create connection and emit event instead
4481             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
4482             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
4483             btstack_memory_hci_connection_free( conn );
4484             break;
4485         case SENT_CREATE_CONNECTION:
4486             // request to send cancel connection
4487             conn->state = SEND_CANCEL_CONNECTION;
4488             hci_run();
4489             break;
4490         default:
4491             break;
4492     }
4493     return 0;
4494 }
4495 #endif
4496 
4497 #ifdef ENABLE_LE_CENTRAL
4498 /**
4499  * @brief Set connection parameters for outgoing connections
4500  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
4501  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
4502  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
4503  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
4504  * @param conn_latency, default: 4
4505  * @param supervision_timeout (unit: 10ms), default: 720 ms
4506  * @param min_ce_length (unit: 0.625ms), default: 10 ms
4507  * @param max_ce_length (unit: 0.625ms), default: 30 ms
4508  */
4509 
4510 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
4511     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
4512     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
4513     hci_stack->le_connection_scan_interval = conn_scan_interval;
4514     hci_stack->le_connection_scan_window = conn_scan_window;
4515     hci_stack->le_connection_interval_min = conn_interval_min;
4516     hci_stack->le_connection_interval_max = conn_interval_max;
4517     hci_stack->le_connection_latency = conn_latency;
4518     hci_stack->le_supervision_timeout = supervision_timeout;
4519     hci_stack->le_minimum_ce_length = min_ce_length;
4520     hci_stack->le_maximum_ce_length = max_ce_length;
4521 }
4522 #endif
4523 
4524 /**
4525  * @brief Updates the connection parameters for a given LE connection
4526  * @param handle
4527  * @param conn_interval_min (unit: 1.25ms)
4528  * @param conn_interval_max (unit: 1.25ms)
4529  * @param conn_latency
4530  * @param supervision_timeout (unit: 10ms)
4531  * @returns 0 if ok
4532  */
4533 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4534     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4535     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4536     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4537     connection->le_conn_interval_min = conn_interval_min;
4538     connection->le_conn_interval_max = conn_interval_max;
4539     connection->le_conn_latency = conn_latency;
4540     connection->le_supervision_timeout = supervision_timeout;
4541     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
4542     hci_run();
4543     return 0;
4544 }
4545 
4546 /**
4547  * @brief Request an update of the connection parameter for a given LE connection
4548  * @param handle
4549  * @param conn_interval_min (unit: 1.25ms)
4550  * @param conn_interval_max (unit: 1.25ms)
4551  * @param conn_latency
4552  * @param supervision_timeout (unit: 10ms)
4553  * @returns 0 if ok
4554  */
4555 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4556     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4557     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4558     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4559     connection->le_conn_interval_min = conn_interval_min;
4560     connection->le_conn_interval_max = conn_interval_max;
4561     connection->le_conn_latency = conn_latency;
4562     connection->le_supervision_timeout = supervision_timeout;
4563     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
4564     hci_run();
4565     return 0;
4566 }
4567 
4568 #ifdef ENABLE_LE_PERIPHERAL
4569 
4570 static void gap_advertisments_changed(void){
4571     // disable advertisements before updating adv, scan data, or adv params
4572     if (hci_stack->le_advertisements_active){
4573         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
4574     }
4575     hci_run();
4576 }
4577 
4578 /**
4579  * @brief Set Advertisement Data
4580  * @param advertising_data_length
4581  * @param advertising_data (max 31 octets)
4582  * @note data is not copied, pointer has to stay valid
4583  */
4584 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
4585     hci_stack->le_advertisements_data_len = advertising_data_length;
4586     hci_stack->le_advertisements_data = advertising_data;
4587     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4588     gap_advertisments_changed();
4589 }
4590 
4591 /**
4592  * @brief Set Scan Response Data
4593  * @param advertising_data_length
4594  * @param advertising_data (max 31 octets)
4595  * @note data is not copied, pointer has to stay valid
4596  */
4597 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
4598     hci_stack->le_scan_response_data_len = scan_response_data_length;
4599     hci_stack->le_scan_response_data = scan_response_data;
4600     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
4601     gap_advertisments_changed();
4602 }
4603 
4604 /**
4605  * @brief Set Advertisement Parameters
4606  * @param adv_int_min
4607  * @param adv_int_max
4608  * @param adv_type
4609  * @param direct_address_type
4610  * @param direct_address
4611  * @param channel_map
4612  * @param filter_policy
4613  *
4614  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
4615  */
4616  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
4617     uint8_t direct_address_typ, bd_addr_t direct_address,
4618     uint8_t channel_map, uint8_t filter_policy) {
4619 
4620     hci_stack->le_advertisements_interval_min = adv_int_min;
4621     hci_stack->le_advertisements_interval_max = adv_int_max;
4622     hci_stack->le_advertisements_type = adv_type;
4623     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
4624     hci_stack->le_advertisements_channel_map = channel_map;
4625     hci_stack->le_advertisements_filter_policy = filter_policy;
4626     memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6);
4627 
4628     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4629     gap_advertisments_changed();
4630  }
4631 
4632 /**
4633  * @brief Enable/Disable Advertisements
4634  * @param enabled
4635  */
4636 void gap_advertisements_enable(int enabled){
4637     hci_stack->le_advertisements_enabled = enabled;
4638     if (enabled && !hci_stack->le_advertisements_active){
4639         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
4640     }
4641     if (!enabled && hci_stack->le_advertisements_active){
4642         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE;
4643     }
4644     hci_run();
4645 }
4646 
4647 #endif
4648 
4649 void hci_le_set_own_address_type(uint8_t own_address_type){
4650     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
4651     if (own_address_type == hci_stack->le_own_addr_type) return;
4652     hci_stack->le_own_addr_type = own_address_type;
4653 
4654 #ifdef ENABLE_LE_PERIPHERAL
4655     // update advertisement parameters, too
4656     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4657     gap_advertisments_changed();
4658 #endif
4659 #ifdef ENABLE_LE_CENTRAL
4660     // note: we don't update scan parameters or modify ongoing connection attempts
4661 #endif
4662 }
4663 
4664 #endif
4665 
4666 uint8_t gap_disconnect(hci_con_handle_t handle){
4667     hci_connection_t * conn = hci_connection_for_handle(handle);
4668     if (!conn){
4669         hci_emit_disconnection_complete(handle, 0);
4670         return 0;
4671     }
4672     // ignore if already disconnected
4673     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
4674         return 0;
4675     }
4676     conn->state = SEND_DISCONNECT;
4677     hci_run();
4678     return 0;
4679 }
4680 
4681 /**
4682  * @brief Get connection type
4683  * @param con_handle
4684  * @result connection_type
4685  */
4686 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
4687     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4688     if (!conn) return GAP_CONNECTION_INVALID;
4689     switch (conn->address_type){
4690         case BD_ADDR_TYPE_LE_PUBLIC:
4691         case BD_ADDR_TYPE_LE_RANDOM:
4692             return GAP_CONNECTION_LE;
4693         case BD_ADDR_TYPE_SCO:
4694             return GAP_CONNECTION_SCO;
4695         case BD_ADDR_TYPE_CLASSIC:
4696             return GAP_CONNECTION_ACL;
4697         default:
4698             return GAP_CONNECTION_INVALID;
4699     }
4700 }
4701 
4702 #ifdef ENABLE_BLE
4703 
4704 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){
4705     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4706     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4707 
4708     conn->le_phy_update_all_phys    = all_phys;
4709     conn->le_phy_update_tx_phys     = tx_phys;
4710     conn->le_phy_update_rx_phys     = rx_phys;
4711     conn->le_phy_update_phy_options = phy_options;
4712 
4713     hci_run();
4714 
4715     return 0;
4716 }
4717 
4718 #ifdef ENABLE_LE_CENTRAL
4719 /**
4720  * @brief Auto Connection Establishment - Start Connecting to device
4721  * @param address_typ
4722  * @param address
4723  * @returns 0 if ok
4724  */
4725 int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){
4726     // check capacity
4727     int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist);
4728     if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
4729     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
4730     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
4731     entry->address_type = address_type;
4732     memcpy(entry->address, address, 6);
4733     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
4734     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
4735     hci_run();
4736     return 0;
4737 }
4738 
4739 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){
4740     btstack_linked_list_iterator_t it;
4741     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4742     while (btstack_linked_list_iterator_has_next(&it)){
4743         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4744         if (entry->address_type != address_type) continue;
4745         if (memcmp(entry->address, address, 6) != 0) continue;
4746         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4747             // remove from controller if already present
4748             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4749             continue;
4750         }
4751         // direclty remove entry from whitelist
4752         btstack_linked_list_iterator_remove(&it);
4753         btstack_memory_whitelist_entry_free(entry);
4754     }
4755 }
4756 
4757 /**
4758  * @brief Auto Connection Establishment - Stop Connecting to device
4759  * @param address_typ
4760  * @param address
4761  * @returns 0 if ok
4762  */
4763 int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){
4764     hci_remove_from_whitelist(address_type, address);
4765     hci_run();
4766     return 0;
4767 }
4768 
4769 /**
4770  * @brief Auto Connection Establishment - Stop everything
4771  * @note  Convenience function to stop all active auto connection attempts
4772  */
4773 void gap_auto_connection_stop_all(void){
4774     btstack_linked_list_iterator_t it;
4775     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4776     while (btstack_linked_list_iterator_has_next(&it)){
4777         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4778         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4779             // remove from controller if already present
4780             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4781             continue;
4782         }
4783         // directly remove entry from whitelist
4784         btstack_linked_list_iterator_remove(&it);
4785         btstack_memory_whitelist_entry_free(entry);
4786     }
4787     hci_run();
4788 }
4789 
4790 uint16_t gap_le_connection_interval(hci_con_handle_t connection_handle){
4791     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4792     if (!conn) return 0;
4793     return conn->le_connection_interval;
4794 }
4795 #endif
4796 #endif
4797 
4798 #ifdef ENABLE_CLASSIC
4799 /**
4800  * @brief Set Extended Inquiry Response data
4801  * @param eir_data size 240 bytes, is not copied make sure memory is accessible during stack startup
4802  * @note has to be done before stack starts up
4803  */
4804 void gap_set_extended_inquiry_response(const uint8_t * data){
4805     hci_stack->eir_data = data;
4806 }
4807 
4808 /**
4809  * @brief Start GAP Classic Inquiry
4810  * @param duration in 1.28s units
4811  * @return 0 if ok
4812  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
4813  */
4814 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
4815     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
4816     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4817     if (duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN || duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX){
4818         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
4819     }
4820     hci_stack->inquiry_state = duration_in_1280ms_units;
4821     hci_run();
4822     return 0;
4823 }
4824 
4825 /**
4826  * @brief Stop GAP Classic Inquiry
4827  * @returns 0 if ok
4828  */
4829 int gap_inquiry_stop(void){
4830     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN && hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX) {
4831         // emit inquiry complete event, before it even started
4832         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
4833         hci_emit_event(event, sizeof(event), 1);
4834         return 0;
4835     }
4836     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
4837     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
4838     hci_run();
4839     return 0;
4840 }
4841 
4842 
4843 /**
4844  * @brief Remote Name Request
4845  * @param addr
4846  * @param page_scan_repetition_mode
4847  * @param clock_offset only used when bit 15 is set
4848  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
4849  */
4850 int gap_remote_name_request(bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
4851     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4852     memcpy(hci_stack->remote_name_addr, addr, 6);
4853     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
4854     hci_stack->remote_name_clock_offset = clock_offset;
4855     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
4856     hci_run();
4857     return 0;
4858 }
4859 
4860 static int gap_pairing_set_state_and_run(bd_addr_t addr, uint8_t state){
4861     hci_stack->gap_pairing_state = state;
4862     memcpy(hci_stack->gap_pairing_addr, addr, 6);
4863     hci_run();
4864     return 0;
4865 }
4866 
4867 /**
4868  * @brief Legacy Pairing Pin Code Response
4869  * @param addr
4870  * @param pin
4871  * @return 0 if ok
4872  */
4873 int gap_pin_code_response(bd_addr_t addr, const char * pin){
4874     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4875     hci_stack->gap_pairing_input.gap_pairing_pin = pin;
4876     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
4877 }
4878 
4879 /**
4880  * @brief Abort Legacy Pairing
4881  * @param addr
4882  * @param pin
4883  * @return 0 if ok
4884  */
4885 int gap_pin_code_negative(bd_addr_t addr){
4886     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4887     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
4888 }
4889 
4890 /**
4891  * @brief SSP Passkey Response
4892  * @param addr
4893  * @param passkey
4894  * @return 0 if ok
4895  */
4896 int gap_ssp_passkey_response(bd_addr_t addr, uint32_t passkey){
4897     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4898     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
4899     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
4900 }
4901 
4902 /**
4903  * @brief Abort SSP Passkey Entry/Pairing
4904  * @param addr
4905  * @param pin
4906  * @return 0 if ok
4907  */
4908 int gap_ssp_passkey_negative(bd_addr_t addr){
4909     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4910     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
4911 }
4912 
4913 /**
4914  * @brief Accept SSP Numeric Comparison
4915  * @param addr
4916  * @param passkey
4917  * @return 0 if ok
4918  */
4919 int gap_ssp_confirmation_response(bd_addr_t addr){
4920     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4921     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
4922 }
4923 
4924 /**
4925  * @brief Abort SSP Numeric Comparison/Pairing
4926  * @param addr
4927  * @param pin
4928  * @return 0 if ok
4929  */
4930 int gap_ssp_confirmation_negative(bd_addr_t addr){
4931     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4932     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
4933 }
4934 
4935 /**
4936  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
4937  * @param inquiry_mode see bluetooth_defines.h
4938  */
4939 void hci_set_inquiry_mode(inquiry_mode_t mode){
4940     hci_stack->inquiry_mode = mode;
4941 }
4942 
4943 /**
4944  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
4945  */
4946 void hci_set_sco_voice_setting(uint16_t voice_setting){
4947     hci_stack->sco_voice_setting = voice_setting;
4948 }
4949 
4950 /**
4951  * @brief Get SCO Voice Setting
4952  * @return current voice setting
4953  */
4954 uint16_t hci_get_sco_voice_setting(void){
4955     return hci_stack->sco_voice_setting;
4956 }
4957 
4958 #ifdef ENABLE_CLASSIC
4959 #ifdef ENABLE_SCO_OVER_HCI
4960 static int hci_have_usb_transport(void){
4961     if (!hci_stack->hci_transport) return 0;
4962     const char * transport_name = hci_stack->hci_transport->name;
4963     if (!transport_name) return 0;
4964     return (transport_name[0] == 'H') && (transport_name[1] == '2');
4965 }
4966 #endif
4967 #endif
4968 
4969 /** @brief Get SCO packet length for current SCO Voice setting
4970  *  @note  Using SCO packets of the exact length is required for USB transfer
4971  *  @return Length of SCO packets in bytes (not audio frames)
4972  */
4973 int hci_get_sco_packet_length(void){
4974     int sco_packet_length = 0;
4975 
4976 #ifdef ENABLE_CLASSIC
4977 #ifdef ENABLE_SCO_OVER_HCI
4978 
4979     // Transparent = mSBC => 1, CVSD with 16-bit samples requires twice as much bytes
4980     int multiplier = ((hci_stack->sco_voice_setting_active & 0x03) == 0x03) ? 1 : 2;
4981 
4982     if (hci_have_usb_transport()){
4983         // see Core Spec for H2 USB Transfer.
4984         // 3 byte SCO header + 24 bytes per connection
4985         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
4986         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
4987     } else {
4988         // 3 byte SCO header + SCO packet size over the air (60 bytes)
4989         sco_packet_length = 3 + 60 * multiplier;
4990         // assert that it still fits inside an SCO buffer
4991         if (sco_packet_length > hci_stack->sco_data_packet_length){
4992             sco_packet_length = 3 + 60;
4993         }
4994     }
4995 #endif
4996 #endif
4997     return sco_packet_length;
4998 }
4999 
5000 /**
5001 * @brief Sets the master/slave policy
5002 * @param policy (0: attempt to become master, 1: let connecting device decide)
5003 */
5004 void hci_set_master_slave_policy(uint8_t policy){
5005     hci_stack->master_slave_policy = policy;
5006 }
5007 
5008 #endif
5009 
5010 HCI_STATE hci_get_state(void){
5011     return hci_stack->state;
5012 }
5013 
5014 
5015 /**
5016  * @brief Set callback for Bluetooth Hardware Error
5017  */
5018 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
5019     hci_stack->hardware_error_callback = fn;
5020 }
5021 
5022 void hci_disconnect_all(void){
5023     btstack_linked_list_iterator_t it;
5024     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
5025     while (btstack_linked_list_iterator_has_next(&it)){
5026         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
5027         if (con->state == SENT_DISCONNECT) continue;
5028         con->state = SEND_DISCONNECT;
5029     }
5030     hci_run();
5031 }
5032 
5033 uint16_t hci_get_manufacturer(void){
5034     return hci_stack->manufacturer;
5035 }
5036 
5037 #ifdef ENABLE_BLE
5038 
5039 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
5040     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
5041     if (!hci_con) return NULL;
5042     return &hci_con->sm_connection;
5043 }
5044 
5045 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
5046 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
5047 
5048 int gap_encryption_key_size(hci_con_handle_t con_handle){
5049     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5050     if (!sm_conn) return 0;     // wrong connection
5051     if (!sm_conn->sm_connection_encrypted) return 0;
5052     return sm_conn->sm_actual_encryption_key_size;
5053 }
5054 
5055 int gap_authenticated(hci_con_handle_t con_handle){
5056     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5057     if (!sm_conn) return 0;     // wrong connection
5058     if (!sm_conn->sm_connection_encrypted) return 0; // unencrypted connection cannot be authenticated
5059     return sm_conn->sm_connection_authenticated;
5060 }
5061 
5062 int gap_secure_connection(hci_con_handle_t con_handle){
5063     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5064     if (!sm_conn) return 0;     // wrong connection
5065     if (!sm_conn->sm_connection_encrypted) return 0; // unencrypted connection cannot be authenticated
5066     return sm_conn->sm_connection_sc;
5067 }
5068 
5069 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
5070     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5071     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
5072     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
5073     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
5074     return sm_conn->sm_connection_authorization_state;
5075 }
5076 #endif
5077 
5078 #ifdef ENABLE_CLASSIC
5079 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){
5080     hci_connection_t * conn = hci_connection_for_handle(con_handle);
5081     if (!conn) return GAP_CONNECTION_INVALID;
5082     conn->sniff_min_interval = sniff_min_interval;
5083     conn->sniff_max_interval = sniff_max_interval;
5084     conn->sniff_attempt = sniff_attempt;
5085     conn->sniff_timeout = sniff_timeout;
5086     hci_run();
5087     return 0;
5088 }
5089 
5090 /**
5091  * @brief Exit Sniff mode
5092  * @param con_handle
5093  @ @return 0 if ok
5094  */
5095 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
5096     hci_connection_t * conn = hci_connection_for_handle(con_handle);
5097     if (!conn) return GAP_CONNECTION_INVALID;
5098     conn->sniff_min_interval = 0xffff;
5099     hci_run();
5100     return 0;
5101 }
5102 #endif
5103 
5104 void hci_halting_defer(void){
5105     if (hci_stack->state != HCI_STATE_HALTING) return;
5106     switch (hci_stack->substate){
5107         case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
5108         case HCI_HALTING_CLOSE:
5109             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_TIMER;
5110             break;
5111         default:
5112             break;
5113     }
5114 }
5115