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