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