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