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