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