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