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