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