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