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