xref: /btstack/src/hci.c (revision 1cfb383e5600f0f096470a696c715ff0fac54bde)
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     uint8_t link_type;
1607     hci_con_handle_t handle;
1608     hci_connection_t * conn;
1609     int i;
1610 
1611     // warnings
1612     (void) link_type;
1613 
1614     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
1615 
1616     switch (hci_event_packet_get_type(packet)) {
1617 
1618         case HCI_EVENT_COMMAND_COMPLETE:
1619             // get num cmd packets - limit to 1 to reduce complexity
1620             hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
1621 
1622             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_name)){
1623                 if (packet[5]) break;
1624                 // terminate, name 248 chars
1625                 packet[6+248] = 0;
1626                 log_info("local name: %s", &packet[6]);
1627             }
1628             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_buffer_size)){
1629                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
1630                 if (hci_stack->state == HCI_STATE_INITIALIZING){
1631                     uint16_t acl_len = little_endian_read_16(packet, 6);
1632                     uint16_t sco_len = packet[8];
1633 
1634                     // determine usable ACL/SCO payload size
1635                     hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
1636                     hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
1637 
1638                     hci_stack->acl_packets_total_num  = little_endian_read_16(packet, 9);
1639                     hci_stack->sco_packets_total_num  = little_endian_read_16(packet, 11);
1640 
1641                     log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
1642                              acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
1643                              hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
1644                 }
1645             }
1646 #ifdef ENABLE_BLE
1647             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_buffer_size)){
1648                 hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
1649                 hci_stack->le_acl_packets_total_num  = packet[8];
1650                     // determine usable ACL payload size
1651                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
1652                         hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
1653                     }
1654                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
1655             }
1656 #ifdef ENABLE_LE_CENTRAL
1657             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_white_list_size)){
1658                 hci_stack->le_whitelist_capacity = packet[6];
1659                 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
1660             }
1661 #endif
1662 #endif
1663             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
1664                 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1],
1665 				hci_stack->local_bd_addr);
1666                 log_info("Local Address, Status: 0x%02x: Addr: %s",
1667                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
1668 #ifdef ENABLE_CLASSIC
1669                 if (hci_stack->link_key_db){
1670                     hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
1671                 }
1672 #endif
1673             }
1674 #ifdef ENABLE_CLASSIC
1675             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
1676                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1677             }
1678 #endif
1679 
1680             // Note: HCI init checks
1681             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_features)){
1682                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
1683 
1684 #ifdef ENABLE_CLASSIC
1685                 // determine usable ACL packet types based on host buffer size and supported features
1686                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
1687                 log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
1688 #endif
1689                 // Classic/LE
1690                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1691             }
1692             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_version_information)){
1693                 // hci_stack->hci_version    = little_endian_read_16(packet, 4);
1694                 // hci_stack->hci_revision   = little_endian_read_16(packet, 6);
1695                 // hci_stack->lmp_version    = little_endian_read_16(packet, 8);
1696                 hci_stack->manufacturer   = little_endian_read_16(packet, 10);
1697                 // hci_stack->lmp_subversion = little_endian_read_16(packet, 12);
1698                 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
1699             }
1700             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
1701                 hci_stack->local_supported_commands[0] =
1702                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+14] & 0x80) >> 7 |  // bit 0 = Octet 14, bit 7
1703                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+24] & 0x40) >> 5 |  // bit 1 = Octet 24, bit 6
1704                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+10] & 0x10) >> 2 |  // bit 2 = Octet 10, bit 4
1705                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+18] & 0x08);        // bit 3 = Octet 18, bit 3
1706                     log_info("Local supported commands summary 0x%02x", hci_stack->local_supported_commands[0]);
1707             }
1708 #ifdef ENABLE_CLASSIC
1709             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_synchronous_flow_control_enable)){
1710                 if (packet[5] == 0){
1711                     hci_stack->synchronous_flow_control_enabled = 1;
1712                 }
1713             }
1714 #endif
1715             break;
1716 
1717         case HCI_EVENT_COMMAND_STATUS:
1718             // get num cmd packets - limit to 1 to reduce complexity
1719             hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
1720             break;
1721 
1722         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
1723             int offset = 3;
1724             for (i=0; i<packet[2];i++){
1725                 handle = little_endian_read_16(packet, offset);
1726                 offset += 2;
1727                 uint16_t num_packets = little_endian_read_16(packet, offset);
1728                 offset += 2;
1729 
1730                 conn = hci_connection_for_handle(handle);
1731                 if (!conn){
1732                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
1733                     continue;
1734                 }
1735 
1736                 if (conn->address_type == BD_ADDR_TYPE_SCO){
1737 #ifdef ENABLE_CLASSIC
1738                     if (conn->num_sco_packets_sent >= num_packets){
1739                         conn->num_sco_packets_sent -= num_packets;
1740                     } else {
1741                         log_error("hci_number_completed_packets, more sco slots freed then sent.");
1742                         conn->num_sco_packets_sent = 0;
1743                     }
1744                     hci_notify_if_sco_can_send_now();
1745 #endif
1746                 } else {
1747                     if (conn->num_acl_packets_sent >= num_packets){
1748                         conn->num_acl_packets_sent -= num_packets;
1749                     } else {
1750                         log_error("hci_number_completed_packets, more acl slots freed then sent.");
1751                         conn->num_acl_packets_sent = 0;
1752                     }
1753                 }
1754                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
1755             }
1756             break;
1757         }
1758 
1759 #ifdef ENABLE_CLASSIC
1760         case HCI_EVENT_CONNECTION_REQUEST:
1761             reverse_bd_addr(&packet[2], addr);
1762             // TODO: eval COD 8-10
1763             link_type = packet[11];
1764             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
1765             addr_type = link_type == 1 ? BD_ADDR_TYPE_CLASSIC : BD_ADDR_TYPE_SCO;
1766             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1767             if (!conn) {
1768                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1769             }
1770             if (!conn) {
1771                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
1772                 hci_stack->decline_reason = 0x0d;
1773                 bd_addr_copy(hci_stack->decline_addr, addr);
1774                 break;
1775             }
1776             conn->role  = HCI_ROLE_SLAVE;
1777             conn->state = RECEIVED_CONNECTION_REQUEST;
1778             // store info about eSCO
1779             if (link_type == 0x02){
1780                 conn->remote_supported_feature_eSCO = 1;
1781             }
1782             hci_run();
1783             break;
1784 
1785         case HCI_EVENT_CONNECTION_COMPLETE:
1786             // Connection management
1787             reverse_bd_addr(&packet[5], addr);
1788             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1789             addr_type = BD_ADDR_TYPE_CLASSIC;
1790             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1791             if (conn) {
1792                 if (!packet[2]){
1793                     conn->state = OPEN;
1794                     conn->con_handle = little_endian_read_16(packet, 3);
1795                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
1796 
1797                     // restart timer
1798                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1799                     btstack_run_loop_add_timer(&conn->timeout);
1800 
1801                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1802 
1803                     hci_emit_nr_connections_changed();
1804                 } else {
1805                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
1806                     uint8_t status = packet[2];
1807                     bd_addr_t bd_address;
1808                     memcpy(&bd_address, conn->address, 6);
1809 
1810                     // connection failed, remove entry
1811                     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1812                     btstack_memory_hci_connection_free( conn );
1813 
1814                     // notify client if dedicated bonding
1815                     if (notify_dedicated_bonding_failed){
1816                         log_info("hci notify_dedicated_bonding_failed");
1817                         hci_emit_dedicated_bonding_result(bd_address, status);
1818                     }
1819 
1820                     // if authentication error, also delete link key
1821                     if (packet[2] == 0x05) {
1822                         gap_drop_link_key_for_bd_addr(addr);
1823                     }
1824                 }
1825             }
1826             break;
1827 
1828         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
1829             reverse_bd_addr(&packet[5], addr);
1830             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1831             if (packet[2]){
1832                 // connection failed
1833                 break;
1834             }
1835             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1836             if (!conn) {
1837                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1838             }
1839             if (!conn) {
1840                 break;
1841             }
1842             conn->state = OPEN;
1843             conn->con_handle = little_endian_read_16(packet, 3);
1844 
1845 #ifdef ENABLE_SCO_OVER_HCI
1846             // update SCO
1847             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
1848                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
1849             }
1850 #endif
1851             break;
1852 
1853         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1854             handle = little_endian_read_16(packet, 3);
1855             conn = hci_connection_for_handle(handle);
1856             if (!conn) break;
1857             if (!packet[2]){
1858                 uint8_t * features = &packet[5];
1859                 if (features[6] & (1 << 3)){
1860                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
1861                 }
1862                 if (features[3] & (1<<7)){
1863                     conn->remote_supported_feature_eSCO = 1;
1864                 }
1865             }
1866             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
1867             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x, eSCO %u", conn->bonding_flags, conn->remote_supported_feature_eSCO);
1868             if (conn->bonding_flags & BONDING_DEDICATED){
1869                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1870             }
1871             break;
1872 
1873         case HCI_EVENT_LINK_KEY_REQUEST:
1874             log_info("HCI_EVENT_LINK_KEY_REQUEST");
1875             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
1876             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
1877             if (hci_stack->bondable && !hci_stack->link_key_db) break;
1878             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
1879             hci_run();
1880             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
1881             return;
1882 
1883         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
1884             reverse_bd_addr(&packet[2], addr);
1885             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
1886             if (!conn) break;
1887             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
1888             link_key_type_t link_key_type = (link_key_type_t)packet[24];
1889             // Change Connection Encryption keeps link key type
1890             if (link_key_type != CHANGED_COMBINATION_KEY){
1891                 conn->link_key_type = link_key_type;
1892             }
1893             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
1894             // still forward event to allow dismiss of pairing dialog
1895             break;
1896         }
1897 
1898         case HCI_EVENT_PIN_CODE_REQUEST:
1899             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
1900             // non-bondable mode: pin code negative reply will be sent
1901             if (!hci_stack->bondable){
1902                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
1903                 hci_run();
1904                 return;
1905             }
1906             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
1907             if (!hci_stack->link_key_db) break;
1908             hci_event_pin_code_request_get_bd_addr(packet, addr);
1909             hci_stack->link_key_db->delete_link_key(addr);
1910             break;
1911 
1912         case HCI_EVENT_IO_CAPABILITY_REQUEST:
1913             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
1914             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
1915             break;
1916 
1917         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
1918             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1919             if (!hci_stack->ssp_auto_accept) break;
1920             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
1921             break;
1922 
1923         case HCI_EVENT_USER_PASSKEY_REQUEST:
1924             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1925             if (!hci_stack->ssp_auto_accept) break;
1926             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
1927             break;
1928 #endif
1929 
1930         case HCI_EVENT_ENCRYPTION_CHANGE:
1931             handle = little_endian_read_16(packet, 3);
1932             conn = hci_connection_for_handle(handle);
1933             if (!conn) break;
1934             if (packet[2] == 0) {
1935                 if (packet[5]){
1936                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
1937                 } else {
1938                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
1939                 }
1940             }
1941 #ifdef ENABLE_CLASSIC
1942             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1943 #endif
1944             break;
1945 
1946 #ifdef ENABLE_CLASSIC
1947         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
1948             handle = little_endian_read_16(packet, 3);
1949             conn = hci_connection_for_handle(handle);
1950             if (!conn) break;
1951 
1952             // dedicated bonding: send result and disconnect
1953             if (conn->bonding_flags & BONDING_DEDICATED){
1954                 conn->bonding_flags &= ~BONDING_DEDICATED;
1955                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
1956                 conn->bonding_status = packet[2];
1957                 break;
1958             }
1959 
1960             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
1961                 // link key sufficient for requested security
1962                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
1963                 break;
1964             }
1965             // not enough
1966             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1967             break;
1968 #endif
1969 
1970         // HCI_EVENT_DISCONNECTION_COMPLETE
1971         // has been split, to first notify stack before shutting connection down
1972         // see end of function, too.
1973         case HCI_EVENT_DISCONNECTION_COMPLETE:
1974             if (packet[2]) break;   // status != 0
1975             handle = little_endian_read_16(packet, 3);
1976             // drop outgoing ACL fragments if it is for closed connection
1977             if (hci_stack->acl_fragmentation_total_size > 0) {
1978                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
1979                     log_info("hci: drop fragmented ACL data for closed connection");
1980                      hci_stack->acl_fragmentation_total_size = 0;
1981                      hci_stack->acl_fragmentation_pos = 0;
1982                 }
1983             }
1984 
1985             // re-enable advertisements for le connections if active
1986             conn = hci_connection_for_handle(handle);
1987             if (!conn) break;
1988 #ifdef ENABLE_BLE
1989 #ifdef ENABLE_LE_PERIPHERAL
1990             if (hci_is_le_connection(conn) && hci_stack->le_advertisements_enabled){
1991                 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
1992             }
1993 #endif
1994 #endif
1995             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
1996             break;
1997 
1998         case HCI_EVENT_HARDWARE_ERROR:
1999             log_error("Hardware Error: 0x%02x", packet[2]);
2000             if (hci_stack->hardware_error_callback){
2001                 (*hci_stack->hardware_error_callback)(packet[2]);
2002             } else {
2003                 // if no special requests, just reboot stack
2004                 hci_power_control_off();
2005                 hci_power_control_on();
2006             }
2007             break;
2008 
2009 #ifdef ENABLE_CLASSIC
2010         case HCI_EVENT_ROLE_CHANGE:
2011             if (packet[2]) break;   // status != 0
2012             handle = little_endian_read_16(packet, 3);
2013             conn = hci_connection_for_handle(handle);
2014             if (!conn) break;       // no conn
2015             conn->role = packet[9];
2016             break;
2017 #endif
2018 
2019         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2020             // release packet buffer only for asynchronous transport and if there are not further fragements
2021             if (hci_transport_synchronous()) {
2022                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
2023                 return; // instead of break: to avoid re-entering hci_run()
2024             }
2025             if (hci_stack->acl_fragmentation_total_size) break;
2026             hci_release_packet_buffer();
2027 
2028             // L2CAP receives this event via the hci_emit_event below
2029 
2030 #ifdef ENABLE_CLASSIC
2031             // For SCO, we do the can_send_now_check here
2032             hci_notify_if_sco_can_send_now();
2033 #endif
2034             break;
2035 
2036 #ifdef ENABLE_CLASSIC
2037         case HCI_EVENT_SCO_CAN_SEND_NOW:
2038             // For SCO, we do the can_send_now_check here
2039             hci_notify_if_sco_can_send_now();
2040             return;
2041 
2042         // explode inquriy results for easier consumption
2043         case HCI_EVENT_INQUIRY_RESULT:
2044         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
2045         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
2046             gap_inquiry_explode(packet);
2047             break;
2048 #endif
2049 
2050 #ifdef ENABLE_BLE
2051         case HCI_EVENT_LE_META:
2052             switch (packet[2]){
2053 #ifdef ENABLE_LE_CENTRAL
2054                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
2055                     // log_info("advertising report received");
2056                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
2057                     le_handle_advertisement_report(packet, size);
2058                     break;
2059 #endif
2060                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
2061                     // Connection management
2062                     reverse_bd_addr(&packet[8], addr);
2063                     addr_type = (bd_addr_type_t)packet[7];
2064                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
2065                     conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2066 #ifdef ENABLE_LE_CENTRAL
2067                     // if auto-connect, remove from whitelist in both roles
2068                     if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){
2069                         hci_remove_from_whitelist(addr_type, addr);
2070                     }
2071                     // handle error: error is reported only to the initiator -> outgoing connection
2072                     if (packet[3]){
2073                         // outgoing connection establishment is done
2074                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2075                         // remove entry
2076                         if (conn){
2077                             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2078                             btstack_memory_hci_connection_free( conn );
2079                         }
2080                         break;
2081                     }
2082 #endif
2083                     // on success, both hosts receive connection complete event
2084                     if (packet[6] == HCI_ROLE_MASTER){
2085 #ifdef ENABLE_LE_CENTRAL
2086                         // if we're master, it was an outgoing connection and we're done with it
2087                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2088 #endif
2089                     } else {
2090 #ifdef ENABLE_LE_PERIPHERAL
2091                         // if we're slave, it was an incoming connection, advertisements have stopped
2092                         hci_stack->le_advertisements_active = 0;
2093                         // try to re-enable them
2094                         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
2095 #endif
2096                     }
2097                     // LE connections are auto-accepted, so just create a connection if there isn't one already
2098                     if (!conn){
2099                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2100                     }
2101                     // no memory, sorry.
2102                     if (!conn){
2103                         break;
2104                     }
2105 
2106                     conn->state = OPEN;
2107                     conn->role  = packet[6];
2108                     conn->con_handle = little_endian_read_16(packet, 4);
2109 
2110                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
2111 
2112                     // restart timer
2113                     // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2114                     // btstack_run_loop_add_timer(&conn->timeout);
2115 
2116                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2117 
2118                     hci_emit_nr_connections_changed();
2119                     break;
2120 
2121             // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
2122 
2123                 default:
2124                     break;
2125             }
2126             break;
2127 #endif
2128         default:
2129             break;
2130     }
2131 
2132     // handle BT initialization
2133     if (hci_stack->state == HCI_STATE_INITIALIZING){
2134         hci_initializing_event_handler(packet, size);
2135     }
2136 
2137     // help with BT sleep
2138     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
2139         && hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE
2140         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
2141         hci_initializing_next_state();
2142     }
2143 
2144     // notify upper stack
2145 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
2146 
2147     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
2148     if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){
2149         if (!packet[2]){
2150             handle = little_endian_read_16(packet, 3);
2151             hci_connection_t * aConn = hci_connection_for_handle(handle);
2152             if (aConn) {
2153                 uint8_t status = aConn->bonding_status;
2154                 uint16_t flags = aConn->bonding_flags;
2155                 bd_addr_t bd_address;
2156                 memcpy(&bd_address, aConn->address, 6);
2157                 hci_shutdown_connection(aConn);
2158                 // connection struct is gone, don't access anymore
2159                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
2160                     hci_emit_dedicated_bonding_result(bd_address, status);
2161                 }
2162             }
2163         }
2164     }
2165 
2166 	// execute main loop
2167 	hci_run();
2168 }
2169 
2170 #ifdef ENABLE_CLASSIC
2171 static void sco_handler(uint8_t * packet, uint16_t size){
2172     if (!hci_stack->sco_packet_handler) return;
2173     hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
2174 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2175     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
2176     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
2177     if (conn){
2178         conn->num_packets_completed++;
2179         hci_stack->host_completed_packets = 1;
2180         hci_run();
2181     }
2182 #endif
2183 }
2184 #endif
2185 
2186 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
2187     hci_dump_packet(packet_type, 1, packet, size);
2188     switch (packet_type) {
2189         case HCI_EVENT_PACKET:
2190             event_handler(packet, size);
2191             break;
2192         case HCI_ACL_DATA_PACKET:
2193             acl_handler(packet, size);
2194             break;
2195 #ifdef ENABLE_CLASSIC
2196         case HCI_SCO_DATA_PACKET:
2197             sco_handler(packet, size);
2198             break;
2199 #endif
2200         default:
2201             break;
2202     }
2203 }
2204 
2205 /**
2206  * @brief Add event packet handler.
2207  */
2208 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
2209     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
2210 }
2211 
2212 
2213 /** Register HCI packet handlers */
2214 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
2215     hci_stack->acl_packet_handler = handler;
2216 }
2217 
2218 #ifdef ENABLE_CLASSIC
2219 /**
2220  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
2221  */
2222 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
2223     hci_stack->sco_packet_handler = handler;
2224 }
2225 #endif
2226 
2227 static void hci_state_reset(void){
2228     // no connections yet
2229     hci_stack->connections = NULL;
2230 
2231     // keep discoverable/connectable as this has been requested by the client(s)
2232     // hci_stack->discoverable = 0;
2233     // hci_stack->connectable = 0;
2234     // hci_stack->bondable = 1;
2235     // hci_stack->own_addr_type = 0;
2236 
2237     // buffer is free
2238     hci_stack->hci_packet_buffer_reserved = 0;
2239 
2240     // no pending cmds
2241     hci_stack->decline_reason = 0;
2242     hci_stack->new_scan_enable_value = 0xff;
2243 
2244     // LE
2245 #ifdef ENABLE_BLE
2246     memset(hci_stack->le_random_address, 0, 6);
2247     hci_stack->le_random_address_set = 0;
2248 #endif
2249 #ifdef ENABLE_LE_CENTRAL
2250     hci_stack->le_scanning_state = LE_SCAN_IDLE;
2251     hci_stack->le_scan_type = 0xff;
2252     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2253     hci_stack->le_whitelist = 0;
2254     hci_stack->le_whitelist_capacity = 0;
2255 #endif
2256 
2257     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
2258     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
2259     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
2260     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
2261     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
2262     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
2263 }
2264 
2265 #ifdef ENABLE_CLASSIC
2266 /**
2267  * @brief Configure Bluetooth hardware control. Has to be called before power on.
2268  */
2269 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
2270     // store and open remote device db
2271     hci_stack->link_key_db = link_key_db;
2272     if (hci_stack->link_key_db) {
2273         hci_stack->link_key_db->open();
2274     }
2275 }
2276 #endif
2277 
2278 void hci_init(const hci_transport_t *transport, const void *config){
2279 
2280 #ifdef HAVE_MALLOC
2281     if (!hci_stack) {
2282         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
2283     }
2284 #else
2285     hci_stack = &hci_stack_static;
2286 #endif
2287     memset(hci_stack, 0, sizeof(hci_stack_t));
2288 
2289     // reference to use transport layer implementation
2290     hci_stack->hci_transport = transport;
2291 
2292     // reference to used config
2293     hci_stack->config = config;
2294 
2295     // setup pointer for outgoing packet buffer
2296     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
2297 
2298     // max acl payload size defined in config.h
2299     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
2300 
2301     // register packet handlers with transport
2302     transport->register_packet_handler(&packet_handler);
2303 
2304     hci_stack->state = HCI_STATE_OFF;
2305 
2306     // class of device
2307     hci_stack->class_of_device = 0x007a020c; // Smartphone
2308 
2309     // bondable by default
2310     hci_stack->bondable = 1;
2311 
2312     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
2313     hci_stack->ssp_enable = 1;
2314     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
2315     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
2316     hci_stack->ssp_auto_accept = 1;
2317 
2318     // voice setting - signed 16 bit pcm data with CVSD over the air
2319     hci_stack->sco_voice_setting = 0x60;
2320 
2321     hci_state_reset();
2322 }
2323 
2324 /**
2325  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
2326  */
2327 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
2328     hci_stack->chipset = chipset_driver;
2329 
2330     // reset chipset driver - init is also called on power_up
2331     if (hci_stack->chipset && hci_stack->chipset->init){
2332         hci_stack->chipset->init(hci_stack->config);
2333     }
2334 }
2335 
2336 /**
2337  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
2338  */
2339 void hci_set_control(const btstack_control_t *hardware_control){
2340     // references to used control implementation
2341     hci_stack->control = hardware_control;
2342     // init with transport config
2343     hardware_control->init(hci_stack->config);
2344 }
2345 
2346 void hci_close(void){
2347     // close remote device db
2348     if (hci_stack->link_key_db) {
2349         hci_stack->link_key_db->close();
2350     }
2351 
2352     btstack_linked_list_iterator_t lit;
2353     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
2354     while (btstack_linked_list_iterator_has_next(&lit)){
2355         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
2356         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
2357         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
2358         hci_shutdown_connection(connection);
2359     }
2360 
2361     hci_power_control(HCI_POWER_OFF);
2362 
2363 #ifdef HAVE_MALLOC
2364     free(hci_stack);
2365 #endif
2366     hci_stack = NULL;
2367 }
2368 
2369 #ifdef ENABLE_CLASSIC
2370 void gap_set_class_of_device(uint32_t class_of_device){
2371     hci_stack->class_of_device = class_of_device;
2372 }
2373 
2374 void hci_disable_l2cap_timeout_check(void){
2375     disable_l2cap_timeouts = 1;
2376 }
2377 #endif
2378 
2379 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
2380 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
2381 void hci_set_bd_addr(bd_addr_t addr){
2382     memcpy(hci_stack->custom_bd_addr, addr, 6);
2383     hci_stack->custom_bd_addr_set = 1;
2384 }
2385 #endif
2386 
2387 // State-Module-Driver overview
2388 // state                    module  low-level
2389 // HCI_STATE_OFF             off      close
2390 // HCI_STATE_INITIALIZING,   on       open
2391 // HCI_STATE_WORKING,        on       open
2392 // HCI_STATE_HALTING,        on       open
2393 // HCI_STATE_SLEEPING,    off/sleep   close
2394 // HCI_STATE_FALLING_ASLEEP  on       open
2395 
2396 static int hci_power_control_on(void){
2397 
2398     // power on
2399     int err = 0;
2400     if (hci_stack->control && hci_stack->control->on){
2401         err = (*hci_stack->control->on)();
2402     }
2403     if (err){
2404         log_error( "POWER_ON failed");
2405         hci_emit_hci_open_failed();
2406         return err;
2407     }
2408 
2409     // int chipset driver
2410     if (hci_stack->chipset && hci_stack->chipset->init){
2411         hci_stack->chipset->init(hci_stack->config);
2412     }
2413 
2414     // init transport
2415     if (hci_stack->hci_transport->init){
2416         hci_stack->hci_transport->init(hci_stack->config);
2417     }
2418 
2419     // open transport
2420     err = hci_stack->hci_transport->open();
2421     if (err){
2422         log_error( "HCI_INIT failed, turning Bluetooth off again");
2423         if (hci_stack->control && hci_stack->control->off){
2424             (*hci_stack->control->off)();
2425         }
2426         hci_emit_hci_open_failed();
2427         return err;
2428     }
2429     return 0;
2430 }
2431 
2432 static void hci_power_control_off(void){
2433 
2434     log_info("hci_power_control_off");
2435 
2436     // close low-level device
2437     hci_stack->hci_transport->close();
2438 
2439     log_info("hci_power_control_off - hci_transport closed");
2440 
2441     // power off
2442     if (hci_stack->control && hci_stack->control->off){
2443         (*hci_stack->control->off)();
2444     }
2445 
2446     log_info("hci_power_control_off - control closed");
2447 
2448     hci_stack->state = HCI_STATE_OFF;
2449 }
2450 
2451 static void hci_power_control_sleep(void){
2452 
2453     log_info("hci_power_control_sleep");
2454 
2455 #if 0
2456     // don't close serial port during sleep
2457 
2458     // close low-level device
2459     hci_stack->hci_transport->close(hci_stack->config);
2460 #endif
2461 
2462     // sleep mode
2463     if (hci_stack->control && hci_stack->control->sleep){
2464         (*hci_stack->control->sleep)();
2465     }
2466 
2467     hci_stack->state = HCI_STATE_SLEEPING;
2468 }
2469 
2470 static int hci_power_control_wake(void){
2471 
2472     log_info("hci_power_control_wake");
2473 
2474     // wake on
2475     if (hci_stack->control && hci_stack->control->wake){
2476         (*hci_stack->control->wake)();
2477     }
2478 
2479 #if 0
2480     // open low-level device
2481     int err = hci_stack->hci_transport->open(hci_stack->config);
2482     if (err){
2483         log_error( "HCI_INIT failed, turning Bluetooth off again");
2484         if (hci_stack->control && hci_stack->control->off){
2485             (*hci_stack->control->off)();
2486         }
2487         hci_emit_hci_open_failed();
2488         return err;
2489     }
2490 #endif
2491 
2492     return 0;
2493 }
2494 
2495 static void hci_power_transition_to_initializing(void){
2496     // set up state machine
2497     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
2498     hci_stack->hci_packet_buffer_reserved = 0;
2499     hci_stack->state = HCI_STATE_INITIALIZING;
2500     hci_stack->substate = HCI_INIT_SEND_RESET;
2501 }
2502 
2503 int hci_power_control(HCI_POWER_MODE power_mode){
2504 
2505     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
2506 
2507     int err = 0;
2508     switch (hci_stack->state){
2509 
2510         case HCI_STATE_OFF:
2511             switch (power_mode){
2512                 case HCI_POWER_ON:
2513                     err = hci_power_control_on();
2514                     if (err) {
2515                         log_error("hci_power_control_on() error %d", err);
2516                         return err;
2517                     }
2518                     hci_power_transition_to_initializing();
2519                     break;
2520                 case HCI_POWER_OFF:
2521                     // do nothing
2522                     break;
2523                 case HCI_POWER_SLEEP:
2524                     // do nothing (with SLEEP == OFF)
2525                     break;
2526             }
2527             break;
2528 
2529         case HCI_STATE_INITIALIZING:
2530             switch (power_mode){
2531                 case HCI_POWER_ON:
2532                     // do nothing
2533                     break;
2534                 case HCI_POWER_OFF:
2535                     // no connections yet, just turn it off
2536                     hci_power_control_off();
2537                     break;
2538                 case HCI_POWER_SLEEP:
2539                     // no connections yet, just turn it off
2540                     hci_power_control_sleep();
2541                     break;
2542             }
2543             break;
2544 
2545         case HCI_STATE_WORKING:
2546             switch (power_mode){
2547                 case HCI_POWER_ON:
2548                     // do nothing
2549                     break;
2550                 case HCI_POWER_OFF:
2551                     // see hci_run
2552                     hci_stack->state = HCI_STATE_HALTING;
2553                     break;
2554                 case HCI_POWER_SLEEP:
2555                     // see hci_run
2556                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2557                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2558                     break;
2559             }
2560             break;
2561 
2562         case HCI_STATE_HALTING:
2563             switch (power_mode){
2564                 case HCI_POWER_ON:
2565                     hci_power_transition_to_initializing();
2566                     break;
2567                 case HCI_POWER_OFF:
2568                     // do nothing
2569                     break;
2570                 case HCI_POWER_SLEEP:
2571                     // see hci_run
2572                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2573                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2574                     break;
2575             }
2576             break;
2577 
2578         case HCI_STATE_FALLING_ASLEEP:
2579             switch (power_mode){
2580                 case HCI_POWER_ON:
2581 
2582 #ifdef HAVE_PLATFORM_IPHONE_OS
2583                     // nothing to do, if H4 supports power management
2584                     if (btstack_control_iphone_power_management_enabled()){
2585                         hci_stack->state = HCI_STATE_INITIALIZING;
2586                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
2587                         break;
2588                     }
2589 #endif
2590                     hci_power_transition_to_initializing();
2591                     break;
2592                 case HCI_POWER_OFF:
2593                     // see hci_run
2594                     hci_stack->state = HCI_STATE_HALTING;
2595                     break;
2596                 case HCI_POWER_SLEEP:
2597                     // do nothing
2598                     break;
2599             }
2600             break;
2601 
2602         case HCI_STATE_SLEEPING:
2603             switch (power_mode){
2604                 case HCI_POWER_ON:
2605 
2606 #ifdef HAVE_PLATFORM_IPHONE_OS
2607                     // nothing to do, if H4 supports power management
2608                     if (btstack_control_iphone_power_management_enabled()){
2609                         hci_stack->state = HCI_STATE_INITIALIZING;
2610                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
2611                         hci_update_scan_enable();
2612                         break;
2613                     }
2614 #endif
2615                     err = hci_power_control_wake();
2616                     if (err) return err;
2617                     hci_power_transition_to_initializing();
2618                     break;
2619                 case HCI_POWER_OFF:
2620                     hci_stack->state = HCI_STATE_HALTING;
2621                     break;
2622                 case HCI_POWER_SLEEP:
2623                     // do nothing
2624                     break;
2625             }
2626             break;
2627     }
2628 
2629     // create internal event
2630 	hci_emit_state();
2631 
2632 	// trigger next/first action
2633 	hci_run();
2634 
2635     return 0;
2636 }
2637 
2638 
2639 #ifdef ENABLE_CLASSIC
2640 
2641 static void hci_update_scan_enable(void){
2642     // 2 = page scan, 1 = inq scan
2643     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
2644     hci_run();
2645 }
2646 
2647 void gap_discoverable_control(uint8_t enable){
2648     if (enable) enable = 1; // normalize argument
2649 
2650     if (hci_stack->discoverable == enable){
2651         hci_emit_discoverable_enabled(hci_stack->discoverable);
2652         return;
2653     }
2654 
2655     hci_stack->discoverable = enable;
2656     hci_update_scan_enable();
2657 }
2658 
2659 void gap_connectable_control(uint8_t enable){
2660     if (enable) enable = 1; // normalize argument
2661 
2662     // don't emit event
2663     if (hci_stack->connectable == enable) return;
2664 
2665     hci_stack->connectable = enable;
2666     hci_update_scan_enable();
2667 }
2668 #endif
2669 
2670 void gap_local_bd_addr(bd_addr_t address_buffer){
2671     memcpy(address_buffer, hci_stack->local_bd_addr, 6);
2672 }
2673 
2674 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2675 static void hci_host_num_completed_packets(void){
2676 
2677     // create packet manually as arrays are not supported and num_commands should not get reduced
2678     hci_reserve_packet_buffer();
2679     uint8_t * packet = hci_get_outgoing_packet_buffer();
2680 
2681     uint16_t size = 0;
2682     uint16_t num_handles = 0;
2683     packet[size++] = 0x35;
2684     packet[size++] = 0x0c;
2685     size++;  // skip param len
2686     size++;  // skip num handles
2687 
2688     // add { handle, packets } entries
2689     btstack_linked_item_t * it;
2690     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
2691         hci_connection_t * connection = (hci_connection_t *) it;
2692         if (connection->num_packets_completed){
2693             little_endian_store_16(packet, size, connection->con_handle);
2694             size += 2;
2695             little_endian_store_16(packet, size, connection->num_packets_completed);
2696             size += 2;
2697             //
2698             num_handles++;
2699             connection->num_packets_completed = 0;
2700         }
2701     }
2702 
2703     packet[2] = size - 3;
2704     packet[3] = num_handles;
2705 
2706     hci_stack->host_completed_packets = 0;
2707 
2708     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
2709     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
2710 
2711     // release packet buffer for synchronous transport implementations
2712     if (hci_transport_synchronous()){
2713         hci_stack->hci_packet_buffer_reserved = 0;
2714     }
2715 }
2716 #endif
2717 
2718 static void hci_run(void){
2719 
2720     // log_info("hci_run: entered");
2721     btstack_linked_item_t * it;
2722 
2723     // send continuation fragments first, as they block the prepared packet buffer
2724     if (hci_stack->acl_fragmentation_total_size > 0) {
2725         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
2726         hci_connection_t *connection = hci_connection_for_handle(con_handle);
2727         if (connection) {
2728             if (hci_can_send_prepared_acl_packet_now(con_handle)){
2729                 hci_send_acl_packet_fragments(connection);
2730                 return;
2731             }
2732         } else {
2733             // connection gone -> discard further fragments
2734             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
2735             hci_stack->acl_fragmentation_total_size = 0;
2736             hci_stack->acl_fragmentation_pos = 0;
2737         }
2738     }
2739 
2740 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2741     // send host num completed packets next as they don't require num_cmd_packets > 0
2742     if (!hci_can_send_comand_packet_transport()) return;
2743     if (hci_stack->host_completed_packets){
2744         hci_host_num_completed_packets();
2745         return;
2746     }
2747 #endif
2748 
2749     if (!hci_can_send_command_packet_now()) return;
2750 
2751     // global/non-connection oriented commands
2752 
2753 #ifdef ENABLE_CLASSIC
2754     // decline incoming connections
2755     if (hci_stack->decline_reason){
2756         uint8_t reason = hci_stack->decline_reason;
2757         hci_stack->decline_reason = 0;
2758         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
2759         return;
2760     }
2761 
2762     // send scan enable
2763     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
2764         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
2765         hci_stack->new_scan_enable_value = 0xff;
2766         return;
2767     }
2768 #endif
2769 
2770 #ifdef ENABLE_BLE
2771     // advertisements, active scanning, and creating connections requires randaom address to be set if using private address
2772     if ((hci_stack->state == HCI_STATE_WORKING)
2773     && (hci_stack->le_own_addr_type == BD_ADDR_TYPE_LE_PUBLIC || hci_stack->le_random_address_set)){
2774 
2775 #ifdef ENABLE_LE_CENTRAL
2776         // handle le scan
2777         switch(hci_stack->le_scanning_state){
2778             case LE_START_SCAN:
2779                 hci_stack->le_scanning_state = LE_SCANNING;
2780                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
2781                 return;
2782 
2783             case LE_STOP_SCAN:
2784                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
2785                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
2786                 return;
2787             default:
2788                 break;
2789         }
2790         if (hci_stack->le_scan_type != 0xff){
2791             // defaults: active scanning, accept all advertisement packets
2792             int scan_type = hci_stack->le_scan_type;
2793             hci_stack->le_scan_type = 0xff;
2794             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);
2795             return;
2796         }
2797 #endif
2798 #ifdef ENABLE_LE_PERIPHERAL
2799         // le advertisement control
2800         if (hci_stack->le_advertisements_todo){
2801             log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo );
2802         }
2803         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){
2804             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE;
2805             hci_send_cmd(&hci_le_set_advertise_enable, 0);
2806             return;
2807         }
2808         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
2809             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
2810             hci_send_cmd(&hci_le_set_advertising_parameters,
2811                  hci_stack->le_advertisements_interval_min,
2812                  hci_stack->le_advertisements_interval_max,
2813                  hci_stack->le_advertisements_type,
2814                  hci_stack->le_own_addr_type,
2815                  hci_stack->le_advertisements_direct_address_type,
2816                  hci_stack->le_advertisements_direct_address,
2817                  hci_stack->le_advertisements_channel_map,
2818                  hci_stack->le_advertisements_filter_policy);
2819             return;
2820         }
2821         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
2822             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
2823             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, hci_stack->le_advertisements_data);
2824             return;
2825         }
2826         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
2827             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
2828             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len,
2829                 hci_stack->le_scan_response_data);
2830             return;
2831         }
2832         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){
2833             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE;
2834             hci_send_cmd(&hci_le_set_advertise_enable, 1);
2835             return;
2836         }
2837 #endif
2838 
2839 #ifdef ENABLE_LE_CENTRAL
2840         //
2841         // LE Whitelist Management
2842         //
2843 
2844         // check if whitelist needs modification
2845         btstack_linked_list_iterator_t lit;
2846         int modification_pending = 0;
2847         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2848         while (btstack_linked_list_iterator_has_next(&lit)){
2849             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
2850             if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
2851                 modification_pending = 1;
2852                 break;
2853             }
2854         }
2855 
2856         if (modification_pending){
2857             // stop connnecting if modification pending
2858             if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){
2859                 hci_send_cmd(&hci_le_create_connection_cancel);
2860                 return;
2861             }
2862 
2863             // add/remove entries
2864             btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
2865             while (btstack_linked_list_iterator_has_next(&lit)){
2866                 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
2867                 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
2868                     entry->state = LE_WHITELIST_ON_CONTROLLER;
2869                     hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
2870                     return;
2871 
2872                 }
2873                 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
2874                     bd_addr_t address;
2875                     bd_addr_type_t address_type = entry->address_type;
2876                     memcpy(address, entry->address, 6);
2877                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
2878                     btstack_memory_whitelist_entry_free(entry);
2879                     hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
2880                     return;
2881                 }
2882             }
2883         }
2884 
2885         // start connecting
2886         if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE &&
2887             !btstack_linked_list_empty(&hci_stack->le_whitelist)){
2888             bd_addr_t null_addr;
2889             memset(null_addr, 0, 6);
2890             hci_send_cmd(&hci_le_create_connection,
2891                  0x0060,    // scan interval: 60 ms
2892                  0x0030,    // scan interval: 30 ms
2893                  1,         // use whitelist
2894                  0,         // peer address type
2895                  null_addr, // peer bd addr
2896                  hci_stack->le_own_addr_type, // our addr type:
2897                  0x0008,    // conn interval min
2898                  0x0018,    // conn interval max
2899                  0,         // conn latency
2900                  0x0048,    // supervision timeout
2901                  0x0001,    // min ce length
2902                  0x0001     // max ce length
2903                  );
2904             return;
2905         }
2906 #endif
2907     }
2908 #endif
2909 
2910     // send pending HCI commands
2911     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
2912         hci_connection_t * connection = (hci_connection_t *) it;
2913 
2914         switch(connection->state){
2915             case SEND_CREATE_CONNECTION:
2916                 switch(connection->address_type){
2917 #ifdef ENABLE_CLASSIC
2918                     case BD_ADDR_TYPE_CLASSIC:
2919                         log_info("sending hci_create_connection");
2920                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
2921                         break;
2922 #endif
2923                     default:
2924 #ifdef ENABLE_BLE
2925 #ifdef ENABLE_LE_CENTRAL
2926                         log_info("sending hci_le_create_connection");
2927                         hci_send_cmd(&hci_le_create_connection,
2928                                      0x0060,    // scan interval: 60 ms
2929                                      0x0030,    // scan interval: 30 ms
2930                                      0,         // don't use whitelist
2931                                      connection->address_type, // peer address type
2932                                      connection->address,      // peer bd addr
2933                                      hci_stack->le_own_addr_type,  // our addr type:
2934                                      0x0008,    // conn interval min
2935                                      0x0018,    // conn interval max
2936                                      0,         // conn latency
2937                                      0x0048,    // supervision timeout
2938                                      0x0001,    // min ce length
2939                                      0x0001     // max ce length
2940                                      );
2941 
2942                         connection->state = SENT_CREATE_CONNECTION;
2943 #endif
2944 #endif
2945                         break;
2946                 }
2947                 return;
2948 
2949 #ifdef ENABLE_CLASSIC
2950             case RECEIVED_CONNECTION_REQUEST:
2951                 log_info("sending hci_accept_connection_request, remote eSCO %u", connection->remote_supported_feature_eSCO);
2952                 connection->state = ACCEPTED_CONNECTION_REQUEST;
2953                 connection->role  = HCI_ROLE_SLAVE;
2954                 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
2955                     hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
2956                 }
2957                 return;
2958 #endif
2959 
2960 #ifdef ENABLE_BLE
2961 #ifdef ENABLE_LE_CENTRAL
2962             case SEND_CANCEL_CONNECTION:
2963                 connection->state = SENT_CANCEL_CONNECTION;
2964                 hci_send_cmd(&hci_le_create_connection_cancel);
2965                 return;
2966 #endif
2967 #endif
2968             case SEND_DISCONNECT:
2969                 connection->state = SENT_DISCONNECT;
2970                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
2971                 return;
2972 
2973             default:
2974                 break;
2975         }
2976 
2977 #ifdef ENABLE_CLASSIC
2978         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
2979             log_info("responding to link key request");
2980             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
2981             link_key_t link_key;
2982             link_key_type_t link_key_type;
2983             if ( hci_stack->link_key_db
2984               && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type)
2985               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
2986                connection->link_key_type = link_key_type;
2987                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
2988             } else {
2989                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
2990             }
2991             return;
2992         }
2993 
2994         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
2995             log_info("denying to pin request");
2996             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
2997             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
2998             return;
2999         }
3000 
3001         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
3002             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
3003             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
3004             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
3005                 // tweak authentication requirements
3006                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
3007                 if (connection->bonding_flags & BONDING_DEDICATED){
3008                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
3009                 }
3010                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
3011                     authreq |= 1;
3012                 }
3013                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
3014             } else {
3015                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
3016             }
3017             return;
3018         }
3019 
3020         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
3021             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
3022             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
3023             return;
3024         }
3025 
3026         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
3027             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
3028             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
3029             return;
3030         }
3031 
3032         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
3033             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
3034             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
3035             return;
3036         }
3037 
3038         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
3039             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
3040             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
3041             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
3042             return;
3043         }
3044 
3045         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
3046             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
3047             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
3048             return;
3049         }
3050 
3051         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
3052             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
3053             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
3054             return;
3055         }
3056 #endif
3057 
3058         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
3059             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
3060             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
3061             return;
3062         }
3063 
3064 #ifdef ENABLE_BLE
3065         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
3066             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3067 
3068             uint16_t connection_interval_min = connection->le_conn_interval_min;
3069             connection->le_conn_interval_min = 0;
3070             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
3071                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
3072                 0x0000, 0xffff);
3073         }
3074 #endif
3075     }
3076 
3077     hci_connection_t * connection;
3078     switch (hci_stack->state){
3079         case HCI_STATE_INITIALIZING:
3080             hci_initializing_run();
3081             break;
3082 
3083         case HCI_STATE_HALTING:
3084 
3085             log_info("HCI_STATE_HALTING");
3086 
3087             // free whitelist entries
3088 #ifdef ENABLE_BLE
3089 #ifdef ENABLE_LE_CENTRAL
3090             {
3091                 btstack_linked_list_iterator_t lit;
3092                 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3093                 while (btstack_linked_list_iterator_has_next(&lit)){
3094                     whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3095                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3096                     btstack_memory_whitelist_entry_free(entry);
3097                 }
3098             }
3099 #endif
3100 #endif
3101             // close all open connections
3102             connection =  (hci_connection_t *) hci_stack->connections;
3103             if (connection){
3104                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
3105                 if (!hci_can_send_command_packet_now()) return;
3106 
3107                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
3108 
3109                 // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
3110                 hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
3111 
3112                 // ... which would be ignored anyway as we shutdown (free) the connection now
3113                 hci_shutdown_connection(connection);
3114 
3115                 // finally, send the disconnect command
3116                 hci_send_cmd(&hci_disconnect, con_handle, 0x13);  // remote closed connection
3117                 return;
3118             }
3119             log_info("HCI_STATE_HALTING, calling off");
3120 
3121             // switch mode
3122             hci_power_control_off();
3123 
3124             log_info("HCI_STATE_HALTING, emitting state");
3125             hci_emit_state();
3126             log_info("HCI_STATE_HALTING, done");
3127             break;
3128 
3129         case HCI_STATE_FALLING_ASLEEP:
3130             switch(hci_stack->substate) {
3131                 case HCI_FALLING_ASLEEP_DISCONNECT:
3132                     log_info("HCI_STATE_FALLING_ASLEEP");
3133                     // close all open connections
3134                     connection =  (hci_connection_t *) hci_stack->connections;
3135 
3136 #ifdef HAVE_PLATFORM_IPHONE_OS
3137                     // don't close connections, if H4 supports power management
3138                     if (btstack_control_iphone_power_management_enabled()){
3139                         connection = NULL;
3140                     }
3141 #endif
3142                     if (connection){
3143 
3144                         // send disconnect
3145                         if (!hci_can_send_command_packet_now()) return;
3146 
3147                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
3148                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
3149 
3150                         // send disconnected event right away - causes higher layer connections to get closed, too.
3151                         hci_shutdown_connection(connection);
3152                         return;
3153                     }
3154 
3155                     if (hci_classic_supported()){
3156                         // disable page and inquiry scan
3157                         if (!hci_can_send_command_packet_now()) return;
3158 
3159                         log_info("HCI_STATE_HALTING, disabling inq scans");
3160                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
3161 
3162                         // continue in next sub state
3163                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
3164                         break;
3165                     }
3166                     // no break - fall through for ble-only chips
3167 
3168                 case HCI_FALLING_ASLEEP_COMPLETE:
3169                     log_info("HCI_STATE_HALTING, calling sleep");
3170 #ifdef HAVE_PLATFORM_IPHONE_OS
3171                     // don't actually go to sleep, if H4 supports power management
3172                     if (btstack_control_iphone_power_management_enabled()){
3173                         // SLEEP MODE reached
3174                         hci_stack->state = HCI_STATE_SLEEPING;
3175                         hci_emit_state();
3176                         break;
3177                     }
3178 #endif
3179                     // switch mode
3180                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
3181                     hci_emit_state();
3182                     break;
3183 
3184                 default:
3185                     break;
3186             }
3187             break;
3188 
3189         default:
3190             break;
3191     }
3192 }
3193 
3194 int hci_send_cmd_packet(uint8_t *packet, int size){
3195     // house-keeping
3196 
3197     if (IS_COMMAND(packet, hci_write_loopback_mode)){
3198         hci_stack->loopback_mode = packet[3];
3199     }
3200 
3201 #ifdef ENABLE_CLASSIC
3202     bd_addr_t addr;
3203     hci_connection_t * conn;
3204 
3205     // create_connection?
3206     if (IS_COMMAND(packet, hci_create_connection)){
3207         reverse_bd_addr(&packet[3], addr);
3208         log_info("Create_connection to %s", bd_addr_to_str(addr));
3209 
3210         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3211         if (!conn){
3212             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3213             if (!conn){
3214                 // notify client that alloc failed
3215                 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3216                 return 0; // don't sent packet to controller
3217             }
3218             conn->state = SEND_CREATE_CONNECTION;
3219         }
3220         log_info("conn state %u", conn->state);
3221         switch (conn->state){
3222             // if connection active exists
3223             case OPEN:
3224                 // and OPEN, emit connection complete command, don't send to controller
3225                 hci_emit_connection_complete(addr, conn->con_handle, 0);
3226                 return 0;
3227             case SEND_CREATE_CONNECTION:
3228                 // connection created by hci, e.g. dedicated bonding
3229                 break;
3230             default:
3231                 // otherwise, just ignore as it is already in the open process
3232                 return 0;
3233         }
3234         conn->state = SENT_CREATE_CONNECTION;
3235     }
3236 
3237     if (IS_COMMAND(packet, hci_link_key_request_reply)){
3238         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
3239     }
3240     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
3241         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
3242     }
3243 
3244     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
3245         if (hci_stack->link_key_db){
3246             reverse_bd_addr(&packet[3], addr);
3247             hci_stack->link_key_db->delete_link_key(addr);
3248         }
3249     }
3250 
3251     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
3252     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
3253         reverse_bd_addr(&packet[3], addr);
3254         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3255         if (conn){
3256             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
3257         }
3258     }
3259 
3260     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
3261     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
3262     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
3263     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
3264         reverse_bd_addr(&packet[3], addr);
3265         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3266         if (conn){
3267             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
3268         }
3269     }
3270 
3271 #ifdef ENABLE_SCO_OVER_HCI
3272     // setup_synchronous_connection? Voice setting at offset 22
3273     if (IS_COMMAND(packet, hci_setup_synchronous_connection)){
3274         // TODO: compare to current setting if sco connection already active
3275         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
3276     }
3277     // accept_synchronus_connection? Voice setting at offset 18
3278     if (IS_COMMAND(packet, hci_accept_synchronous_connection)){
3279         // TODO: compare to current setting if sco connection already active
3280         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
3281     }
3282 #endif
3283 #endif
3284 
3285 #ifdef ENABLE_BLE
3286 #ifdef ENABLE_LE_PERIPHERAL
3287     if (IS_COMMAND(packet, hci_le_set_random_address)){
3288         hci_stack->le_random_address_set = 1;
3289         reverse_bd_addr(&packet[3], hci_stack->le_random_address);
3290     }
3291     if (IS_COMMAND(packet, hci_le_set_advertise_enable)){
3292         hci_stack->le_advertisements_active = packet[3];
3293     }
3294 #endif
3295 #ifdef ENABLE_LE_CENTRAL
3296     if (IS_COMMAND(packet, hci_le_create_connection)){
3297         // white list used?
3298         uint8_t initiator_filter_policy = packet[7];
3299         switch (initiator_filter_policy){
3300             case 0:
3301                 // whitelist not used
3302                 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
3303                 break;
3304             case 1:
3305                 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
3306                 break;
3307             default:
3308                 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
3309                 break;
3310         }
3311     }
3312     if (IS_COMMAND(packet, hci_le_create_connection_cancel)){
3313         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3314     }
3315 #endif
3316 #endif
3317 
3318     hci_stack->num_cmd_packets--;
3319 
3320     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3321     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3322 
3323     // release packet buffer for synchronous transport implementations
3324     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
3325         hci_stack->hci_packet_buffer_reserved = 0;
3326     }
3327 
3328     return err;
3329 }
3330 
3331 // disconnect because of security block
3332 void hci_disconnect_security_block(hci_con_handle_t con_handle){
3333     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3334     if (!connection) return;
3335     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3336 }
3337 
3338 
3339 // Configure Secure Simple Pairing
3340 
3341 #ifdef ENABLE_CLASSIC
3342 
3343 // enable will enable SSP during init
3344 void gap_ssp_set_enable(int enable){
3345     hci_stack->ssp_enable = enable;
3346 }
3347 
3348 static int hci_local_ssp_activated(void){
3349     return gap_ssp_supported() && hci_stack->ssp_enable;
3350 }
3351 
3352 // if set, BTstack will respond to io capability request using authentication requirement
3353 void gap_ssp_set_io_capability(int io_capability){
3354     hci_stack->ssp_io_capability = io_capability;
3355 }
3356 void gap_ssp_set_authentication_requirement(int authentication_requirement){
3357     hci_stack->ssp_authentication_requirement = authentication_requirement;
3358 }
3359 
3360 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
3361 void gap_ssp_set_auto_accept(int auto_accept){
3362     hci_stack->ssp_auto_accept = auto_accept;
3363 }
3364 #endif
3365 
3366 // va_list part of hci_send_cmd
3367 int hci_send_cmd_va_arg(const hci_cmd_t *cmd, va_list argptr){
3368     if (!hci_can_send_command_packet_now()){
3369         log_error("hci_send_cmd called but cannot send packet now");
3370         return 0;
3371     }
3372 
3373     // for HCI INITIALIZATION
3374     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
3375     hci_stack->last_cmd_opcode = cmd->opcode;
3376 
3377     hci_reserve_packet_buffer();
3378     uint8_t * packet = hci_stack->hci_packet_buffer;
3379     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
3380     return hci_send_cmd_packet(packet, size);
3381 }
3382 
3383 /**
3384  * pre: numcmds >= 0 - it's allowed to send a command to the controller
3385  */
3386 int hci_send_cmd(const hci_cmd_t *cmd, ...){
3387     va_list argptr;
3388     va_start(argptr, cmd);
3389     int res = hci_send_cmd_va_arg(cmd, argptr);
3390     va_end(argptr);
3391     return res;
3392 }
3393 
3394 // Create various non-HCI events.
3395 // TODO: generalize, use table similar to hci_create_command
3396 
3397 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
3398     // dump packet
3399     if (dump) {
3400         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
3401     }
3402 
3403     // dispatch to all event handlers
3404     btstack_linked_list_iterator_t it;
3405     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
3406     while (btstack_linked_list_iterator_has_next(&it)){
3407         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
3408         entry->callback(HCI_EVENT_PACKET, 0, event, size);
3409     }
3410 }
3411 
3412 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
3413     if (!hci_stack->acl_packet_handler) return;
3414     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
3415 }
3416 
3417 #ifdef ENABLE_CLASSIC
3418 static void hci_notify_if_sco_can_send_now(void){
3419     // notify SCO sender if waiting
3420     if (!hci_stack->sco_waiting_for_can_send_now) return;
3421     if (hci_can_send_sco_packet_now()){
3422         hci_stack->sco_waiting_for_can_send_now = 0;
3423         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
3424         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
3425         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
3426     }
3427 }
3428 
3429 // parsing end emitting has been merged to reduce code size
3430 static void gap_inquiry_explode(uint8_t * packet){
3431     uint8_t event[15+GAP_INQUIRY_MAX_NAME_LEN];
3432 
3433     uint8_t * eir_data;
3434     ad_context_t context;
3435     const uint8_t * name;
3436     uint8_t         name_len;
3437 
3438     int event_type = hci_event_packet_get_type(packet);
3439     int num_reserved_fields = event_type == HCI_EVENT_INQUIRY_RESULT ? 2 : 1;    // 2 for old event, 1 otherwise
3440     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
3441 
3442     // event[1] is set at the end
3443     int i;
3444     for (i=0; i<num_responses;i++){
3445         memset(event, 0, sizeof(event));
3446         event[0] = GAP_EVENT_INQUIRY_RESULT;
3447         uint8_t event_size = 18;    // if name is not set by EIR
3448 
3449         memcpy(&event[2],  &packet[3 +                                             i*6], 6); // bd_addr
3450         event[8] =          packet[3 + num_responses*(6)                         + i*1];     // page_scan_repetition_mode
3451         memcpy(&event[9],  &packet[3 + num_responses*(6+1+num_reserved_fields)   + i*3], 3); // class of device
3452         memcpy(&event[12], &packet[3 + num_responses*(6+1+num_reserved_fields+3) + i*2], 2); // clock offset
3453 
3454         switch (event_type){
3455             case HCI_EVENT_INQUIRY_RESULT:
3456                 // 14,15,16,17 = 0, size 18
3457                 break;
3458             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
3459                 event[14] = 1;
3460                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
3461                 // 16,17 = 0, size 18
3462                 break;
3463             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
3464                 event[14] = 1;
3465                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
3466                 // for EIR packets, there is only one reponse in it
3467                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
3468                 name = NULL;
3469                 // EIR data is 240 bytes in EIR event
3470                 for (ad_iterator_init(&context, 240, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
3471                     uint8_t data_type    = ad_iterator_get_data_type(&context);
3472                     uint8_t data_size    = ad_iterator_get_data_len(&context);
3473                     const uint8_t * data = ad_iterator_get_data(&context);
3474                     // Prefer Complete Local Name over Shortend Local Name
3475                     switch (data_type){
3476                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
3477                             if (name) continue;
3478                             /* explicit fall-through */
3479                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
3480                             name = data;
3481                             name_len = data_size;
3482                             break;
3483                         default:
3484                             break;
3485                     }
3486                 }
3487                 if (name){
3488                     event[16] = 1;
3489                     // truncate name if needed
3490                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
3491                     event[17] = len;
3492                     memcpy(&event[18], name, len);
3493                     event_size += len;
3494                 }
3495                 break;
3496         }
3497         event[1] = event_size - 2;
3498         hci_emit_event(event, event_size, 1);
3499     }
3500 }
3501 #endif
3502 
3503 void hci_emit_state(void){
3504     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
3505     uint8_t event[3];
3506     event[0] = BTSTACK_EVENT_STATE;
3507     event[1] = sizeof(event) - 2;
3508     event[2] = hci_stack->state;
3509     hci_emit_event(event, sizeof(event), 1);
3510 }
3511 
3512 #ifdef ENABLE_CLASSIC
3513 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3514     uint8_t event[13];
3515     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
3516     event[1] = sizeof(event) - 2;
3517     event[2] = status;
3518     little_endian_store_16(event, 3, con_handle);
3519     reverse_bd_addr(address, &event[5]);
3520     event[11] = 1; // ACL connection
3521     event[12] = 0; // encryption disabled
3522     hci_emit_event(event, sizeof(event), 1);
3523 }
3524 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
3525     if (disable_l2cap_timeouts) return;
3526     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
3527     uint8_t event[4];
3528     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
3529     event[1] = sizeof(event) - 2;
3530     little_endian_store_16(event, 2, conn->con_handle);
3531     hci_emit_event(event, sizeof(event), 1);
3532 }
3533 #endif
3534 
3535 #ifdef ENABLE_BLE
3536 #ifdef ENABLE_LE_CENTRAL
3537 static void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3538     uint8_t event[21];
3539     event[0] = HCI_EVENT_LE_META;
3540     event[1] = sizeof(event) - 2;
3541     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
3542     event[3] = status;
3543     little_endian_store_16(event, 4, con_handle);
3544     event[6] = 0; // TODO: role
3545     event[7] = address_type;
3546     reverse_bd_addr(address, &event[8]);
3547     little_endian_store_16(event, 14, 0); // interval
3548     little_endian_store_16(event, 16, 0); // latency
3549     little_endian_store_16(event, 18, 0); // supervision timeout
3550     event[20] = 0; // master clock accuracy
3551     hci_emit_event(event, sizeof(event), 1);
3552 }
3553 #endif
3554 #endif
3555 
3556 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
3557     uint8_t event[6];
3558     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
3559     event[1] = sizeof(event) - 2;
3560     event[2] = 0; // status = OK
3561     little_endian_store_16(event, 3, con_handle);
3562     event[5] = reason;
3563     hci_emit_event(event, sizeof(event), 1);
3564 }
3565 
3566 static void hci_emit_nr_connections_changed(void){
3567     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
3568     uint8_t event[3];
3569     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
3570     event[1] = sizeof(event) - 2;
3571     event[2] = nr_hci_connections();
3572     hci_emit_event(event, sizeof(event), 1);
3573 }
3574 
3575 static void hci_emit_hci_open_failed(void){
3576     log_info("BTSTACK_EVENT_POWERON_FAILED");
3577     uint8_t event[2];
3578     event[0] = BTSTACK_EVENT_POWERON_FAILED;
3579     event[1] = sizeof(event) - 2;
3580     hci_emit_event(event, sizeof(event), 1);
3581 }
3582 
3583 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
3584     log_info("hci_emit_dedicated_bonding_result %u ", status);
3585     uint8_t event[9];
3586     int pos = 0;
3587     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
3588     event[pos++] = sizeof(event) - 2;
3589     event[pos++] = status;
3590     reverse_bd_addr(address, &event[pos]);
3591     hci_emit_event(event, sizeof(event), 1);
3592 }
3593 
3594 
3595 #ifdef ENABLE_CLASSIC
3596 
3597 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
3598     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
3599     uint8_t event[5];
3600     int pos = 0;
3601     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
3602     event[pos++] = sizeof(event) - 2;
3603     little_endian_store_16(event, 2, con_handle);
3604     pos += 2;
3605     event[pos++] = level;
3606     hci_emit_event(event, sizeof(event), 1);
3607 }
3608 
3609 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
3610     if (!connection) return LEVEL_0;
3611     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
3612     return gap_security_level_for_link_key_type(connection->link_key_type);
3613 }
3614 
3615 static void hci_emit_discoverable_enabled(uint8_t enabled){
3616     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
3617     uint8_t event[3];
3618     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
3619     event[1] = sizeof(event) - 2;
3620     event[2] = enabled;
3621     hci_emit_event(event, sizeof(event), 1);
3622 }
3623 
3624 #ifdef ENABLE_CLASSIC
3625 // query if remote side supports eSCO
3626 int hci_remote_esco_supported(hci_con_handle_t con_handle){
3627     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3628     if (!connection) return 0;
3629     return connection->remote_supported_feature_eSCO;
3630 }
3631 
3632 // query if remote side supports SSP
3633 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
3634     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3635     if (!connection) return 0;
3636     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
3637 }
3638 
3639 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
3640     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
3641 }
3642 #endif
3643 
3644 // GAP API
3645 /**
3646  * @bbrief enable/disable bonding. default is enabled
3647  * @praram enabled
3648  */
3649 void gap_set_bondable_mode(int enable){
3650     hci_stack->bondable = enable ? 1 : 0;
3651 }
3652 /**
3653  * @brief Get bondable mode.
3654  * @return 1 if bondable
3655  */
3656 int gap_get_bondable_mode(void){
3657     return hci_stack->bondable;
3658 }
3659 
3660 /**
3661  * @brief map link keys to security levels
3662  */
3663 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
3664     switch (link_key_type){
3665         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
3666             return LEVEL_4;
3667         case COMBINATION_KEY:
3668         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
3669             return LEVEL_3;
3670         default:
3671             return LEVEL_2;
3672     }
3673 }
3674 
3675 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
3676     log_info("gap_mitm_protection_required_for_security_level %u", level);
3677     return level > LEVEL_2;
3678 }
3679 
3680 /**
3681  * @brief get current security level
3682  */
3683 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
3684     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3685     if (!connection) return LEVEL_0;
3686     return gap_security_level_for_connection(connection);
3687 }
3688 
3689 /**
3690  * @brief request connection to device to
3691  * @result GAP_AUTHENTICATION_RESULT
3692  */
3693 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
3694     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3695     if (!connection){
3696         hci_emit_security_level(con_handle, LEVEL_0);
3697         return;
3698     }
3699     gap_security_level_t current_level = gap_security_level(con_handle);
3700     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
3701     if (current_level >= requested_level){
3702         hci_emit_security_level(con_handle, current_level);
3703         return;
3704     }
3705 
3706     connection->requested_security_level = requested_level;
3707 
3708 #if 0
3709     // sending encryption request without a link key results in an error.
3710     // TODO: figure out how to use it properly
3711 
3712     // would enabling ecnryption suffice (>= LEVEL_2)?
3713     if (hci_stack->link_key_db){
3714         link_key_type_t link_key_type;
3715         link_key_t      link_key;
3716         if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){
3717             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
3718                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
3719                 return;
3720             }
3721         }
3722     }
3723 #endif
3724 
3725     // try to authenticate connection
3726     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
3727     hci_run();
3728 }
3729 
3730 /**
3731  * @brief start dedicated bonding with device. disconnect after bonding
3732  * @param device
3733  * @param request MITM protection
3734  * @result GAP_DEDICATED_BONDING_COMPLETE
3735  */
3736 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
3737 
3738     // create connection state machine
3739     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
3740 
3741     if (!connection){
3742         return BTSTACK_MEMORY_ALLOC_FAILED;
3743     }
3744 
3745     // delete linkn key
3746     gap_drop_link_key_for_bd_addr(device);
3747 
3748     // configure LEVEL_2/3, dedicated bonding
3749     connection->state = SEND_CREATE_CONNECTION;
3750     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
3751     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
3752     connection->bonding_flags = BONDING_DEDICATED;
3753 
3754     // wait for GAP Security Result and send GAP Dedicated Bonding complete
3755 
3756     // handle: connnection failure (connection complete != ok)
3757     // handle: authentication failure
3758     // handle: disconnect on done
3759 
3760     hci_run();
3761 
3762     return 0;
3763 }
3764 #endif
3765 
3766 void gap_set_local_name(const char * local_name){
3767     hci_stack->local_name = local_name;
3768 }
3769 
3770 
3771 #ifdef ENABLE_BLE
3772 
3773 #ifdef ENABLE_LE_CENTRAL
3774 void gap_start_scan(void){
3775     if (hci_stack->le_scanning_state == LE_SCANNING) return;
3776     hci_stack->le_scanning_state = LE_START_SCAN;
3777     hci_run();
3778 }
3779 
3780 void gap_stop_scan(void){
3781     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return;
3782     hci_stack->le_scanning_state = LE_STOP_SCAN;
3783     hci_run();
3784 }
3785 
3786 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
3787     hci_stack->le_scan_type     = scan_type;
3788     hci_stack->le_scan_interval = scan_interval;
3789     hci_stack->le_scan_window   = scan_window;
3790     hci_run();
3791 }
3792 
3793 uint8_t gap_connect(bd_addr_t addr, bd_addr_type_t addr_type){
3794     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
3795     if (!conn){
3796         log_info("gap_connect: no connection exists yet, creating context");
3797         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
3798         if (!conn){
3799             // notify client that alloc failed
3800             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3801             log_info("gap_connect: failed to alloc hci_connection_t");
3802             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
3803         }
3804         conn->state = SEND_CREATE_CONNECTION;
3805         log_info("gap_connect: send create connection next");
3806         hci_run();
3807         return 0;
3808     }
3809 
3810     if (!hci_is_le_connection(conn) ||
3811         conn->state == SEND_CREATE_CONNECTION ||
3812         conn->state == SENT_CREATE_CONNECTION) {
3813         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
3814         log_error("gap_connect: classic connection or connect is already being created");
3815         return GATT_CLIENT_IN_WRONG_STATE;
3816     }
3817 
3818     log_info("gap_connect: context exists with state %u", conn->state);
3819     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0);
3820     hci_run();
3821     return 0;
3822 }
3823 
3824 // @assumption: only a single outgoing LE Connection exists
3825 static hci_connection_t * gap_get_outgoing_connection(void){
3826     btstack_linked_item_t *it;
3827     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3828         hci_connection_t * conn = (hci_connection_t *) it;
3829         if (!hci_is_le_connection(conn)) continue;
3830         switch (conn->state){
3831             case SEND_CREATE_CONNECTION:
3832             case SENT_CREATE_CONNECTION:
3833                 return conn;
3834             default:
3835                 break;
3836         };
3837     }
3838     return NULL;
3839 }
3840 
3841 uint8_t gap_connect_cancel(void){
3842     hci_connection_t * conn = gap_get_outgoing_connection();
3843     if (!conn) return 0;
3844     switch (conn->state){
3845         case SEND_CREATE_CONNECTION:
3846             // skip sending create connection and emit event instead
3847             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
3848             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
3849             btstack_memory_hci_connection_free( conn );
3850             break;
3851         case SENT_CREATE_CONNECTION:
3852             // request to send cancel connection
3853             conn->state = SEND_CANCEL_CONNECTION;
3854             hci_run();
3855             break;
3856         default:
3857             break;
3858     }
3859     return 0;
3860 }
3861 #endif
3862 
3863 /**
3864  * @brief Updates the connection parameters for a given LE connection
3865  * @param handle
3866  * @param conn_interval_min (unit: 1.25ms)
3867  * @param conn_interval_max (unit: 1.25ms)
3868  * @param conn_latency
3869  * @param supervision_timeout (unit: 10ms)
3870  * @returns 0 if ok
3871  */
3872 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
3873     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
3874     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3875     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3876     connection->le_conn_interval_min = conn_interval_min;
3877     connection->le_conn_interval_max = conn_interval_max;
3878     connection->le_conn_latency = conn_latency;
3879     connection->le_supervision_timeout = supervision_timeout;
3880     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
3881     hci_run();
3882     return 0;
3883 }
3884 
3885 /**
3886  * @brief Request an update of the connection parameter for a given LE connection
3887  * @param handle
3888  * @param conn_interval_min (unit: 1.25ms)
3889  * @param conn_interval_max (unit: 1.25ms)
3890  * @param conn_latency
3891  * @param supervision_timeout (unit: 10ms)
3892  * @returns 0 if ok
3893  */
3894 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
3895     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
3896     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3897     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
3898     connection->le_conn_interval_min = conn_interval_min;
3899     connection->le_conn_interval_max = conn_interval_max;
3900     connection->le_conn_latency = conn_latency;
3901     connection->le_supervision_timeout = supervision_timeout;
3902     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
3903     hci_run();
3904     return 0;
3905 }
3906 
3907 #ifdef ENABLE_LE_PERIPHERAL
3908 
3909 static void gap_advertisments_changed(void){
3910     // disable advertisements before updating adv, scan data, or adv params
3911     if (hci_stack->le_advertisements_active){
3912         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
3913     }
3914     hci_run();
3915 }
3916 
3917 /**
3918  * @brief Set Advertisement Data
3919  * @param advertising_data_length
3920  * @param advertising_data (max 31 octets)
3921  * @note data is not copied, pointer has to stay valid
3922  */
3923 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
3924     hci_stack->le_advertisements_data_len = advertising_data_length;
3925     hci_stack->le_advertisements_data = advertising_data;
3926     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3927     gap_advertisments_changed();
3928 }
3929 
3930 /**
3931  * @brief Set Scan Response Data
3932  * @param advertising_data_length
3933  * @param advertising_data (max 31 octets)
3934  * @note data is not copied, pointer has to stay valid
3935  */
3936 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
3937     hci_stack->le_scan_response_data_len = scan_response_data_length;
3938     hci_stack->le_scan_response_data = scan_response_data;
3939     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
3940     gap_advertisments_changed();
3941 }
3942 
3943 /**
3944  * @brief Set Advertisement Parameters
3945  * @param adv_int_min
3946  * @param adv_int_max
3947  * @param adv_type
3948  * @param direct_address_type
3949  * @param direct_address
3950  * @param channel_map
3951  * @param filter_policy
3952  *
3953  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
3954  */
3955  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
3956     uint8_t direct_address_typ, bd_addr_t direct_address,
3957     uint8_t channel_map, uint8_t filter_policy) {
3958 
3959     hci_stack->le_advertisements_interval_min = adv_int_min;
3960     hci_stack->le_advertisements_interval_max = adv_int_max;
3961     hci_stack->le_advertisements_type = adv_type;
3962     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
3963     hci_stack->le_advertisements_channel_map = channel_map;
3964     hci_stack->le_advertisements_filter_policy = filter_policy;
3965     memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6);
3966 
3967     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3968     gap_advertisments_changed();
3969  }
3970 
3971 /**
3972  * @brief Enable/Disable Advertisements
3973  * @param enabled
3974  */
3975 void gap_advertisements_enable(int enabled){
3976     hci_stack->le_advertisements_enabled = enabled;
3977     if (enabled && !hci_stack->le_advertisements_active){
3978         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
3979     }
3980     if (!enabled && hci_stack->le_advertisements_active){
3981         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE;
3982     }
3983     hci_run();
3984 }
3985 
3986 #endif
3987 
3988 void hci_le_set_own_address_type(uint8_t own_address_type){
3989     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
3990     if (own_address_type == hci_stack->le_own_addr_type) return;
3991     hci_stack->le_own_addr_type = own_address_type;
3992 
3993 #ifdef ENABLE_LE_PERIPHERAL
3994     // update advertisement parameters, too
3995     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3996     gap_advertisments_changed();
3997 #endif
3998 #ifdef ENABLE_LE_CENTRAL
3999     // note: we don't update scan parameters or modify ongoing connection attempts
4000 #endif
4001 }
4002 
4003 #endif
4004 
4005 uint8_t gap_disconnect(hci_con_handle_t handle){
4006     hci_connection_t * conn = hci_connection_for_handle(handle);
4007     if (!conn){
4008         hci_emit_disconnection_complete(handle, 0);
4009         return 0;
4010     }
4011     conn->state = SEND_DISCONNECT;
4012     hci_run();
4013     return 0;
4014 }
4015 
4016 /**
4017  * @brief Get connection type
4018  * @param con_handle
4019  * @result connection_type
4020  */
4021 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
4022     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4023     if (!conn) return GAP_CONNECTION_INVALID;
4024     switch (conn->address_type){
4025         case BD_ADDR_TYPE_LE_PUBLIC:
4026         case BD_ADDR_TYPE_LE_RANDOM:
4027             return GAP_CONNECTION_LE;
4028         case BD_ADDR_TYPE_SCO:
4029             return GAP_CONNECTION_SCO;
4030         case BD_ADDR_TYPE_CLASSIC:
4031             return GAP_CONNECTION_ACL;
4032         default:
4033             return GAP_CONNECTION_INVALID;
4034     }
4035 }
4036 
4037 #ifdef ENABLE_BLE
4038 
4039 #ifdef ENABLE_LE_CENTRAL
4040 /**
4041  * @brief Auto Connection Establishment - Start Connecting to device
4042  * @param address_typ
4043  * @param address
4044  * @returns 0 if ok
4045  */
4046 int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){
4047     // check capacity
4048     int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist);
4049     if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
4050     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
4051     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
4052     entry->address_type = address_type;
4053     memcpy(entry->address, address, 6);
4054     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
4055     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
4056     hci_run();
4057     return 0;
4058 }
4059 
4060 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){
4061     btstack_linked_list_iterator_t it;
4062     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4063     while (btstack_linked_list_iterator_has_next(&it)){
4064         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4065         if (entry->address_type != address_type) continue;
4066         if (memcmp(entry->address, address, 6) != 0) continue;
4067         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4068             // remove from controller if already present
4069             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4070             continue;
4071         }
4072         // direclty remove entry from whitelist
4073         btstack_linked_list_iterator_remove(&it);
4074         btstack_memory_whitelist_entry_free(entry);
4075     }
4076 }
4077 
4078 /**
4079  * @brief Auto Connection Establishment - Stop Connecting to device
4080  * @param address_typ
4081  * @param address
4082  * @returns 0 if ok
4083  */
4084 int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){
4085     hci_remove_from_whitelist(address_type, address);
4086     hci_run();
4087     return 0;
4088 }
4089 
4090 /**
4091  * @brief Auto Connection Establishment - Stop everything
4092  * @note  Convenience function to stop all active auto connection attempts
4093  */
4094 void gap_auto_connection_stop_all(void){
4095     btstack_linked_list_iterator_t it;
4096     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4097     while (btstack_linked_list_iterator_has_next(&it)){
4098         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4099         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4100             // remove from controller if already present
4101             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4102             continue;
4103         }
4104         // directly remove entry from whitelist
4105         btstack_linked_list_iterator_remove(&it);
4106         btstack_memory_whitelist_entry_free(entry);
4107     }
4108     hci_run();
4109 }
4110 #endif
4111 #endif
4112 
4113 #ifdef ENABLE_CLASSIC
4114 /**
4115  * @brief Set Extended Inquiry Response data
4116  * @param eir_data size 240 bytes, is not copied make sure memory is accessible during stack startup
4117  * @note has to be done before stack starts up
4118  */
4119 void gap_set_extended_inquiry_response(const uint8_t * data){
4120     hci_stack->eir_data = data;
4121 }
4122 
4123 /**
4124  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
4125  * @param inquriy_mode see bluetooth_defines.h
4126  */
4127 void hci_set_inquiry_mode(inquiry_mode_t mode){
4128     hci_stack->inquiry_mode = mode;
4129 }
4130 
4131 /**
4132  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
4133  */
4134 void hci_set_sco_voice_setting(uint16_t voice_setting){
4135     hci_stack->sco_voice_setting = voice_setting;
4136 }
4137 
4138 /**
4139  * @brief Get SCO Voice Setting
4140  * @return current voice setting
4141  */
4142 uint16_t hci_get_sco_voice_setting(void){
4143     return hci_stack->sco_voice_setting;
4144 }
4145 
4146 /** @brief Get SCO packet length for current SCO Voice setting
4147  *  @note  Using SCO packets of the exact length is required for USB transfer
4148  *  @return Length of SCO packets in bytes (not audio frames)
4149  */
4150 int hci_get_sco_packet_length(void){
4151     // see Core Spec for H2 USB Transfer.
4152     if (hci_stack->sco_voice_setting & 0x0020) return 51;
4153     return 27;
4154 }
4155 #endif
4156 
4157 /**
4158  * @brief Set callback for Bluetooth Hardware Error
4159  */
4160 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
4161     hci_stack->hardware_error_callback = fn;
4162 }
4163 
4164 void hci_disconnect_all(void){
4165     btstack_linked_list_iterator_t it;
4166     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
4167     while (btstack_linked_list_iterator_has_next(&it)){
4168         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
4169         if (con->state == SENT_DISCONNECT) continue;
4170         con->state = SEND_DISCONNECT;
4171     }
4172     hci_run();
4173 }
4174 
4175 uint16_t hci_get_manufacturer(void){
4176     return hci_stack->manufacturer;
4177 }
4178