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