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