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