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