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