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