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