xref: /btstack/src/hci.c (revision 745274476c0bcb9f940992b7d0c1aa5570184a14)
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
531         unsigned int sco_payload_len = hci_get_sco_packet_length() - 3;
532         num_sco_packets_sent = (num_sco_bytes_sent / sco_payload_len);
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 SCO 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             // wait with SCO send until first packet was received
2146             if ((hci_stack->sco_voice_setting_active & 0x03) == 0x03){
2147                 // mSBC
2148                 conn->num_sco_bytes_sent = 60;
2149             } else {
2150                 // CVSD
2151                 conn->num_sco_bytes_sent = 120;
2152             }
2153 #endif
2154             break;
2155 
2156         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
2157             handle = little_endian_read_16(packet, 3);
2158             conn = hci_connection_for_handle(handle);
2159             if (!conn) break;
2160             if (!packet[2]){
2161                 uint8_t * features = &packet[5];
2162                 if (features[6] & (1 << 3)){
2163                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
2164                 }
2165                 if (features[3] & (1<<7)){
2166                     conn->remote_supported_feature_eSCO = 1;
2167                 }
2168             }
2169             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
2170             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x, eSCO %u", conn->bonding_flags, conn->remote_supported_feature_eSCO);
2171             if (conn->bonding_flags & BONDING_DEDICATED){
2172                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2173             }
2174             break;
2175 
2176         case HCI_EVENT_LINK_KEY_REQUEST:
2177             log_info("HCI_EVENT_LINK_KEY_REQUEST");
2178             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
2179             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
2180             if (hci_stack->bondable && !hci_stack->link_key_db) break;
2181             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
2182             hci_run();
2183             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
2184             return;
2185 
2186         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
2187             reverse_bd_addr(&packet[2], addr);
2188             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2189             if (!conn) break;
2190             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
2191             link_key_type_t link_key_type = (link_key_type_t)packet[24];
2192             // Change Connection Encryption keeps link key type
2193             if (link_key_type != CHANGED_COMBINATION_KEY){
2194                 conn->link_key_type = link_key_type;
2195             }
2196             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
2197             // still forward event to allow dismiss of pairing dialog
2198             break;
2199         }
2200 
2201         case HCI_EVENT_PIN_CODE_REQUEST:
2202             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
2203             // non-bondable mode: pin code negative reply will be sent
2204             if (!hci_stack->bondable){
2205                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
2206                 hci_run();
2207                 return;
2208             }
2209             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
2210             if (!hci_stack->link_key_db) break;
2211             hci_event_pin_code_request_get_bd_addr(packet, addr);
2212             hci_stack->link_key_db->delete_link_key(addr);
2213             break;
2214 
2215         case HCI_EVENT_IO_CAPABILITY_REQUEST:
2216             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
2217             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
2218             break;
2219 
2220         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
2221             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2222             if (!hci_stack->ssp_auto_accept) break;
2223             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
2224             break;
2225 
2226         case HCI_EVENT_USER_PASSKEY_REQUEST:
2227             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2228             if (!hci_stack->ssp_auto_accept) break;
2229             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
2230             break;
2231         case HCI_EVENT_MODE_CHANGE:
2232             handle = hci_event_mode_change_get_handle(packet);
2233             conn = hci_connection_for_handle(handle);
2234             if (!conn) break;
2235             conn->connection_mode = hci_event_mode_change_get_mode(packet);
2236             log_info("HCI_EVENT_MODE_CHANGE, handle 0x%04x, mode %u", handle, conn->connection_mode);
2237             break;
2238 #endif
2239 
2240         case HCI_EVENT_ENCRYPTION_CHANGE:
2241             handle = little_endian_read_16(packet, 3);
2242             conn = hci_connection_for_handle(handle);
2243             if (!conn) break;
2244             if (packet[2] == 0) {
2245                 if (packet[5]){
2246                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
2247                 } else {
2248                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
2249                 }
2250             }
2251 #ifdef ENABLE_CLASSIC
2252             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2253 #endif
2254             break;
2255 
2256 #ifdef ENABLE_CLASSIC
2257         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
2258             handle = little_endian_read_16(packet, 3);
2259             conn = hci_connection_for_handle(handle);
2260             if (!conn) break;
2261 
2262             // dedicated bonding: send result and disconnect
2263             if (conn->bonding_flags & BONDING_DEDICATED){
2264                 conn->bonding_flags &= ~BONDING_DEDICATED;
2265                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2266                 conn->bonding_status = packet[2];
2267                 break;
2268             }
2269 
2270             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
2271                 // link key sufficient for requested security
2272                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2273                 break;
2274             }
2275             // not enough
2276             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2277             break;
2278 #endif
2279 
2280         // HCI_EVENT_DISCONNECTION_COMPLETE
2281         // has been split, to first notify stack before shutting connection down
2282         // see end of function, too.
2283         case HCI_EVENT_DISCONNECTION_COMPLETE:
2284             if (packet[2]) break;   // status != 0
2285             handle = little_endian_read_16(packet, 3);
2286             // drop outgoing ACL fragments if it is for closed connection and release buffer if tx not active
2287             if (hci_stack->acl_fragmentation_total_size > 0) {
2288                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
2289                     int release_buffer = hci_stack->acl_fragmentation_tx_active == 0;
2290                     log_info("drop fragmented ACL data for closed connection, release buffer %u", release_buffer);
2291                     hci_stack->acl_fragmentation_total_size = 0;
2292                     hci_stack->acl_fragmentation_pos = 0;
2293                     if (release_buffer){
2294                         hci_release_packet_buffer();
2295                     }
2296                 }
2297             }
2298 
2299             // re-enable advertisements for le connections if active
2300             conn = hci_connection_for_handle(handle);
2301             if (!conn) break;
2302             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
2303 #ifdef ENABLE_BLE
2304 #ifdef ENABLE_LE_PERIPHERAL
2305             if (hci_is_le_connection(conn)){
2306                 hci_reenable_advertisements_if_needed();
2307             }
2308 #endif
2309 #endif
2310             break;
2311 
2312         case HCI_EVENT_HARDWARE_ERROR:
2313             log_error("Hardware Error: 0x%02x", packet[2]);
2314             if (hci_stack->hardware_error_callback){
2315                 (*hci_stack->hardware_error_callback)(packet[2]);
2316             } else {
2317                 // if no special requests, just reboot stack
2318                 hci_power_control_off();
2319                 hci_power_control_on();
2320             }
2321             break;
2322 
2323 #ifdef ENABLE_CLASSIC
2324         case HCI_EVENT_ROLE_CHANGE:
2325             if (packet[2]) break;   // status != 0
2326             reverse_bd_addr(&packet[3], addr);
2327             addr_type = BD_ADDR_TYPE_CLASSIC;
2328             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2329             if (!conn) break;
2330             conn->role = packet[9];
2331             break;
2332 #endif
2333 
2334         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2335             // release packet buffer only for asynchronous transport and if there are not further fragements
2336             if (hci_transport_synchronous()) {
2337                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
2338                 return; // instead of break: to avoid re-entering hci_run()
2339             }
2340             hci_stack->acl_fragmentation_tx_active = 0;
2341             if (hci_stack->acl_fragmentation_total_size) break;
2342             hci_release_packet_buffer();
2343 
2344             // L2CAP receives this event via the hci_emit_event below
2345 
2346 #ifdef ENABLE_CLASSIC
2347             // For SCO, we do the can_send_now_check here
2348             hci_notify_if_sco_can_send_now();
2349 #endif
2350             break;
2351 
2352 #ifdef ENABLE_CLASSIC
2353         case HCI_EVENT_SCO_CAN_SEND_NOW:
2354             // For SCO, we do the can_send_now_check here
2355             hci_notify_if_sco_can_send_now();
2356             return;
2357 
2358         // explode inquriy results for easier consumption
2359         case HCI_EVENT_INQUIRY_RESULT:
2360         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
2361         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
2362             gap_inquiry_explode(packet);
2363             break;
2364 #endif
2365 
2366 #ifdef ENABLE_BLE
2367         case HCI_EVENT_LE_META:
2368             switch (packet[2]){
2369 #ifdef ENABLE_LE_CENTRAL
2370                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
2371                     // log_info("advertising report received");
2372                     if (!hci_stack->le_scanning_enabled) break;
2373                     le_handle_advertisement_report(packet, size);
2374                     break;
2375 #endif
2376                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
2377                     // Connection management
2378                     reverse_bd_addr(&packet[8], addr);
2379                     addr_type = (bd_addr_type_t)packet[7];
2380                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
2381                     conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2382 
2383 #ifdef ENABLE_LE_CENTRAL
2384                     // if auto-connect, remove from whitelist in both roles
2385                     if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){
2386                         hci_remove_from_whitelist(addr_type, addr);
2387                     }
2388                     // handle error: error is reported only to the initiator -> outgoing connection
2389                     if (packet[3]){
2390 
2391                         // handle cancelled outgoing connection
2392                         // "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
2393                         //  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
2394                         //  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
2395                         if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
2396                             conn = gap_get_outgoing_connection();
2397                         }
2398 
2399                         // outgoing connection establishment is done
2400                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2401                         // remove entry
2402                         if (conn){
2403                             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2404                             btstack_memory_hci_connection_free( conn );
2405                         }
2406                         break;
2407                     }
2408 #endif
2409                     // on success, both hosts receive connection complete event
2410                     if (packet[6] == HCI_ROLE_MASTER){
2411 #ifdef ENABLE_LE_CENTRAL
2412                         // if we're master, it was an outgoing connection and we're done with it
2413                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2414 #endif
2415                     } else {
2416 #ifdef ENABLE_LE_PERIPHERAL
2417                         // if we're slave, it was an incoming connection, advertisements have stopped
2418                         hci_stack->le_advertisements_active = 0;
2419 #endif
2420                     }
2421                     // LE connections are auto-accepted, so just create a connection if there isn't one already
2422                     if (!conn){
2423                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2424                     }
2425                     // no memory, sorry.
2426                     if (!conn){
2427                         break;
2428                     }
2429 
2430                     conn->state = OPEN;
2431                     conn->role  = packet[6];
2432                     conn->con_handle             = hci_subevent_le_connection_complete_get_connection_handle(packet);
2433                     conn->le_connection_interval = hci_subevent_le_connection_complete_get_conn_interval(packet);
2434 
2435 #ifdef ENABLE_LE_PERIPHERAL
2436                     if (packet[6] == HCI_ROLE_SLAVE){
2437                         hci_reenable_advertisements_if_needed();
2438                     }
2439 #endif
2440 
2441                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
2442 
2443                     // restart timer
2444                     // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2445                     // btstack_run_loop_add_timer(&conn->timeout);
2446 
2447                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2448 
2449                     hci_emit_nr_connections_changed();
2450                     break;
2451 
2452                 // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
2453                 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
2454                     handle = hci_subevent_le_connection_update_complete_get_connection_handle(packet);
2455                     conn = hci_connection_for_handle(handle);
2456                     if (!conn) break;
2457                     conn->le_connection_interval = hci_subevent_le_connection_update_complete_get_conn_interval(packet);
2458                     break;
2459 
2460                 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
2461                     // connection
2462                     handle = hci_subevent_le_remote_connection_parameter_request_get_connection_handle(packet);
2463                     conn = hci_connection_for_handle(handle);
2464                     if (conn) {
2465                         // read arguments
2466                         uint16_t le_conn_interval_min   = hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet);
2467                         uint16_t le_conn_interval_max   = hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet);
2468                         uint16_t le_conn_latency        = hci_subevent_le_remote_connection_parameter_request_get_latency(packet);
2469                         uint16_t le_supervision_timeout = hci_subevent_le_remote_connection_parameter_request_get_timeout(packet);
2470 
2471                         // validate against current connection parameter range
2472                         le_connection_parameter_range_t existing_range;
2473                         gap_get_connection_parameter_range(&existing_range);
2474                         int update_parameter = gap_connection_parameter_range_included(&existing_range, le_conn_interval_min, le_conn_interval_max, le_conn_latency, le_supervision_timeout);
2475                         if (update_parameter){
2476                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_REPLY;
2477                             conn->le_conn_interval_min = le_conn_interval_min;
2478                             conn->le_conn_interval_max = le_conn_interval_max;
2479                             conn->le_conn_latency = le_conn_latency;
2480                             conn->le_supervision_timeout = le_supervision_timeout;
2481                         } else {
2482                             conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_DENY;
2483                         }
2484                     }
2485                     break;
2486                 default:
2487                     break;
2488             }
2489             break;
2490 #endif
2491         case HCI_EVENT_VENDOR_SPECIFIC:
2492             // Vendor specific commands often create vendor specific event instead of num completed packets
2493             // To avoid getting stuck as num_cmds_packets is zero, reset it to 1 for controllers with this behaviour
2494             switch (hci_stack->manufacturer){
2495                 case BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO:
2496                     hci_stack->num_cmd_packets = 1;
2497                     break;
2498                 default:
2499                     break;
2500             }
2501             break;
2502         default:
2503             break;
2504     }
2505 
2506     // handle BT initialization
2507     if (hci_stack->state == HCI_STATE_INITIALIZING){
2508         hci_initializing_event_handler(packet, size);
2509     }
2510 
2511     // help with BT sleep
2512     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
2513         && hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE
2514         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
2515         hci_initializing_next_state();
2516     }
2517 
2518     // notify upper stack
2519 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
2520 
2521     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
2522     if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){
2523         if (!packet[2]){
2524             handle = little_endian_read_16(packet, 3);
2525             hci_connection_t * aConn = hci_connection_for_handle(handle);
2526             if (aConn) {
2527                 uint8_t status = aConn->bonding_status;
2528                 uint16_t flags = aConn->bonding_flags;
2529                 bd_addr_t bd_address;
2530                 memcpy(&bd_address, aConn->address, 6);
2531                 hci_shutdown_connection(aConn);
2532                 // connection struct is gone, don't access anymore
2533                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
2534                     hci_emit_dedicated_bonding_result(bd_address, status);
2535                 }
2536             }
2537         }
2538     }
2539 
2540 	// execute main loop
2541 	hci_run();
2542 }
2543 
2544 #ifdef ENABLE_CLASSIC
2545 static void sco_handler(uint8_t * packet, uint16_t size){
2546     // lookup connection struct
2547     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
2548     hci_connection_t * conn     = hci_connection_for_handle(con_handle);
2549     if (!conn) return;
2550 
2551     int notify_sco = 0;
2552 
2553     // CSR 8811 prefixes 60 byte SCO packet in transparent mode with 20 zero bytes -> skip first 20 payload bytes
2554     if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_CAMBRIDGE_SILICON_RADIO){
2555         if (size == 83 && ((hci_stack->sco_voice_setting_active & 0x03) == 0x03)){
2556             packet[2] = 0x3c;
2557             memmove(&packet[3], &packet[23], 63);
2558             size = 63;
2559         }
2560     }
2561 
2562     // treat received SCO packets as indicator of successfully sent packet, if flow control is not explicite
2563     log_debug("sco flow %u, handle 0x%04x, packets sent %u, bytes send %u", hci_stack->synchronous_flow_control_enabled, (int) con_handle, conn->num_packets_sent, conn->num_sco_bytes_sent);
2564     if (hci_stack->synchronous_flow_control_enabled == 0){
2565         uint16_t sco_payload_len = size - 3;
2566         if (conn->num_sco_bytes_sent >= sco_payload_len){
2567             conn->num_sco_bytes_sent -= sco_payload_len;
2568         } else {
2569             conn->num_sco_bytes_sent = 0;
2570         }
2571         notify_sco = 1;
2572     }
2573     // deliver to app
2574     if (hci_stack->sco_packet_handler) {
2575         hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
2576     }
2577 
2578     // notify app if it can send again
2579     if (notify_sco){
2580         hci_notify_if_sco_can_send_now();
2581     }
2582 
2583 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2584     conn->num_packets_completed++;
2585     hci_stack->host_completed_packets = 1;
2586     hci_run();
2587 #endif
2588 }
2589 #endif
2590 
2591 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
2592     hci_dump_packet(packet_type, 1, packet, size);
2593     switch (packet_type) {
2594         case HCI_EVENT_PACKET:
2595             event_handler(packet, size);
2596             break;
2597         case HCI_ACL_DATA_PACKET:
2598             acl_handler(packet, size);
2599             break;
2600 #ifdef ENABLE_CLASSIC
2601         case HCI_SCO_DATA_PACKET:
2602             sco_handler(packet, size);
2603             break;
2604 #endif
2605         default:
2606             break;
2607     }
2608 }
2609 
2610 /**
2611  * @brief Add event packet handler.
2612  */
2613 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
2614     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
2615 }
2616 
2617 
2618 /** Register HCI packet handlers */
2619 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
2620     hci_stack->acl_packet_handler = handler;
2621 }
2622 
2623 #ifdef ENABLE_CLASSIC
2624 /**
2625  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
2626  */
2627 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
2628     hci_stack->sco_packet_handler = handler;
2629 }
2630 #endif
2631 
2632 static void hci_state_reset(void){
2633     // no connections yet
2634     hci_stack->connections = NULL;
2635 
2636     // keep discoverable/connectable as this has been requested by the client(s)
2637     // hci_stack->discoverable = 0;
2638     // hci_stack->connectable = 0;
2639     // hci_stack->bondable = 1;
2640     // hci_stack->own_addr_type = 0;
2641 
2642     // buffer is free
2643     hci_stack->hci_packet_buffer_reserved = 0;
2644 
2645     // no pending cmds
2646     hci_stack->decline_reason = 0;
2647     hci_stack->new_scan_enable_value = 0xff;
2648 
2649     // LE
2650 #ifdef ENABLE_BLE
2651     memset(hci_stack->le_random_address, 0, 6);
2652     hci_stack->le_random_address_set = 0;
2653 #endif
2654 #ifdef ENABLE_LE_CENTRAL
2655     hci_stack->le_scanning_active  = 0;
2656     hci_stack->le_scan_type = 0xff;
2657     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2658     hci_stack->le_whitelist = 0;
2659     hci_stack->le_whitelist_capacity = 0;
2660 #endif
2661 }
2662 
2663 #ifdef ENABLE_CLASSIC
2664 /**
2665  * @brief Configure Bluetooth hardware control. Has to be called before power on.
2666  */
2667 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
2668     // store and open remote device db
2669     hci_stack->link_key_db = link_key_db;
2670     if (hci_stack->link_key_db) {
2671         hci_stack->link_key_db->open();
2672     }
2673 }
2674 #endif
2675 
2676 void hci_init(const hci_transport_t *transport, const void *config){
2677 
2678 #ifdef HAVE_MALLOC
2679     if (!hci_stack) {
2680         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
2681     }
2682 #else
2683     hci_stack = &hci_stack_static;
2684 #endif
2685     memset(hci_stack, 0, sizeof(hci_stack_t));
2686 
2687     // reference to use transport layer implementation
2688     hci_stack->hci_transport = transport;
2689 
2690     // reference to used config
2691     hci_stack->config = config;
2692 
2693     // setup pointer for outgoing packet buffer
2694     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
2695 
2696     // max acl payload size defined in config.h
2697     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
2698 
2699     // register packet handlers with transport
2700     transport->register_packet_handler(&packet_handler);
2701 
2702     hci_stack->state = HCI_STATE_OFF;
2703 
2704     // class of device
2705     hci_stack->class_of_device = 0x007a020c; // Smartphone
2706 
2707     // bondable by default
2708     hci_stack->bondable = 1;
2709 
2710 #ifdef ENABLE_CLASSIC
2711     // classic name
2712     hci_stack->local_name = default_classic_name;
2713 
2714     // Master slave policy
2715     hci_stack->master_slave_policy = 1;
2716 #endif
2717 
2718     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
2719     hci_stack->ssp_enable = 1;
2720     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
2721     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
2722     hci_stack->ssp_auto_accept = 1;
2723 
2724     // voice setting - signed 16 bit pcm data with CVSD over the air
2725     hci_stack->sco_voice_setting = 0x60;
2726 
2727 #ifdef ENABLE_LE_CENTRAL
2728     // connection parameter to use for outgoing connections
2729     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
2730     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
2731     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
2732     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
2733     hci_stack->le_connection_latency      = 4;         // 4
2734     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
2735     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
2736     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
2737 #endif
2738 
2739 #ifdef ENABLE_LE_PERIPHERAL
2740     hci_stack->le_max_number_peripheral_connections = 1; // only single connection as peripheral
2741 #endif
2742 
2743     // connection parameter range used to answer connection parameter update requests in l2cap
2744     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
2745     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
2746     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
2747     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
2748     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
2749     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
2750 
2751     hci_state_reset();
2752 }
2753 
2754 /**
2755  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
2756  */
2757 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
2758     hci_stack->chipset = chipset_driver;
2759 
2760     // reset chipset driver - init is also called on power_up
2761     if (hci_stack->chipset && hci_stack->chipset->init){
2762         hci_stack->chipset->init(hci_stack->config);
2763     }
2764 }
2765 
2766 /**
2767  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
2768  */
2769 void hci_set_control(const btstack_control_t *hardware_control){
2770     // references to used control implementation
2771     hci_stack->control = hardware_control;
2772     // init with transport config
2773     hardware_control->init(hci_stack->config);
2774 }
2775 
2776 void hci_close(void){
2777     // close remote device db
2778     if (hci_stack->link_key_db) {
2779         hci_stack->link_key_db->close();
2780     }
2781 
2782     btstack_linked_list_iterator_t lit;
2783     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
2784     while (btstack_linked_list_iterator_has_next(&lit)){
2785         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
2786         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
2787         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
2788         hci_shutdown_connection(connection);
2789     }
2790 
2791     hci_power_control(HCI_POWER_OFF);
2792 
2793 #ifdef HAVE_MALLOC
2794     free(hci_stack);
2795 #endif
2796     hci_stack = NULL;
2797 }
2798 
2799 #ifdef ENABLE_CLASSIC
2800 void gap_set_class_of_device(uint32_t class_of_device){
2801     hci_stack->class_of_device = class_of_device;
2802 }
2803 
2804 void gap_set_default_link_policy_settings(uint16_t default_link_policy_settings){
2805     hci_stack->default_link_policy_settings = default_link_policy_settings;
2806 }
2807 
2808 void hci_disable_l2cap_timeout_check(void){
2809     disable_l2cap_timeouts = 1;
2810 }
2811 #endif
2812 
2813 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
2814 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
2815 void hci_set_bd_addr(bd_addr_t addr){
2816     memcpy(hci_stack->custom_bd_addr, addr, 6);
2817     hci_stack->custom_bd_addr_set = 1;
2818 }
2819 #endif
2820 
2821 // State-Module-Driver overview
2822 // state                    module  low-level
2823 // HCI_STATE_OFF             off      close
2824 // HCI_STATE_INITIALIZING,   on       open
2825 // HCI_STATE_WORKING,        on       open
2826 // HCI_STATE_HALTING,        on       open
2827 // HCI_STATE_SLEEPING,    off/sleep   close
2828 // HCI_STATE_FALLING_ASLEEP  on       open
2829 
2830 static int hci_power_control_on(void){
2831 
2832     // power on
2833     int err = 0;
2834     if (hci_stack->control && hci_stack->control->on){
2835         err = (*hci_stack->control->on)();
2836     }
2837     if (err){
2838         log_error( "POWER_ON failed");
2839         hci_emit_hci_open_failed();
2840         return err;
2841     }
2842 
2843     // int chipset driver
2844     if (hci_stack->chipset && hci_stack->chipset->init){
2845         hci_stack->chipset->init(hci_stack->config);
2846     }
2847 
2848     // init transport
2849     if (hci_stack->hci_transport->init){
2850         hci_stack->hci_transport->init(hci_stack->config);
2851     }
2852 
2853     // open transport
2854     err = hci_stack->hci_transport->open();
2855     if (err){
2856         log_error( "HCI_INIT failed, turning Bluetooth off again");
2857         if (hci_stack->control && hci_stack->control->off){
2858             (*hci_stack->control->off)();
2859         }
2860         hci_emit_hci_open_failed();
2861         return err;
2862     }
2863     return 0;
2864 }
2865 
2866 static void hci_power_control_off(void){
2867 
2868     log_info("hci_power_control_off");
2869 
2870     // close low-level device
2871     hci_stack->hci_transport->close();
2872 
2873     log_info("hci_power_control_off - hci_transport closed");
2874 
2875     // power off
2876     if (hci_stack->control && hci_stack->control->off){
2877         (*hci_stack->control->off)();
2878     }
2879 
2880     log_info("hci_power_control_off - control closed");
2881 
2882     hci_stack->state = HCI_STATE_OFF;
2883 }
2884 
2885 static void hci_power_control_sleep(void){
2886 
2887     log_info("hci_power_control_sleep");
2888 
2889 #if 0
2890     // don't close serial port during sleep
2891 
2892     // close low-level device
2893     hci_stack->hci_transport->close(hci_stack->config);
2894 #endif
2895 
2896     // sleep mode
2897     if (hci_stack->control && hci_stack->control->sleep){
2898         (*hci_stack->control->sleep)();
2899     }
2900 
2901     hci_stack->state = HCI_STATE_SLEEPING;
2902 }
2903 
2904 static int hci_power_control_wake(void){
2905 
2906     log_info("hci_power_control_wake");
2907 
2908     // wake on
2909     if (hci_stack->control && hci_stack->control->wake){
2910         (*hci_stack->control->wake)();
2911     }
2912 
2913 #if 0
2914     // open low-level device
2915     int err = hci_stack->hci_transport->open(hci_stack->config);
2916     if (err){
2917         log_error( "HCI_INIT failed, turning Bluetooth off again");
2918         if (hci_stack->control && hci_stack->control->off){
2919             (*hci_stack->control->off)();
2920         }
2921         hci_emit_hci_open_failed();
2922         return err;
2923     }
2924 #endif
2925 
2926     return 0;
2927 }
2928 
2929 static void hci_power_transition_to_initializing(void){
2930     // set up state machine
2931     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
2932     hci_stack->hci_packet_buffer_reserved = 0;
2933     hci_stack->state = HCI_STATE_INITIALIZING;
2934     hci_stack->substate = HCI_INIT_SEND_RESET;
2935 }
2936 
2937 int hci_power_control(HCI_POWER_MODE power_mode){
2938 
2939     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
2940 
2941     int err = 0;
2942     switch (hci_stack->state){
2943 
2944         case HCI_STATE_OFF:
2945             switch (power_mode){
2946                 case HCI_POWER_ON:
2947                     err = hci_power_control_on();
2948                     if (err) {
2949                         log_error("hci_power_control_on() error %d", err);
2950                         return err;
2951                     }
2952                     hci_power_transition_to_initializing();
2953                     break;
2954                 case HCI_POWER_OFF:
2955                     // do nothing
2956                     break;
2957                 case HCI_POWER_SLEEP:
2958                     // do nothing (with SLEEP == OFF)
2959                     break;
2960             }
2961             break;
2962 
2963         case HCI_STATE_INITIALIZING:
2964             switch (power_mode){
2965                 case HCI_POWER_ON:
2966                     // do nothing
2967                     break;
2968                 case HCI_POWER_OFF:
2969                     // no connections yet, just turn it off
2970                     hci_power_control_off();
2971                     break;
2972                 case HCI_POWER_SLEEP:
2973                     // no connections yet, just turn it off
2974                     hci_power_control_sleep();
2975                     break;
2976             }
2977             break;
2978 
2979         case HCI_STATE_WORKING:
2980             switch (power_mode){
2981                 case HCI_POWER_ON:
2982                     // do nothing
2983                     break;
2984                 case HCI_POWER_OFF:
2985                     // see hci_run
2986                     hci_stack->state = HCI_STATE_HALTING;
2987                     hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
2988                     break;
2989                 case HCI_POWER_SLEEP:
2990                     // see hci_run
2991                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2992                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2993                     break;
2994             }
2995             break;
2996 
2997         case HCI_STATE_HALTING:
2998             switch (power_mode){
2999                 case HCI_POWER_ON:
3000                     hci_power_transition_to_initializing();
3001                     break;
3002                 case HCI_POWER_OFF:
3003                     // do nothing
3004                     break;
3005                 case HCI_POWER_SLEEP:
3006                     // see hci_run
3007                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
3008                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
3009                     break;
3010             }
3011             break;
3012 
3013         case HCI_STATE_FALLING_ASLEEP:
3014             switch (power_mode){
3015                 case HCI_POWER_ON:
3016 
3017 #ifdef HAVE_PLATFORM_IPHONE_OS
3018                     // nothing to do, if H4 supports power management
3019                     if (btstack_control_iphone_power_management_enabled()){
3020                         hci_stack->state = HCI_STATE_INITIALIZING;
3021                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
3022                         break;
3023                     }
3024 #endif
3025                     hci_power_transition_to_initializing();
3026                     break;
3027                 case HCI_POWER_OFF:
3028                     // see hci_run
3029                     hci_stack->state = HCI_STATE_HALTING;
3030                     hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3031                     break;
3032                 case HCI_POWER_SLEEP:
3033                     // do nothing
3034                     break;
3035             }
3036             break;
3037 
3038         case HCI_STATE_SLEEPING:
3039             switch (power_mode){
3040                 case HCI_POWER_ON:
3041 
3042 #ifdef HAVE_PLATFORM_IPHONE_OS
3043                     // nothing to do, if H4 supports power management
3044                     if (btstack_control_iphone_power_management_enabled()){
3045                         hci_stack->state = HCI_STATE_INITIALIZING;
3046                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
3047                         hci_update_scan_enable();
3048                         break;
3049                     }
3050 #endif
3051                     err = hci_power_control_wake();
3052                     if (err) return err;
3053                     hci_power_transition_to_initializing();
3054                     break;
3055                 case HCI_POWER_OFF:
3056                     hci_stack->state = HCI_STATE_HALTING;
3057                     hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_NO_TIMER;
3058                     break;
3059                 case HCI_POWER_SLEEP:
3060                     // do nothing
3061                     break;
3062             }
3063             break;
3064     }
3065 
3066     // create internal event
3067 	hci_emit_state();
3068 
3069 	// trigger next/first action
3070 	hci_run();
3071 
3072     return 0;
3073 }
3074 
3075 
3076 #ifdef ENABLE_CLASSIC
3077 
3078 static void hci_update_scan_enable(void){
3079     // 2 = page scan, 1 = inq scan
3080     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
3081     hci_run();
3082 }
3083 
3084 void gap_discoverable_control(uint8_t enable){
3085     if (enable) enable = 1; // normalize argument
3086 
3087     if (hci_stack->discoverable == enable){
3088         hci_emit_discoverable_enabled(hci_stack->discoverable);
3089         return;
3090     }
3091 
3092     hci_stack->discoverable = enable;
3093     hci_update_scan_enable();
3094 }
3095 
3096 void gap_connectable_control(uint8_t enable){
3097     if (enable) enable = 1; // normalize argument
3098 
3099     // don't emit event
3100     if (hci_stack->connectable == enable) return;
3101 
3102     hci_stack->connectable = enable;
3103     hci_update_scan_enable();
3104 }
3105 #endif
3106 
3107 void gap_local_bd_addr(bd_addr_t address_buffer){
3108     memcpy(address_buffer, hci_stack->local_bd_addr, 6);
3109 }
3110 
3111 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3112 static void hci_host_num_completed_packets(void){
3113 
3114     // create packet manually as arrays are not supported and num_commands should not get reduced
3115     hci_reserve_packet_buffer();
3116     uint8_t * packet = hci_get_outgoing_packet_buffer();
3117 
3118     uint16_t size = 0;
3119     uint16_t num_handles = 0;
3120     packet[size++] = 0x35;
3121     packet[size++] = 0x0c;
3122     size++;  // skip param len
3123     size++;  // skip num handles
3124 
3125     // add { handle, packets } entries
3126     btstack_linked_item_t * it;
3127     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3128         hci_connection_t * connection = (hci_connection_t *) it;
3129         if (connection->num_packets_completed){
3130             little_endian_store_16(packet, size, connection->con_handle);
3131             size += 2;
3132             little_endian_store_16(packet, size, connection->num_packets_completed);
3133             size += 2;
3134             //
3135             num_handles++;
3136             connection->num_packets_completed = 0;
3137         }
3138     }
3139 
3140     packet[2] = size - 3;
3141     packet[3] = num_handles;
3142 
3143     hci_stack->host_completed_packets = 0;
3144 
3145     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3146     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3147 
3148     // release packet buffer for synchronous transport implementations
3149     if (hci_transport_synchronous()){
3150         hci_release_packet_buffer();
3151         hci_emit_transport_packet_sent();
3152     }
3153 }
3154 #endif
3155 
3156 static void hci_halting_timeout_handler(btstack_timer_source_t * ds){
3157     UNUSED(ds);
3158     hci_stack->substate = HCI_HALTING_CLOSE;
3159     // allow packet handlers to defer final shutdown
3160     hci_emit_state();
3161     hci_run();
3162 }
3163 
3164 static void hci_run(void){
3165 
3166     // log_info("hci_run: entered");
3167     btstack_linked_item_t * it;
3168 
3169     // send continuation fragments first, as they block the prepared packet buffer
3170     if (hci_stack->acl_fragmentation_total_size > 0) {
3171         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
3172         hci_connection_t *connection = hci_connection_for_handle(con_handle);
3173         if (connection) {
3174             if (hci_can_send_prepared_acl_packet_now(con_handle)){
3175                 hci_send_acl_packet_fragments(connection);
3176                 return;
3177             }
3178         } else {
3179             // connection gone -> discard further fragments
3180             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
3181             hci_stack->acl_fragmentation_total_size = 0;
3182             hci_stack->acl_fragmentation_pos = 0;
3183         }
3184     }
3185 
3186 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
3187     // send host num completed packets next as they don't require num_cmd_packets > 0
3188     if (!hci_can_send_comand_packet_transport()) return;
3189     if (hci_stack->host_completed_packets){
3190         hci_host_num_completed_packets();
3191         return;
3192     }
3193 #endif
3194 
3195     if (!hci_can_send_command_packet_now()) return;
3196 
3197     // global/non-connection oriented commands
3198 
3199 #ifdef ENABLE_CLASSIC
3200     // decline incoming connections
3201     if (hci_stack->decline_reason){
3202         uint8_t reason = hci_stack->decline_reason;
3203         hci_stack->decline_reason = 0;
3204         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
3205         return;
3206     }
3207     // send scan enable
3208     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
3209         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
3210         hci_stack->new_scan_enable_value = 0xff;
3211         return;
3212     }
3213     // start/stop inquiry
3214     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN && hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX){
3215         uint8_t duration = hci_stack->inquiry_state;
3216         hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
3217         hci_send_cmd(&hci_inquiry, GAP_IAC_GENERAL_INQUIRY, duration, 0);
3218         return;
3219     }
3220     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
3221         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
3222         hci_send_cmd(&hci_inquiry_cancel);
3223         return;
3224     }
3225     // remote name request
3226     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
3227         hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
3228         hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
3229             hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
3230         return;
3231     }
3232     // pairing
3233     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
3234         uint8_t state = hci_stack->gap_pairing_state;
3235         hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
3236         switch (state){
3237             case GAP_PAIRING_STATE_SEND_PIN:
3238                 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);
3239                 break;
3240             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
3241                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
3242                 break;
3243             case GAP_PAIRING_STATE_SEND_PASSKEY:
3244                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_input.gap_pairing_passkey);
3245                 break;
3246             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
3247                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
3248                 break;
3249             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
3250                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
3251                 break;
3252             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
3253                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
3254                 break;
3255             default:
3256                 break;
3257         }
3258         return;
3259     }
3260 #endif
3261 
3262 #ifdef ENABLE_BLE
3263     // advertisements, active scanning, and creating connections requires randaom address to be set if using private address
3264     if ((hci_stack->state == HCI_STATE_WORKING)
3265     && (hci_stack->le_own_addr_type == BD_ADDR_TYPE_LE_PUBLIC || hci_stack->le_random_address_set)){
3266 
3267 #ifdef ENABLE_LE_CENTRAL
3268         // handle le scan
3269         if ((hci_stack->le_scanning_enabled != hci_stack->le_scanning_active)){
3270             hci_stack->le_scanning_active = hci_stack->le_scanning_enabled;
3271             hci_send_cmd(&hci_le_set_scan_enable, hci_stack->le_scanning_enabled, 0);
3272             return;
3273         }
3274         if (hci_stack->le_scan_type != 0xff){
3275             // defaults: active scanning, accept all advertisement packets
3276             int scan_type = hci_stack->le_scan_type;
3277             hci_stack->le_scan_type = 0xff;
3278             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);
3279             return;
3280         }
3281 #endif
3282 #ifdef ENABLE_LE_PERIPHERAL
3283         // le advertisement control
3284         if (hci_stack->le_advertisements_todo){
3285             log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo );
3286         }
3287         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){
3288             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE;
3289             hci_send_cmd(&hci_le_set_advertise_enable, 0);
3290             return;
3291         }
3292         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
3293             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3294             hci_send_cmd(&hci_le_set_advertising_parameters,
3295                  hci_stack->le_advertisements_interval_min,
3296                  hci_stack->le_advertisements_interval_max,
3297                  hci_stack->le_advertisements_type,
3298                  hci_stack->le_own_addr_type,
3299                  hci_stack->le_advertisements_direct_address_type,
3300                  hci_stack->le_advertisements_direct_address,
3301                  hci_stack->le_advertisements_channel_map,
3302                  hci_stack->le_advertisements_filter_policy);
3303             return;
3304         }
3305         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
3306             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3307             uint8_t adv_data_clean[31];
3308             memset(adv_data_clean, 0, sizeof(adv_data_clean));
3309             memcpy(adv_data_clean, hci_stack->le_advertisements_data, hci_stack->le_advertisements_data_len);
3310             hci_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len);
3311             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
3312             return;
3313         }
3314         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
3315             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
3316             uint8_t scan_data_clean[31];
3317             memset(scan_data_clean, 0, sizeof(scan_data_clean));
3318             memcpy(scan_data_clean, hci_stack->le_scan_response_data, hci_stack->le_scan_response_data_len);
3319             hci_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len);
3320             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, hci_stack->le_scan_response_data);
3321             return;
3322         }
3323         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){
3324             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE;
3325             hci_send_cmd(&hci_le_set_advertise_enable, 1);
3326             return;
3327         }
3328 #endif
3329 
3330 #ifdef ENABLE_LE_CENTRAL
3331         //
3332         // LE Whitelist Management
3333         //
3334 
3335         // check if whitelist needs modification
3336         btstack_linked_list_iterator_t lit;
3337         int modification_pending = 0;
3338         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3339         while (btstack_linked_list_iterator_has_next(&lit)){
3340             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3341             if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
3342                 modification_pending = 1;
3343                 break;
3344             }
3345         }
3346 
3347         if (modification_pending){
3348             // stop connnecting if modification pending
3349             if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){
3350                 hci_send_cmd(&hci_le_create_connection_cancel);
3351                 return;
3352             }
3353 
3354             // add/remove entries
3355             btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3356             while (btstack_linked_list_iterator_has_next(&lit)){
3357                 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3358                 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
3359                     entry->state = LE_WHITELIST_ON_CONTROLLER;
3360                     hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
3361                     return;
3362 
3363                 }
3364                 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
3365                     bd_addr_t address;
3366                     bd_addr_type_t address_type = entry->address_type;
3367                     memcpy(address, entry->address, 6);
3368                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3369                     btstack_memory_whitelist_entry_free(entry);
3370                     hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
3371                     return;
3372                 }
3373             }
3374         }
3375 
3376         // start connecting
3377         if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE &&
3378             !btstack_linked_list_empty(&hci_stack->le_whitelist)){
3379             bd_addr_t null_addr;
3380             memset(null_addr, 0, 6);
3381             hci_send_cmd(&hci_le_create_connection,
3382                 hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
3383                 hci_stack->le_connection_scan_window,    // scan interval: 30 ms
3384                  1,         // use whitelist
3385                  0,         // peer address type
3386                  null_addr, // peer bd addr
3387                  hci_stack->le_own_addr_type, // our addr type:
3388                  hci_stack->le_connection_interval_min,    // conn interval min
3389                  hci_stack->le_connection_interval_max,    // conn interval max
3390                  hci_stack->le_connection_latency,         // conn latency
3391                  hci_stack->le_supervision_timeout,        // conn latency
3392                  hci_stack->le_minimum_ce_length,          // min ce length
3393                  hci_stack->le_maximum_ce_length           // max ce length
3394                 );
3395             return;
3396         }
3397 #endif
3398     }
3399 #endif
3400 
3401     // send pending HCI commands
3402     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3403         hci_connection_t * connection = (hci_connection_t *) it;
3404 
3405         switch(connection->state){
3406             case SEND_CREATE_CONNECTION:
3407                 switch(connection->address_type){
3408 #ifdef ENABLE_CLASSIC
3409                     case BD_ADDR_TYPE_CLASSIC:
3410                         log_info("sending hci_create_connection");
3411                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
3412                         break;
3413 #endif
3414                     default:
3415 #ifdef ENABLE_BLE
3416 #ifdef ENABLE_LE_CENTRAL
3417                         // track outgoing connection
3418                         hci_stack->outgoing_addr_type = connection->address_type;
3419                         memcpy(hci_stack->outgoing_addr, connection->address, 6);
3420                         log_info("sending hci_le_create_connection");
3421                         hci_send_cmd(&hci_le_create_connection,
3422                              hci_stack->le_connection_scan_interval,    // conn scan interval
3423                              hci_stack->le_connection_scan_window,      // conn scan windows
3424                              0,         // don't use whitelist
3425                              connection->address_type, // peer address type
3426                              connection->address,      // peer bd addr
3427                              hci_stack->le_own_addr_type, // our addr type:
3428                              hci_stack->le_connection_interval_min,    // conn interval min
3429                              hci_stack->le_connection_interval_max,    // conn interval max
3430                              hci_stack->le_connection_latency,         // conn latency
3431                              hci_stack->le_supervision_timeout,        // conn latency
3432                              hci_stack->le_minimum_ce_length,          // min ce length
3433                              hci_stack->le_maximum_ce_length          // max ce length
3434                              );
3435                         connection->state = SENT_CREATE_CONNECTION;
3436 #endif
3437 #endif
3438                         break;
3439                 }
3440                 return;
3441 
3442 #ifdef ENABLE_CLASSIC
3443             case RECEIVED_CONNECTION_REQUEST:
3444                 connection->role  = HCI_ROLE_SLAVE;
3445                 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
3446                     log_info("sending hci_accept_connection_request, remote eSCO %u", connection->remote_supported_feature_eSCO);
3447                     connection->state = ACCEPTED_CONNECTION_REQUEST;
3448                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
3449                 }
3450                 return;
3451 #endif
3452 
3453 #ifdef ENABLE_BLE
3454 #ifdef ENABLE_LE_CENTRAL
3455             case SEND_CANCEL_CONNECTION:
3456                 connection->state = SENT_CANCEL_CONNECTION;
3457                 hci_send_cmd(&hci_le_create_connection_cancel);
3458                 return;
3459 #endif
3460 #endif
3461             case SEND_DISCONNECT:
3462                 connection->state = SENT_DISCONNECT;
3463                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
3464                 return;
3465 
3466             default:
3467                 break;
3468         }
3469 
3470         // no further commands if connection is about to get shut down
3471         if (connection->state == SENT_DISCONNECT) continue;
3472 
3473 #ifdef ENABLE_CLASSIC
3474         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
3475             log_info("responding to link key request");
3476             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
3477             link_key_t link_key;
3478             link_key_type_t link_key_type;
3479             if ( hci_stack->link_key_db
3480               && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type)
3481               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
3482                connection->link_key_type = link_key_type;
3483                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
3484             } else {
3485                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
3486             }
3487             return;
3488         }
3489 
3490         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
3491             log_info("denying to pin request");
3492             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
3493             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
3494             return;
3495         }
3496 
3497         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
3498             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
3499             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
3500             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
3501                 // tweak authentication requirements
3502                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
3503                 if (connection->bonding_flags & BONDING_DEDICATED){
3504                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
3505                 }
3506                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
3507                     authreq |= 1;
3508                 }
3509                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
3510             } else {
3511                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
3512             }
3513             return;
3514         }
3515 
3516         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
3517             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
3518             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
3519             return;
3520         }
3521 
3522         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
3523             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
3524             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
3525             return;
3526         }
3527 
3528         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
3529             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
3530             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
3531             return;
3532         }
3533 
3534         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
3535             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
3536             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
3537             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
3538             return;
3539         }
3540 
3541         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
3542             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
3543             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
3544             return;
3545         }
3546 
3547         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
3548             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
3549             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
3550             return;
3551         }
3552 #endif
3553 
3554         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
3555             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
3556             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
3557             return;
3558         }
3559 
3560 #ifdef ENABLE_CLASSIC
3561         uint16_t sniff_min_interval;
3562         switch (connection->sniff_min_interval){
3563             case 0:
3564                 break;
3565             case 0xffff:
3566                 connection->sniff_min_interval = 0;
3567                 hci_send_cmd(&hci_exit_sniff_mode, connection->con_handle);
3568                 return;
3569             default:
3570                 sniff_min_interval = connection->sniff_min_interval;
3571                 connection->sniff_min_interval = 0;
3572                 hci_send_cmd(&hci_sniff_mode, connection->con_handle, connection->sniff_max_interval, sniff_min_interval, connection->sniff_attempt, connection->sniff_timeout);
3573                 return;
3574         }
3575 #endif
3576 
3577 #ifdef ENABLE_BLE
3578         switch (connection->le_con_parameter_update_state){
3579             // response to L2CAP CON PARAMETER UPDATE REQUEST
3580             case CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS:
3581                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3582                 hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection->le_conn_interval_min,
3583                     connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
3584                     0x0000, 0xffff);
3585                 return;
3586             case CON_PARAMETER_UPDATE_REPLY:
3587                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3588                 hci_send_cmd(&hci_le_remote_connection_parameter_request_reply, connection->con_handle, connection->le_conn_interval_min,
3589                     connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
3590                     0x0000, 0xffff);
3591                 return;
3592             case CON_PARAMETER_UPDATE_NEGATIVE_REPLY:
3593                 connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3594                 hci_send_cmd(&hci_le_remote_connection_parameter_request_negative_reply, ERROR_CODE_UNSUPPORTED_LMP_PARAMETER_VALUE_UNSUPPORTED_LL_PARAMETER_VALUE);
3595                 return;
3596             default:
3597                 break;
3598         }
3599         if (connection->le_phy_update_all_phys != 0xff){
3600             uint8_t all_phys = connection->le_phy_update_all_phys;
3601             connection->le_phy_update_all_phys = 0xff;
3602             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);
3603             return;
3604         }
3605 #endif
3606     }
3607 
3608     hci_connection_t * connection;
3609     switch (hci_stack->state){
3610         case HCI_STATE_INITIALIZING:
3611             hci_initializing_run();
3612             break;
3613 
3614         case HCI_STATE_HALTING:
3615 
3616             log_info("HCI_STATE_HALTING, substate %x\n", hci_stack->substate);
3617             switch (hci_stack->substate){
3618                 case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
3619                 case HCI_HALTING_DISCONNECT_ALL_TIMER:
3620 
3621 #ifdef ENABLE_BLE
3622 #ifdef ENABLE_LE_CENTRAL
3623                     // free whitelist entries
3624                     {
3625                         btstack_linked_list_iterator_t lit;
3626                         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3627                         while (btstack_linked_list_iterator_has_next(&lit)){
3628                             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3629                             btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3630                             btstack_memory_whitelist_entry_free(entry);
3631                         }
3632                     }
3633 #endif
3634 #endif
3635                     // close all open connections
3636                     connection =  (hci_connection_t *) hci_stack->connections;
3637                     if (connection){
3638                         hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
3639                         if (!hci_can_send_command_packet_now()) return;
3640 
3641                         // check state
3642                         if (connection->state == SENT_DISCONNECT) return;
3643                         connection->state = SENT_DISCONNECT;
3644 
3645                         log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
3646 
3647                         // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
3648                         hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
3649 
3650                         // ... which would be ignored anyway as we shutdown (free) the connection now
3651                         hci_shutdown_connection(connection);
3652 
3653                         // finally, send the disconnect command
3654                         hci_send_cmd(&hci_disconnect, con_handle, 0x13);  // remote closed connection
3655                         return;
3656                     }
3657 
3658                     if (hci_stack->substate == HCI_HALTING_DISCONNECT_ALL_TIMER){
3659                         // no connections left, wait a bit to assert that btstack_cyrpto isn't waiting for an HCI event
3660                         log_info("HCI_STATE_HALTING: wait 50 ms");
3661                         hci_stack->substate = HCI_HALTING_W4_TIMER;
3662                         btstack_run_loop_set_timer(&hci_stack->timeout, 50);
3663                         btstack_run_loop_set_timer_handler(&hci_stack->timeout, hci_halting_timeout_handler);
3664                         btstack_run_loop_add_timer(&hci_stack->timeout);
3665                         break;
3666                     }
3667 
3668                     /* explicit fall-through */
3669 
3670                 case HCI_HALTING_CLOSE:
3671                     log_info("HCI_STATE_HALTING, calling off");
3672 
3673                     // switch mode
3674                     hci_power_control_off();
3675 
3676                     log_info("HCI_STATE_HALTING, emitting state");
3677                     hci_emit_state();
3678                     log_info("HCI_STATE_HALTING, done");
3679                     break;
3680 
3681                 case HCI_HALTING_W4_TIMER:
3682                     // keep waiting
3683 
3684                     break;
3685                 default:
3686                     break;
3687             }
3688 
3689             break;
3690 
3691         case HCI_STATE_FALLING_ASLEEP:
3692             switch(hci_stack->substate) {
3693                 case HCI_FALLING_ASLEEP_DISCONNECT:
3694                     log_info("HCI_STATE_FALLING_ASLEEP");
3695                     // close all open connections
3696                     connection =  (hci_connection_t *) hci_stack->connections;
3697 
3698 #ifdef HAVE_PLATFORM_IPHONE_OS
3699                     // don't close connections, if H4 supports power management
3700                     if (btstack_control_iphone_power_management_enabled()){
3701                         connection = NULL;
3702                     }
3703 #endif
3704                     if (connection){
3705 
3706                         // send disconnect
3707                         if (!hci_can_send_command_packet_now()) return;
3708 
3709                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
3710                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
3711 
3712                         // send disconnected event right away - causes higher layer connections to get closed, too.
3713                         hci_shutdown_connection(connection);
3714                         return;
3715                     }
3716 
3717                     if (hci_classic_supported()){
3718                         // disable page and inquiry scan
3719                         if (!hci_can_send_command_packet_now()) return;
3720 
3721                         log_info("HCI_STATE_HALTING, disabling inq scans");
3722                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
3723 
3724                         // continue in next sub state
3725                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
3726                         break;
3727                     }
3728                     // no break - fall through for ble-only chips
3729 
3730                 case HCI_FALLING_ASLEEP_COMPLETE:
3731                     log_info("HCI_STATE_HALTING, calling sleep");
3732 #ifdef HAVE_PLATFORM_IPHONE_OS
3733                     // don't actually go to sleep, if H4 supports power management
3734                     if (btstack_control_iphone_power_management_enabled()){
3735                         // SLEEP MODE reached
3736                         hci_stack->state = HCI_STATE_SLEEPING;
3737                         hci_emit_state();
3738                         break;
3739                     }
3740 #endif
3741                     // switch mode
3742                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
3743                     hci_emit_state();
3744                     break;
3745 
3746                 default:
3747                     break;
3748             }
3749             break;
3750 
3751         default:
3752             break;
3753     }
3754 }
3755 
3756 int hci_send_cmd_packet(uint8_t *packet, int size){
3757     // house-keeping
3758 
3759     if (IS_COMMAND(packet, hci_write_loopback_mode)){
3760         hci_stack->loopback_mode = packet[3];
3761     }
3762 
3763 #ifdef ENABLE_CLASSIC
3764     bd_addr_t addr;
3765     hci_connection_t * conn;
3766 
3767     // create_connection?
3768     if (IS_COMMAND(packet, hci_create_connection)){
3769         reverse_bd_addr(&packet[3], addr);
3770         log_info("Create_connection to %s", bd_addr_to_str(addr));
3771 
3772         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3773         if (!conn){
3774             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3775             if (!conn){
3776                 // notify client that alloc failed
3777                 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3778                 return -1; // packet not sent to controller
3779             }
3780             conn->state = SEND_CREATE_CONNECTION;
3781         }
3782         log_info("conn state %u", conn->state);
3783         switch (conn->state){
3784             // if connection active exists
3785             case OPEN:
3786                 // and OPEN, emit connection complete command
3787                 hci_emit_connection_complete(addr, conn->con_handle, 0);
3788                 return -1; // packet not sent to controller
3789             case SEND_CREATE_CONNECTION:
3790                 // connection created by hci, e.g. dedicated bonding, but not executed yet, let's do it now
3791                 break;
3792             default:
3793                 // otherwise, just ignore as it is already in the open process
3794                 return -1; // packet not sent to controller
3795         }
3796         conn->state = SENT_CREATE_CONNECTION;
3797 
3798         // track outgoing connection
3799         hci_stack->outgoing_addr_type = BD_ADDR_TYPE_CLASSIC;
3800         memcpy(hci_stack->outgoing_addr, addr, 6);
3801     }
3802 
3803     if (IS_COMMAND(packet, hci_link_key_request_reply)){
3804         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
3805     }
3806     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
3807         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
3808     }
3809 
3810     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
3811         if (hci_stack->link_key_db){
3812             reverse_bd_addr(&packet[3], addr);
3813             hci_stack->link_key_db->delete_link_key(addr);
3814         }
3815     }
3816 
3817     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
3818     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
3819         reverse_bd_addr(&packet[3], addr);
3820         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3821         if (conn){
3822             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
3823         }
3824     }
3825 
3826     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
3827     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
3828     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
3829     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
3830         reverse_bd_addr(&packet[3], addr);
3831         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3832         if (conn){
3833             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
3834         }
3835     }
3836 
3837 #ifdef ENABLE_SCO_OVER_HCI
3838     // setup_synchronous_connection? Voice setting at offset 22
3839     if (IS_COMMAND(packet, hci_setup_synchronous_connection)){
3840         // TODO: compare to current setting if sco connection already active
3841         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
3842     }
3843     // accept_synchronus_connection? Voice setting at offset 18
3844     if (IS_COMMAND(packet, hci_accept_synchronous_connection)){
3845         // TODO: compare to current setting if sco connection already active
3846         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
3847     }
3848 #endif
3849 #endif
3850 
3851 #ifdef ENABLE_BLE
3852 #ifdef ENABLE_LE_PERIPHERAL
3853     if (IS_COMMAND(packet, hci_le_set_random_address)){
3854         hci_stack->le_random_address_set = 1;
3855         reverse_bd_addr(&packet[3], hci_stack->le_random_address);
3856     }
3857     if (IS_COMMAND(packet, hci_le_set_advertise_enable)){
3858         hci_stack->le_advertisements_active = packet[3];
3859     }
3860 #endif
3861 #ifdef ENABLE_LE_CENTRAL
3862     if (IS_COMMAND(packet, hci_le_create_connection)){
3863         // white list used?
3864         uint8_t initiator_filter_policy = packet[7];
3865         switch (initiator_filter_policy){
3866             case 0:
3867                 // whitelist not used
3868                 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
3869                 break;
3870             case 1:
3871                 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
3872                 break;
3873             default:
3874                 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
3875                 break;
3876         }
3877     }
3878     if (IS_COMMAND(packet, hci_le_create_connection_cancel)){
3879         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3880     }
3881 #endif
3882 #endif
3883 
3884     hci_stack->num_cmd_packets--;
3885 
3886     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3887     return hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3888 }
3889 
3890 // disconnect because of security block
3891 void hci_disconnect_security_block(hci_con_handle_t con_handle){
3892     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3893     if (!connection) return;
3894     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3895 }
3896 
3897 
3898 // Configure Secure Simple Pairing
3899 
3900 #ifdef ENABLE_CLASSIC
3901 
3902 // enable will enable SSP during init
3903 void gap_ssp_set_enable(int enable){
3904     hci_stack->ssp_enable = enable;
3905 }
3906 
3907 static int hci_local_ssp_activated(void){
3908     return gap_ssp_supported() && hci_stack->ssp_enable;
3909 }
3910 
3911 // if set, BTstack will respond to io capability request using authentication requirement
3912 void gap_ssp_set_io_capability(int io_capability){
3913     hci_stack->ssp_io_capability = io_capability;
3914 }
3915 void gap_ssp_set_authentication_requirement(int authentication_requirement){
3916     hci_stack->ssp_authentication_requirement = authentication_requirement;
3917 }
3918 
3919 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
3920 void gap_ssp_set_auto_accept(int auto_accept){
3921     hci_stack->ssp_auto_accept = auto_accept;
3922 }
3923 #endif
3924 
3925 // va_list part of hci_send_cmd
3926 int hci_send_cmd_va_arg(const hci_cmd_t *cmd, va_list argptr){
3927     if (!hci_can_send_command_packet_now()){
3928         log_error("hci_send_cmd called but cannot send packet now");
3929         return 0;
3930     }
3931 
3932     // for HCI INITIALIZATION
3933     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
3934     hci_stack->last_cmd_opcode = cmd->opcode;
3935 
3936     hci_reserve_packet_buffer();
3937     uint8_t * packet = hci_stack->hci_packet_buffer;
3938     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
3939     int err = hci_send_cmd_packet(packet, size);
3940 
3941     // release packet buffer for synchronous transport implementations
3942     if (hci_transport_synchronous()){
3943         hci_release_packet_buffer();
3944         hci_emit_transport_packet_sent();
3945     }
3946 
3947     return err;
3948 }
3949 
3950 /**
3951  * pre: numcmds >= 0 - it's allowed to send a command to the controller
3952  */
3953 int hci_send_cmd(const hci_cmd_t *cmd, ...){
3954     va_list argptr;
3955     va_start(argptr, cmd);
3956     int res = hci_send_cmd_va_arg(cmd, argptr);
3957     va_end(argptr);
3958     return res;
3959 }
3960 
3961 // Create various non-HCI events.
3962 // TODO: generalize, use table similar to hci_create_command
3963 
3964 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
3965     // dump packet
3966     if (dump) {
3967         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
3968     }
3969 
3970     // dispatch to all event handlers
3971     btstack_linked_list_iterator_t it;
3972     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
3973     while (btstack_linked_list_iterator_has_next(&it)){
3974         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
3975         entry->callback(HCI_EVENT_PACKET, 0, event, size);
3976     }
3977 }
3978 
3979 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
3980     if (!hci_stack->acl_packet_handler) return;
3981     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
3982 }
3983 
3984 #ifdef ENABLE_CLASSIC
3985 static void hci_notify_if_sco_can_send_now(void){
3986     // notify SCO sender if waiting
3987     if (!hci_stack->sco_waiting_for_can_send_now) return;
3988     if (hci_can_send_sco_packet_now()){
3989         hci_stack->sco_waiting_for_can_send_now = 0;
3990         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
3991         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
3992         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
3993     }
3994 }
3995 
3996 // parsing end emitting has been merged to reduce code size
3997 static void gap_inquiry_explode(uint8_t * packet){
3998     uint8_t event[19+GAP_INQUIRY_MAX_NAME_LEN];
3999 
4000     uint8_t * eir_data;
4001     ad_context_t context;
4002     const uint8_t * name;
4003     uint8_t         name_len;
4004 
4005     int event_type = hci_event_packet_get_type(packet);
4006     int num_reserved_fields = event_type == HCI_EVENT_INQUIRY_RESULT ? 2 : 1;    // 2 for old event, 1 otherwise
4007     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
4008 
4009     // event[1] is set at the end
4010     int i;
4011     for (i=0; i<num_responses;i++){
4012         memset(event, 0, sizeof(event));
4013         event[0] = GAP_EVENT_INQUIRY_RESULT;
4014         uint8_t event_size = 18;    // if name is not set by EIR
4015 
4016         memcpy(&event[2],  &packet[3 +                                             i*6], 6); // bd_addr
4017         event[8] =          packet[3 + num_responses*(6)                         + i*1];     // page_scan_repetition_mode
4018         memcpy(&event[9],  &packet[3 + num_responses*(6+1+num_reserved_fields)   + i*3], 3); // class of device
4019         memcpy(&event[12], &packet[3 + num_responses*(6+1+num_reserved_fields+3) + i*2], 2); // clock offset
4020 
4021         switch (event_type){
4022             case HCI_EVENT_INQUIRY_RESULT:
4023                 // 14,15,16,17 = 0, size 18
4024                 break;
4025             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
4026                 event[14] = 1;
4027                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
4028                 // 16,17 = 0, size 18
4029                 break;
4030             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
4031                 event[14] = 1;
4032                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
4033                 // for EIR packets, there is only one reponse in it
4034                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
4035                 name = NULL;
4036                 // EIR data is 240 bytes in EIR event
4037                 for (ad_iterator_init(&context, 240, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
4038                     uint8_t data_type    = ad_iterator_get_data_type(&context);
4039                     uint8_t data_size    = ad_iterator_get_data_len(&context);
4040                     const uint8_t * data = ad_iterator_get_data(&context);
4041                     // Prefer Complete Local Name over Shortend Local Name
4042                     switch (data_type){
4043                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
4044                             if (name) continue;
4045                             /* explicit fall-through */
4046                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
4047                             name = data;
4048                             name_len = data_size;
4049                             break;
4050                         default:
4051                             break;
4052                     }
4053                 }
4054                 if (name){
4055                     event[16] = 1;
4056                     // truncate name if needed
4057                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
4058                     event[17] = len;
4059                     memcpy(&event[18], name, len);
4060                     event_size += len;
4061                 }
4062                 break;
4063         }
4064         event[1] = event_size - 2;
4065         hci_emit_event(event, event_size, 1);
4066     }
4067 }
4068 #endif
4069 
4070 void hci_emit_state(void){
4071     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
4072     uint8_t event[3];
4073     event[0] = BTSTACK_EVENT_STATE;
4074     event[1] = sizeof(event) - 2;
4075     event[2] = hci_stack->state;
4076     hci_emit_event(event, sizeof(event), 1);
4077 }
4078 
4079 #ifdef ENABLE_CLASSIC
4080 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
4081     uint8_t event[13];
4082     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
4083     event[1] = sizeof(event) - 2;
4084     event[2] = status;
4085     little_endian_store_16(event, 3, con_handle);
4086     reverse_bd_addr(address, &event[5]);
4087     event[11] = 1; // ACL connection
4088     event[12] = 0; // encryption disabled
4089     hci_emit_event(event, sizeof(event), 1);
4090 }
4091 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
4092     if (disable_l2cap_timeouts) return;
4093     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
4094     uint8_t event[4];
4095     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
4096     event[1] = sizeof(event) - 2;
4097     little_endian_store_16(event, 2, conn->con_handle);
4098     hci_emit_event(event, sizeof(event), 1);
4099 }
4100 #endif
4101 
4102 #ifdef ENABLE_BLE
4103 #ifdef ENABLE_LE_CENTRAL
4104 static void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
4105     uint8_t event[21];
4106     event[0] = HCI_EVENT_LE_META;
4107     event[1] = sizeof(event) - 2;
4108     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
4109     event[3] = status;
4110     little_endian_store_16(event, 4, con_handle);
4111     event[6] = 0; // TODO: role
4112     event[7] = address_type;
4113     reverse_bd_addr(address, &event[8]);
4114     little_endian_store_16(event, 14, 0); // interval
4115     little_endian_store_16(event, 16, 0); // latency
4116     little_endian_store_16(event, 18, 0); // supervision timeout
4117     event[20] = 0; // master clock accuracy
4118     hci_emit_event(event, sizeof(event), 1);
4119 }
4120 #endif
4121 #endif
4122 
4123 static void hci_emit_transport_packet_sent(void){
4124     // notify upper stack that it might be possible to send again
4125     uint8_t event[] = { HCI_EVENT_TRANSPORT_PACKET_SENT, 0};
4126     hci_emit_event(&event[0], sizeof(event), 0);  // don't dump
4127 }
4128 
4129 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
4130     uint8_t event[6];
4131     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
4132     event[1] = sizeof(event) - 2;
4133     event[2] = 0; // status = OK
4134     little_endian_store_16(event, 3, con_handle);
4135     event[5] = reason;
4136     hci_emit_event(event, sizeof(event), 1);
4137 }
4138 
4139 static void hci_emit_nr_connections_changed(void){
4140     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
4141     uint8_t event[3];
4142     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
4143     event[1] = sizeof(event) - 2;
4144     event[2] = nr_hci_connections();
4145     hci_emit_event(event, sizeof(event), 1);
4146 }
4147 
4148 static void hci_emit_hci_open_failed(void){
4149     log_info("BTSTACK_EVENT_POWERON_FAILED");
4150     uint8_t event[2];
4151     event[0] = BTSTACK_EVENT_POWERON_FAILED;
4152     event[1] = sizeof(event) - 2;
4153     hci_emit_event(event, sizeof(event), 1);
4154 }
4155 
4156 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
4157     log_info("hci_emit_dedicated_bonding_result %u ", status);
4158     uint8_t event[9];
4159     int pos = 0;
4160     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
4161     event[pos++] = sizeof(event) - 2;
4162     event[pos++] = status;
4163     reverse_bd_addr(address, &event[pos]);
4164     hci_emit_event(event, sizeof(event), 1);
4165 }
4166 
4167 
4168 #ifdef ENABLE_CLASSIC
4169 
4170 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
4171     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
4172     uint8_t event[5];
4173     int pos = 0;
4174     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
4175     event[pos++] = sizeof(event) - 2;
4176     little_endian_store_16(event, 2, con_handle);
4177     pos += 2;
4178     event[pos++] = level;
4179     hci_emit_event(event, sizeof(event), 1);
4180 }
4181 
4182 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
4183     if (!connection) return LEVEL_0;
4184     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
4185     return gap_security_level_for_link_key_type(connection->link_key_type);
4186 }
4187 
4188 static void hci_emit_discoverable_enabled(uint8_t enabled){
4189     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
4190     uint8_t event[3];
4191     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
4192     event[1] = sizeof(event) - 2;
4193     event[2] = enabled;
4194     hci_emit_event(event, sizeof(event), 1);
4195 }
4196 
4197 #ifdef ENABLE_CLASSIC
4198 // query if remote side supports eSCO
4199 int hci_remote_esco_supported(hci_con_handle_t con_handle){
4200     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4201     if (!connection) return 0;
4202     return connection->remote_supported_feature_eSCO;
4203 }
4204 
4205 // query if remote side supports SSP
4206 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
4207     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4208     if (!connection) return 0;
4209     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
4210 }
4211 
4212 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
4213     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
4214 }
4215 #endif
4216 
4217 // GAP API
4218 /**
4219  * @bbrief enable/disable bonding. default is enabled
4220  * @praram enabled
4221  */
4222 void gap_set_bondable_mode(int enable){
4223     hci_stack->bondable = enable ? 1 : 0;
4224 }
4225 /**
4226  * @brief Get bondable mode.
4227  * @return 1 if bondable
4228  */
4229 int gap_get_bondable_mode(void){
4230     return hci_stack->bondable;
4231 }
4232 
4233 /**
4234  * @brief map link keys to security levels
4235  */
4236 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
4237     switch (link_key_type){
4238         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
4239             return LEVEL_4;
4240         case COMBINATION_KEY:
4241         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
4242             return LEVEL_3;
4243         default:
4244             return LEVEL_2;
4245     }
4246 }
4247 
4248 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
4249     log_info("gap_mitm_protection_required_for_security_level %u", level);
4250     return level > LEVEL_2;
4251 }
4252 
4253 /**
4254  * @brief get current security level
4255  */
4256 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
4257     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4258     if (!connection) return LEVEL_0;
4259     return gap_security_level_for_connection(connection);
4260 }
4261 
4262 /**
4263  * @brief request connection to device to
4264  * @result GAP_AUTHENTICATION_RESULT
4265  */
4266 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
4267     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4268     if (!connection){
4269         hci_emit_security_level(con_handle, LEVEL_0);
4270         return;
4271     }
4272     gap_security_level_t current_level = gap_security_level(con_handle);
4273     log_info("gap_request_security_level requested level %u, planned level %u, current level %u",
4274         requested_level, connection->requested_security_level, current_level);
4275 
4276     // assumption: earlier requested security higher than current level => security request is active
4277     if (current_level < connection->requested_security_level){
4278         if (connection->requested_security_level < requested_level){
4279             // increase requested level as new level is higher
4280 
4281             // TODO: handle re-authentication when done
4282 
4283             connection->requested_security_level = requested_level;
4284         }
4285         return;
4286     }
4287 
4288     // no request active, notify if security sufficient
4289     if (requested_level <= current_level){
4290         hci_emit_security_level(con_handle, current_level);
4291         return;
4292     }
4293 
4294     // start pairing to increase security level
4295     connection->requested_security_level = requested_level;
4296 
4297 #if 0
4298     // sending encryption request without a link key results in an error.
4299     // TODO: figure out how to use it properly
4300 
4301     // would enabling ecnryption suffice (>= LEVEL_2)?
4302     if (hci_stack->link_key_db){
4303         link_key_type_t link_key_type;
4304         link_key_t      link_key;
4305         if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){
4306             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
4307                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
4308                 return;
4309             }
4310         }
4311     }
4312 #endif
4313 
4314     // start to authenticate connection
4315     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
4316     hci_run();
4317 }
4318 
4319 /**
4320  * @brief start dedicated bonding with device. disconnect after bonding
4321  * @param device
4322  * @param request MITM protection
4323  * @result GAP_DEDICATED_BONDING_COMPLETE
4324  */
4325 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
4326 
4327     // create connection state machine
4328     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
4329 
4330     if (!connection){
4331         return BTSTACK_MEMORY_ALLOC_FAILED;
4332     }
4333 
4334     // delete linkn key
4335     gap_drop_link_key_for_bd_addr(device);
4336 
4337     // configure LEVEL_2/3, dedicated bonding
4338     connection->state = SEND_CREATE_CONNECTION;
4339     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
4340     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
4341     connection->bonding_flags = BONDING_DEDICATED;
4342 
4343     // wait for GAP Security Result and send GAP Dedicated Bonding complete
4344 
4345     // handle: connnection failure (connection complete != ok)
4346     // handle: authentication failure
4347     // handle: disconnect on done
4348 
4349     hci_run();
4350 
4351     return 0;
4352 }
4353 #endif
4354 
4355 void gap_set_local_name(const char * local_name){
4356     hci_stack->local_name = local_name;
4357 }
4358 
4359 
4360 #ifdef ENABLE_BLE
4361 
4362 #ifdef ENABLE_LE_CENTRAL
4363 void gap_start_scan(void){
4364     hci_stack->le_scanning_enabled = 1;
4365     hci_run();
4366 }
4367 
4368 void gap_stop_scan(void){
4369     hci_stack->le_scanning_enabled = 0;
4370     hci_run();
4371 }
4372 
4373 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
4374     hci_stack->le_scan_type     = scan_type;
4375     hci_stack->le_scan_interval = scan_interval;
4376     hci_stack->le_scan_window   = scan_window;
4377     hci_run();
4378 }
4379 
4380 uint8_t gap_connect(bd_addr_t addr, bd_addr_type_t addr_type){
4381     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
4382     if (!conn){
4383         log_info("gap_connect: no connection exists yet, creating context");
4384         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
4385         if (!conn){
4386             // notify client that alloc failed
4387             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
4388             log_info("gap_connect: failed to alloc hci_connection_t");
4389             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
4390         }
4391         conn->state = SEND_CREATE_CONNECTION;
4392         log_info("gap_connect: send create connection next");
4393         hci_run();
4394         return 0;
4395     }
4396 
4397     if (!hci_is_le_connection(conn) ||
4398         conn->state == SEND_CREATE_CONNECTION ||
4399         conn->state == SENT_CREATE_CONNECTION) {
4400         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
4401         log_error("gap_connect: classic connection or connect is already being created");
4402         return GATT_CLIENT_IN_WRONG_STATE;
4403     }
4404 
4405     log_info("gap_connect: context exists with state %u", conn->state);
4406     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0);
4407     hci_run();
4408     return 0;
4409 }
4410 
4411 // @assumption: only a single outgoing LE Connection exists
4412 static hci_connection_t * gap_get_outgoing_connection(void){
4413     btstack_linked_item_t *it;
4414     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
4415         hci_connection_t * conn = (hci_connection_t *) it;
4416         if (!hci_is_le_connection(conn)) continue;
4417         switch (conn->state){
4418             case SEND_CREATE_CONNECTION:
4419             case SENT_CREATE_CONNECTION:
4420             case SENT_CANCEL_CONNECTION:
4421                 return conn;
4422             default:
4423                 break;
4424         };
4425     }
4426     return NULL;
4427 }
4428 
4429 uint8_t gap_connect_cancel(void){
4430     hci_connection_t * conn = gap_get_outgoing_connection();
4431     if (!conn) return 0;
4432     switch (conn->state){
4433         case SEND_CREATE_CONNECTION:
4434             // skip sending create connection and emit event instead
4435             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
4436             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
4437             btstack_memory_hci_connection_free( conn );
4438             break;
4439         case SENT_CREATE_CONNECTION:
4440             // request to send cancel connection
4441             conn->state = SEND_CANCEL_CONNECTION;
4442             hci_run();
4443             break;
4444         default:
4445             break;
4446     }
4447     return 0;
4448 }
4449 #endif
4450 
4451 #ifdef ENABLE_LE_CENTRAL
4452 /**
4453  * @brief Set connection parameters for outgoing connections
4454  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
4455  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
4456  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
4457  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
4458  * @param conn_latency, default: 4
4459  * @param supervision_timeout (unit: 10ms), default: 720 ms
4460  * @param min_ce_length (unit: 0.625ms), default: 10 ms
4461  * @param max_ce_length (unit: 0.625ms), default: 30 ms
4462  */
4463 
4464 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
4465     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
4466     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
4467     hci_stack->le_connection_scan_interval = conn_scan_interval;
4468     hci_stack->le_connection_scan_window = conn_scan_window;
4469     hci_stack->le_connection_interval_min = conn_interval_min;
4470     hci_stack->le_connection_interval_max = conn_interval_max;
4471     hci_stack->le_connection_latency = conn_latency;
4472     hci_stack->le_supervision_timeout = supervision_timeout;
4473     hci_stack->le_minimum_ce_length = min_ce_length;
4474     hci_stack->le_maximum_ce_length = max_ce_length;
4475 }
4476 #endif
4477 
4478 /**
4479  * @brief Updates the connection parameters for a given LE connection
4480  * @param handle
4481  * @param conn_interval_min (unit: 1.25ms)
4482  * @param conn_interval_max (unit: 1.25ms)
4483  * @param conn_latency
4484  * @param supervision_timeout (unit: 10ms)
4485  * @returns 0 if ok
4486  */
4487 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4488     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4489     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4490     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4491     connection->le_conn_interval_min = conn_interval_min;
4492     connection->le_conn_interval_max = conn_interval_max;
4493     connection->le_conn_latency = conn_latency;
4494     connection->le_supervision_timeout = supervision_timeout;
4495     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
4496     hci_run();
4497     return 0;
4498 }
4499 
4500 /**
4501  * @brief Request an update of the connection parameter for a given LE connection
4502  * @param handle
4503  * @param conn_interval_min (unit: 1.25ms)
4504  * @param conn_interval_max (unit: 1.25ms)
4505  * @param conn_latency
4506  * @param supervision_timeout (unit: 10ms)
4507  * @returns 0 if ok
4508  */
4509 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4510     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4511     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4512     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4513     connection->le_conn_interval_min = conn_interval_min;
4514     connection->le_conn_interval_max = conn_interval_max;
4515     connection->le_conn_latency = conn_latency;
4516     connection->le_supervision_timeout = supervision_timeout;
4517     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
4518     hci_run();
4519     return 0;
4520 }
4521 
4522 #ifdef ENABLE_LE_PERIPHERAL
4523 
4524 static void gap_advertisments_changed(void){
4525     // disable advertisements before updating adv, scan data, or adv params
4526     if (hci_stack->le_advertisements_active){
4527         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
4528     }
4529     hci_run();
4530 }
4531 
4532 /**
4533  * @brief Set Advertisement Data
4534  * @param advertising_data_length
4535  * @param advertising_data (max 31 octets)
4536  * @note data is not copied, pointer has to stay valid
4537  */
4538 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
4539     hci_stack->le_advertisements_data_len = advertising_data_length;
4540     hci_stack->le_advertisements_data = advertising_data;
4541     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4542     gap_advertisments_changed();
4543 }
4544 
4545 /**
4546  * @brief Set Scan Response Data
4547  * @param advertising_data_length
4548  * @param advertising_data (max 31 octets)
4549  * @note data is not copied, pointer has to stay valid
4550  */
4551 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
4552     hci_stack->le_scan_response_data_len = scan_response_data_length;
4553     hci_stack->le_scan_response_data = scan_response_data;
4554     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
4555     gap_advertisments_changed();
4556 }
4557 
4558 /**
4559  * @brief Set Advertisement Parameters
4560  * @param adv_int_min
4561  * @param adv_int_max
4562  * @param adv_type
4563  * @param direct_address_type
4564  * @param direct_address
4565  * @param channel_map
4566  * @param filter_policy
4567  *
4568  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
4569  */
4570  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
4571     uint8_t direct_address_typ, bd_addr_t direct_address,
4572     uint8_t channel_map, uint8_t filter_policy) {
4573 
4574     hci_stack->le_advertisements_interval_min = adv_int_min;
4575     hci_stack->le_advertisements_interval_max = adv_int_max;
4576     hci_stack->le_advertisements_type = adv_type;
4577     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
4578     hci_stack->le_advertisements_channel_map = channel_map;
4579     hci_stack->le_advertisements_filter_policy = filter_policy;
4580     memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6);
4581 
4582     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4583     gap_advertisments_changed();
4584  }
4585 
4586 /**
4587  * @brief Enable/Disable Advertisements
4588  * @param enabled
4589  */
4590 void gap_advertisements_enable(int enabled){
4591     hci_stack->le_advertisements_enabled = enabled;
4592     if (enabled && !hci_stack->le_advertisements_active){
4593         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
4594     }
4595     if (!enabled && hci_stack->le_advertisements_active){
4596         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE;
4597     }
4598     hci_run();
4599 }
4600 
4601 #endif
4602 
4603 void hci_le_set_own_address_type(uint8_t own_address_type){
4604     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
4605     if (own_address_type == hci_stack->le_own_addr_type) return;
4606     hci_stack->le_own_addr_type = own_address_type;
4607 
4608 #ifdef ENABLE_LE_PERIPHERAL
4609     // update advertisement parameters, too
4610     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4611     gap_advertisments_changed();
4612 #endif
4613 #ifdef ENABLE_LE_CENTRAL
4614     // note: we don't update scan parameters or modify ongoing connection attempts
4615 #endif
4616 }
4617 
4618 #endif
4619 
4620 uint8_t gap_disconnect(hci_con_handle_t handle){
4621     hci_connection_t * conn = hci_connection_for_handle(handle);
4622     if (!conn){
4623         hci_emit_disconnection_complete(handle, 0);
4624         return 0;
4625     }
4626     // ignore if already disconnected
4627     if (conn->state == RECEIVED_DISCONNECTION_COMPLETE){
4628         return 0;
4629     }
4630     conn->state = SEND_DISCONNECT;
4631     hci_run();
4632     return 0;
4633 }
4634 
4635 /**
4636  * @brief Get connection type
4637  * @param con_handle
4638  * @result connection_type
4639  */
4640 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
4641     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4642     if (!conn) return GAP_CONNECTION_INVALID;
4643     switch (conn->address_type){
4644         case BD_ADDR_TYPE_LE_PUBLIC:
4645         case BD_ADDR_TYPE_LE_RANDOM:
4646             return GAP_CONNECTION_LE;
4647         case BD_ADDR_TYPE_SCO:
4648             return GAP_CONNECTION_SCO;
4649         case BD_ADDR_TYPE_CLASSIC:
4650             return GAP_CONNECTION_ACL;
4651         default:
4652             return GAP_CONNECTION_INVALID;
4653     }
4654 }
4655 
4656 #ifdef ENABLE_BLE
4657 
4658 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){
4659     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4660     if (!conn) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4661 
4662     conn->le_phy_update_all_phys    = all_phys;
4663     conn->le_phy_update_tx_phys     = tx_phys;
4664     conn->le_phy_update_rx_phys     = rx_phys;
4665     conn->le_phy_update_phy_options = phy_options;
4666 
4667     hci_run();
4668 
4669     return 0;
4670 }
4671 
4672 #ifdef ENABLE_LE_CENTRAL
4673 /**
4674  * @brief Auto Connection Establishment - Start Connecting to device
4675  * @param address_typ
4676  * @param address
4677  * @returns 0 if ok
4678  */
4679 int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){
4680     // check capacity
4681     int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist);
4682     if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
4683     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
4684     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
4685     entry->address_type = address_type;
4686     memcpy(entry->address, address, 6);
4687     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
4688     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
4689     hci_run();
4690     return 0;
4691 }
4692 
4693 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){
4694     btstack_linked_list_iterator_t it;
4695     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4696     while (btstack_linked_list_iterator_has_next(&it)){
4697         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4698         if (entry->address_type != address_type) continue;
4699         if (memcmp(entry->address, address, 6) != 0) continue;
4700         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4701             // remove from controller if already present
4702             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4703             continue;
4704         }
4705         // direclty remove entry from whitelist
4706         btstack_linked_list_iterator_remove(&it);
4707         btstack_memory_whitelist_entry_free(entry);
4708     }
4709 }
4710 
4711 /**
4712  * @brief Auto Connection Establishment - Stop Connecting to device
4713  * @param address_typ
4714  * @param address
4715  * @returns 0 if ok
4716  */
4717 int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){
4718     hci_remove_from_whitelist(address_type, address);
4719     hci_run();
4720     return 0;
4721 }
4722 
4723 /**
4724  * @brief Auto Connection Establishment - Stop everything
4725  * @note  Convenience function to stop all active auto connection attempts
4726  */
4727 void gap_auto_connection_stop_all(void){
4728     btstack_linked_list_iterator_t it;
4729     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4730     while (btstack_linked_list_iterator_has_next(&it)){
4731         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4732         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4733             // remove from controller if already present
4734             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4735             continue;
4736         }
4737         // directly remove entry from whitelist
4738         btstack_linked_list_iterator_remove(&it);
4739         btstack_memory_whitelist_entry_free(entry);
4740     }
4741     hci_run();
4742 }
4743 
4744 uint16_t gap_le_connection_interval(hci_con_handle_t connection_handle){
4745     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4746     if (!conn) return 0;
4747     return conn->le_connection_interval;
4748 }
4749 #endif
4750 #endif
4751 
4752 #ifdef ENABLE_CLASSIC
4753 /**
4754  * @brief Set Extended Inquiry Response data
4755  * @param eir_data size 240 bytes, is not copied make sure memory is accessible during stack startup
4756  * @note has to be done before stack starts up
4757  */
4758 void gap_set_extended_inquiry_response(const uint8_t * data){
4759     hci_stack->eir_data = data;
4760 }
4761 
4762 /**
4763  * @brief Start GAP Classic Inquiry
4764  * @param duration in 1.28s units
4765  * @return 0 if ok
4766  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
4767  */
4768 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
4769     if (hci_stack->state != HCI_STATE_WORKING) return ERROR_CODE_COMMAND_DISALLOWED;
4770     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4771     if (duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN || duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX){
4772         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
4773     }
4774     hci_stack->inquiry_state = duration_in_1280ms_units;
4775     hci_run();
4776     return 0;
4777 }
4778 
4779 /**
4780  * @brief Stop GAP Classic Inquiry
4781  * @returns 0 if ok
4782  */
4783 int gap_inquiry_stop(void){
4784     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN && hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX) {
4785         // emit inquiry complete event, before it even started
4786         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
4787         hci_emit_event(event, sizeof(event), 1);
4788         return 0;
4789     }
4790     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
4791     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
4792     hci_run();
4793     return 0;
4794 }
4795 
4796 
4797 /**
4798  * @brief Remote Name Request
4799  * @param addr
4800  * @param page_scan_repetition_mode
4801  * @param clock_offset only used when bit 15 is set
4802  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
4803  */
4804 int gap_remote_name_request(bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
4805     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4806     memcpy(hci_stack->remote_name_addr, addr, 6);
4807     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
4808     hci_stack->remote_name_clock_offset = clock_offset;
4809     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
4810     hci_run();
4811     return 0;
4812 }
4813 
4814 static int gap_pairing_set_state_and_run(bd_addr_t addr, uint8_t state){
4815     hci_stack->gap_pairing_state = state;
4816     memcpy(hci_stack->gap_pairing_addr, addr, 6);
4817     hci_run();
4818     return 0;
4819 }
4820 
4821 /**
4822  * @brief Legacy Pairing Pin Code Response
4823  * @param addr
4824  * @param pin
4825  * @return 0 if ok
4826  */
4827 int gap_pin_code_response(bd_addr_t addr, const char * pin){
4828     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4829     hci_stack->gap_pairing_input.gap_pairing_pin = pin;
4830     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
4831 }
4832 
4833 /**
4834  * @brief Abort Legacy Pairing
4835  * @param addr
4836  * @param pin
4837  * @return 0 if ok
4838  */
4839 int gap_pin_code_negative(bd_addr_t addr){
4840     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4841     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
4842 }
4843 
4844 /**
4845  * @brief SSP Passkey Response
4846  * @param addr
4847  * @param passkey
4848  * @return 0 if ok
4849  */
4850 int gap_ssp_passkey_response(bd_addr_t addr, uint32_t passkey){
4851     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4852     hci_stack->gap_pairing_input.gap_pairing_passkey = passkey;
4853     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
4854 }
4855 
4856 /**
4857  * @brief Abort SSP Passkey Entry/Pairing
4858  * @param addr
4859  * @param pin
4860  * @return 0 if ok
4861  */
4862 int gap_ssp_passkey_negative(bd_addr_t addr){
4863     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4864     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
4865 }
4866 
4867 /**
4868  * @brief Accept SSP Numeric Comparison
4869  * @param addr
4870  * @param passkey
4871  * @return 0 if ok
4872  */
4873 int gap_ssp_confirmation_response(bd_addr_t addr){
4874     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4875     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
4876 }
4877 
4878 /**
4879  * @brief Abort SSP Numeric Comparison/Pairing
4880  * @param addr
4881  * @param pin
4882  * @return 0 if ok
4883  */
4884 int gap_ssp_confirmation_negative(bd_addr_t addr){
4885     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4886     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
4887 }
4888 
4889 /**
4890  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
4891  * @param inquiry_mode see bluetooth_defines.h
4892  */
4893 void hci_set_inquiry_mode(inquiry_mode_t mode){
4894     hci_stack->inquiry_mode = mode;
4895 }
4896 
4897 /**
4898  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
4899  */
4900 void hci_set_sco_voice_setting(uint16_t voice_setting){
4901     hci_stack->sco_voice_setting = voice_setting;
4902 }
4903 
4904 /**
4905  * @brief Get SCO Voice Setting
4906  * @return current voice setting
4907  */
4908 uint16_t hci_get_sco_voice_setting(void){
4909     return hci_stack->sco_voice_setting;
4910 }
4911 
4912 #ifdef ENABLE_CLASSIC
4913 #ifdef ENABLE_SCO_OVER_HCI
4914 static int hci_have_usb_transport(void){
4915     if (!hci_stack->hci_transport) return 0;
4916     const char * transport_name = hci_stack->hci_transport->name;
4917     if (!transport_name) return 0;
4918     return (transport_name[0] == 'H') && (transport_name[1] == '2');
4919 }
4920 #endif
4921 #endif
4922 
4923 /** @brief Get SCO packet length for current SCO Voice setting
4924  *  @note  Using SCO packets of the exact length is required for USB transfer
4925  *  @return Length of SCO packets in bytes (not audio frames)
4926  */
4927 int hci_get_sco_packet_length(void){
4928     int sco_packet_length = 0;
4929 
4930 #ifdef ENABLE_CLASSIC
4931 #ifdef ENABLE_SCO_OVER_HCI
4932 
4933     // CVSD requires twice as much bytes
4934     int multiplier = hci_stack->sco_voice_setting_active & 0x0020 ? 2 : 1;
4935 
4936     if (hci_have_usb_transport()){
4937         // see Core Spec for H2 USB Transfer.
4938         // 3 byte SCO header + 24 bytes per connection
4939         int num_sco_connections = btstack_max(1, hci_number_sco_connections());
4940         sco_packet_length = 3 + 24 * num_sco_connections * multiplier;
4941     } else {
4942         // 3 byte SCO header + SCO packet size over the air (60 bytes)
4943         sco_packet_length = 3 + 60 * multiplier;
4944         // assert that it still fits inside an SCO buffer
4945         if (sco_packet_length > hci_stack->sco_data_packet_length){
4946             sco_packet_length = 3 + 60;
4947         }
4948     }
4949 #endif
4950 #endif
4951     return sco_packet_length;
4952 }
4953 
4954 /**
4955 * @brief Sets the master/slave policy
4956 * @param policy (0: attempt to become master, 1: let connecting device decide)
4957 */
4958 void hci_set_master_slave_policy(uint8_t policy){
4959     hci_stack->master_slave_policy = policy;
4960 }
4961 
4962 #endif
4963 
4964 HCI_STATE hci_get_state(void){
4965     return hci_stack->state;
4966 }
4967 
4968 
4969 /**
4970  * @brief Set callback for Bluetooth Hardware Error
4971  */
4972 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
4973     hci_stack->hardware_error_callback = fn;
4974 }
4975 
4976 void hci_disconnect_all(void){
4977     btstack_linked_list_iterator_t it;
4978     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
4979     while (btstack_linked_list_iterator_has_next(&it)){
4980         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
4981         if (con->state == SENT_DISCONNECT) continue;
4982         con->state = SEND_DISCONNECT;
4983     }
4984     hci_run();
4985 }
4986 
4987 uint16_t hci_get_manufacturer(void){
4988     return hci_stack->manufacturer;
4989 }
4990 
4991 #ifdef ENABLE_BLE
4992 
4993 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4994     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
4995     if (!hci_con) return NULL;
4996     return &hci_con->sm_connection;
4997 }
4998 
4999 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
5000 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
5001 
5002 int gap_encryption_key_size(hci_con_handle_t con_handle){
5003     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5004     if (!sm_conn) return 0;     // wrong connection
5005     if (!sm_conn->sm_connection_encrypted) return 0;
5006     return sm_conn->sm_actual_encryption_key_size;
5007 }
5008 
5009 int gap_authenticated(hci_con_handle_t con_handle){
5010     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5011     if (!sm_conn) return 0;     // wrong connection
5012     if (!sm_conn->sm_connection_encrypted) return 0; // unencrypted connection cannot be authenticated
5013     return sm_conn->sm_connection_authenticated;
5014 }
5015 
5016 int gap_secure_connection(hci_con_handle_t con_handle){
5017     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5018     if (!sm_conn) return 0;     // wrong connection
5019     if (!sm_conn->sm_connection_encrypted) return 0; // unencrypted connection cannot be authenticated
5020     return sm_conn->sm_connection_sc;
5021 }
5022 
5023 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
5024     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
5025     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
5026     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
5027     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
5028     return sm_conn->sm_connection_authorization_state;
5029 }
5030 #endif
5031 
5032 #ifdef ENABLE_CLASSIC
5033 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){
5034     hci_connection_t * conn = hci_connection_for_handle(con_handle);
5035     if (!conn) return GAP_CONNECTION_INVALID;
5036     conn->sniff_min_interval = sniff_min_interval;
5037     conn->sniff_max_interval = sniff_max_interval;
5038     conn->sniff_attempt = sniff_attempt;
5039     conn->sniff_timeout = sniff_timeout;
5040     hci_run();
5041     return 0;
5042 }
5043 
5044 /**
5045  * @brief Exit Sniff mode
5046  * @param con_handle
5047  @ @return 0 if ok
5048  */
5049 uint8_t gap_sniff_mode_exit(hci_con_handle_t con_handle){
5050     hci_connection_t * conn = hci_connection_for_handle(con_handle);
5051     if (!conn) return GAP_CONNECTION_INVALID;
5052     conn->sniff_min_interval = 0xffff;
5053     hci_run();
5054     return 0;
5055 }
5056 #endif
5057 
5058 void hci_halting_defer(void){
5059     if (hci_stack->state != HCI_STATE_HALTING) return;
5060     switch (hci_stack->substate){
5061         case HCI_HALTING_DISCONNECT_ALL_NO_TIMER:
5062         case HCI_HALTING_CLOSE:
5063             hci_stack->substate = HCI_HALTING_DISCONNECT_ALL_TIMER;
5064             break;
5065         default:
5066             break;
5067     }
5068 }
5069