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