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