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