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