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