xref: /btstack/src/hci.c (revision 004902f13ed4e8849c50e355f2640b9d4ad3a9ec)
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         // Fix: no HCI Command Complete received, so num_cmd_packets not reset
1432         hci_stack->num_cmd_packets = 1;
1433     }
1434 
1435     // Late response (> 100 ms) for HCI Reset e.g. on Toshiba TC35661:
1436     // Command complete for HCI Reset arrives after we've resent the HCI Reset command
1437     //
1438     // HCI Reset
1439     // Timeout 100 ms
1440     // HCI Reset
1441     // Command Complete Reset
1442     // HCI Read Local Version Information
1443     // Command Complete Reset - but we expected Command Complete Read Local Version Information
1444     // hang...
1445     //
1446     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1447     if (!command_completed
1448             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
1449             && hci_stack->substate == HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION){
1450 
1451         uint16_t opcode = little_endian_read_16(packet,3);
1452         if (opcode == hci_reset.opcode){
1453             hci_stack->substate = HCI_INIT_SEND_READ_LOCAL_VERSION_INFORMATION;
1454             return;
1455         }
1456     }
1457 
1458     // CSR & H5
1459     // Fix: Command Complete for HCI Reset in HCI_INIT_W4_SEND_READ_LOCAL_VERSION_INFORMATION trigger resend
1460     if (!command_completed
1461             && hci_event_packet_get_type(packet) == HCI_EVENT_COMMAND_COMPLETE
1462             && hci_stack->substate == HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS){
1463 
1464         uint16_t opcode = little_endian_read_16(packet,3);
1465         if (opcode == hci_reset.opcode){
1466             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1467             return;
1468         }
1469     }
1470 
1471     // on CSR with BCSP/H5, the reset resend timeout leads to substate == HCI_INIT_SEND_RESET or HCI_INIT_SEND_RESET_CSR_WARM_BOOT
1472     // fix: Correct substate and behave as command below
1473     if (command_completed){
1474         switch (hci_stack->substate){
1475             case HCI_INIT_SEND_RESET:
1476                 hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1477                 break;
1478             case HCI_INIT_SEND_RESET_CSR_WARM_BOOT:
1479                 hci_stack->substate = HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT;
1480                 break;
1481             default:
1482                 break;
1483         }
1484     }
1485 
1486 #endif
1487 
1488     if (!command_completed) return;
1489 
1490     int need_baud_change = 0;
1491     int need_addr_change = 0;
1492 
1493 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1494     need_baud_change = hci_stack->config
1495                         && hci_stack->chipset
1496                         && hci_stack->chipset->set_baudrate_command
1497                         && hci_stack->hci_transport->set_baudrate
1498                         && ((hci_transport_config_uart_t *)hci_stack->config)->baudrate_main;
1499 
1500     need_addr_change = hci_stack->custom_bd_addr_set
1501                         && hci_stack->chipset
1502                         && hci_stack->chipset->set_bd_addr_command;
1503 #endif
1504 
1505     switch(hci_stack->substate){
1506 
1507 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1508         case HCI_INIT_SEND_RESET:
1509             // on CSR with BCSP/H5, resend triggers resend of HCI Reset and leads to substate == HCI_INIT_SEND_RESET
1510             // fix: just correct substate and behave as command below
1511             hci_stack->substate = HCI_INIT_W4_SEND_RESET;
1512             btstack_run_loop_remove_timer(&hci_stack->timeout);
1513             break;
1514         case HCI_INIT_W4_SEND_RESET:
1515             btstack_run_loop_remove_timer(&hci_stack->timeout);
1516             break;
1517         case HCI_INIT_W4_SEND_READ_LOCAL_NAME:
1518             log_info("Received local name, need baud change %d", need_baud_change);
1519             if (need_baud_change){
1520                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE;
1521                 return;
1522             }
1523             // skip baud change
1524             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1525             return;
1526         case HCI_INIT_W4_SEND_BAUD_CHANGE:
1527             // for STLC2500D, baud rate change already happened.
1528             // for others, baud rate gets changed now
1529             if ((hci_stack->manufacturer != BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS) && need_baud_change){
1530                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1531                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change)", baud_rate);
1532                 hci_stack->hci_transport->set_baudrate(baud_rate);
1533             }
1534             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1535             return;
1536         case HCI_INIT_W4_CUSTOM_INIT_CSR_WARM_BOOT:
1537             btstack_run_loop_remove_timer(&hci_stack->timeout);
1538             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1539             return;
1540         case HCI_INIT_W4_CUSTOM_INIT:
1541             // repeat custom init
1542             hci_stack->substate = HCI_INIT_CUSTOM_INIT;
1543             return;
1544 #else
1545         case HCI_INIT_W4_SEND_RESET:
1546             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_COMMANDS;
1547             return ;
1548 #endif
1549 
1550         case HCI_INIT_W4_READ_LOCAL_SUPPORTED_COMMANDS:
1551             if (need_baud_change &&
1552               ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) ||
1553                (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_EM_MICROELECTRONIC_MARIN_SA))) {
1554                 hci_stack->substate = HCI_INIT_SEND_BAUD_CHANGE_BCM;
1555                 return;
1556             }
1557             if (need_addr_change){
1558                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1559                 return;
1560             }
1561             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1562             return;
1563 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
1564         case HCI_INIT_W4_SEND_BAUD_CHANGE_BCM:
1565             if (need_baud_change){
1566                 uint32_t baud_rate = hci_transport_uart_get_main_baud_rate();
1567                 log_info("Local baud rate change to %"PRIu32"(w4_send_baud_change_bcm))", baud_rate);
1568                 hci_stack->hci_transport->set_baudrate(baud_rate);
1569             }
1570             if (need_addr_change){
1571                 hci_stack->substate = HCI_INIT_SET_BD_ADDR;
1572                 return;
1573             }
1574             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1575             return;
1576         case HCI_INIT_W4_SET_BD_ADDR:
1577             // for STLC2500D + ATWILC3000, bd addr change only gets active after sending reset command
1578             if ((hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ST_MICROELECTRONICS)
1579             ||  (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_ATMEL_CORPORATION)){
1580                 hci_stack->substate = HCI_INIT_SEND_RESET_ST_WARM_BOOT;
1581                 return;
1582             }
1583             // skipping st warm boot
1584             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1585             return;
1586         case HCI_INIT_W4_SEND_RESET_ST_WARM_BOOT:
1587             hci_stack->substate = HCI_INIT_READ_BD_ADDR;
1588             return;
1589 #endif
1590         case HCI_INIT_W4_READ_BD_ADDR:
1591             // only read buffer size if supported
1592             if (hci_stack->local_supported_commands[0] & 0x01) {
1593                 hci_stack->substate = HCI_INIT_READ_BUFFER_SIZE;
1594                 return;
1595             }
1596             // skipping read buffer size
1597             hci_stack->substate = HCI_INIT_READ_LOCAL_SUPPORTED_FEATURES;
1598             return;
1599         case HCI_INIT_W4_SET_EVENT_MASK:
1600             // skip Classic init commands for LE only chipsets
1601             if (!hci_classic_supported()){
1602 #ifdef ENABLE_BLE
1603                 if (hci_le_supported()){
1604                     hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE; // skip all classic command
1605                     return;
1606                 }
1607 #endif
1608                 log_error("Neither BR/EDR nor LE supported");
1609                 hci_init_done();
1610                 return;
1611             }
1612             if (!gap_ssp_supported()){
1613                 hci_stack->substate = HCI_INIT_WRITE_PAGE_TIMEOUT;
1614                 return;
1615             }
1616             break;
1617 #ifdef ENABLE_BLE
1618         case HCI_INIT_W4_LE_READ_BUFFER_SIZE:
1619             // skip write le host if not supported (e.g. on LE only EM9301)
1620             if (hci_stack->local_supported_commands[0] & 0x02) break;
1621             hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1622             return;
1623 
1624 
1625 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1626         case HCI_INIT_W4_WRITE_LE_HOST_SUPPORTED:
1627             if ((hci_stack->local_supported_commands[0] & 0x30) == 0x30){
1628                 hci_stack->substate = HCI_INIT_LE_SET_EVENT_MASK;
1629                 return;
1630             }
1631             // explicit fall through to reduce repetitions
1632 #endif
1633 
1634 #ifdef ENABLE_LE_CENTRAL
1635             hci_stack->substate = HCI_INIT_READ_WHITE_LIST_SIZE;
1636 #else
1637             hci_init_done();
1638 #endif
1639             return;
1640 #endif
1641 
1642 #ifdef ENABLE_SCO_OVER_HCI
1643         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1644             // skip write synchronous flow control if not supported
1645             if (hci_stack->local_supported_commands[0] & 0x04) break;
1646             hci_stack->substate = HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE;
1647             // explicit fall through to reduce repetitions
1648 
1649         case HCI_INIT_W4_WRITE_SYNCHRONOUS_FLOW_CONTROL_ENABLE:
1650             // skip write default erroneous data reporting if not supported
1651             if (hci_stack->local_supported_commands[0] & 0x08) break;
1652             hci_stack->substate = HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING;
1653             // explicit fall through to reduce repetitions
1654 
1655         case HCI_INIT_W4_WRITE_DEFAULT_ERRONEOUS_DATA_REPORTING:
1656             // skip bcm set sco pcm config on non-Broadcom chipsets
1657             if (hci_stack->manufacturer == BLUETOOTH_COMPANY_ID_BROADCOM_CORPORATION) break;
1658             hci_stack->substate = HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT;
1659             // explicit fall through to reduce repetitions
1660 
1661         case HCI_INIT_W4_BCM_WRITE_SCO_PCM_INT:
1662             if (!hci_le_supported()){
1663                 // SKIP LE init for Classic only configuration
1664                 hci_init_done();
1665                 return;
1666             }
1667             break;
1668 
1669 #else /* !ENABLE_SCO_OVER_HCI */
1670 
1671         case HCI_INIT_W4_WRITE_SCAN_ENABLE:
1672 #ifdef ENABLE_BLE
1673             if (hci_le_supported()){
1674                 hci_stack->substate = HCI_INIT_LE_READ_BUFFER_SIZE;
1675                 return;
1676             }
1677 #endif
1678             // SKIP LE init for Classic only configuration
1679             hci_init_done();
1680             return;
1681 #endif /* ENABLE_SCO_OVER_HCI */
1682 
1683         // Response to command before init done state -> init done
1684         case (HCI_INIT_DONE-1):
1685             hci_init_done();
1686             return;
1687 
1688         default:
1689             break;
1690     }
1691     hci_initializing_next_state();
1692 }
1693 
1694 static void event_handler(uint8_t *packet, int size){
1695 
1696     uint16_t event_length = packet[1];
1697 
1698     // assert packet is complete
1699     if (size != event_length + 2){
1700         log_error("hci.c: event_handler called with event packet of wrong size %d, expected %u => dropping packet", size, event_length + 2);
1701         return;
1702     }
1703 
1704     bd_addr_t addr;
1705     bd_addr_type_t addr_type;
1706     hci_con_handle_t handle;
1707     hci_connection_t * conn;
1708     int i;
1709 #ifdef ENABLE_CLASSIC
1710     uint8_t link_type;
1711 #endif
1712 
1713     // log_info("HCI:EVENT:%02x", hci_event_packet_get_type(packet));
1714 
1715     switch (hci_event_packet_get_type(packet)) {
1716 
1717         case HCI_EVENT_COMMAND_COMPLETE:
1718             // get num cmd packets - limit to 1 to reduce complexity
1719             hci_stack->num_cmd_packets = packet[2] ? 1 : 0;
1720 
1721             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_name)){
1722                 if (packet[5]) break;
1723                 // terminate, name 248 chars
1724                 packet[6+248] = 0;
1725                 log_info("local name: %s", &packet[6]);
1726             }
1727             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_buffer_size)){
1728                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
1729                 if (hci_stack->state == HCI_STATE_INITIALIZING){
1730                     uint16_t acl_len = little_endian_read_16(packet, 6);
1731                     uint16_t sco_len = packet[8];
1732 
1733                     // determine usable ACL/SCO payload size
1734                     hci_stack->acl_data_packet_length = btstack_min(acl_len, HCI_ACL_PAYLOAD_SIZE);
1735                     hci_stack->sco_data_packet_length = btstack_min(sco_len, HCI_ACL_PAYLOAD_SIZE);
1736 
1737                     hci_stack->acl_packets_total_num  = little_endian_read_16(packet, 9);
1738                     hci_stack->sco_packets_total_num  = little_endian_read_16(packet, 11);
1739 
1740                     log_info("hci_read_buffer_size: ACL size module %u -> used %u, count %u / SCO size %u, count %u",
1741                              acl_len, hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num,
1742                              hci_stack->sco_data_packet_length, hci_stack->sco_packets_total_num);
1743                 }
1744             }
1745 #ifdef ENABLE_BLE
1746             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_buffer_size)){
1747                 hci_stack->le_data_packets_length = little_endian_read_16(packet, 6);
1748                 hci_stack->le_acl_packets_total_num  = packet[8];
1749                 // determine usable ACL payload size
1750                 if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
1751                     hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
1752                 }
1753                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
1754             }
1755 #endif
1756 #ifdef ENABLE_LE_DATA_LENGTH_EXTENSION
1757             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_maximum_data_length)){
1758                 hci_stack->le_supported_max_tx_octets = little_endian_read_16(packet, 6);
1759                 hci_stack->le_supported_max_tx_time = little_endian_read_16(packet, 8);
1760                 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);
1761             }
1762 #endif
1763 #ifdef ENABLE_LE_CENTRAL
1764             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_le_read_white_list_size)){
1765                 hci_stack->le_whitelist_capacity = packet[6];
1766                 log_info("hci_le_read_white_list_size: size %u", hci_stack->le_whitelist_capacity);
1767             }
1768 #endif
1769             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_bd_addr)) {
1770                 reverse_bd_addr(&packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1],
1771 				hci_stack->local_bd_addr);
1772                 log_info("Local Address, Status: 0x%02x: Addr: %s",
1773                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
1774 #ifdef ENABLE_CLASSIC
1775                 if (hci_stack->link_key_db){
1776                     hci_stack->link_key_db->set_local_bd_addr(hci_stack->local_bd_addr);
1777                 }
1778 #endif
1779             }
1780 #ifdef ENABLE_CLASSIC
1781             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
1782                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1783             }
1784             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_inquiry_cancel)){
1785                 if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W4_CANCELLED){
1786                     hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
1787                     uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
1788                     hci_emit_event(event, sizeof(event), 1);
1789                 }
1790             }
1791 #endif
1792 
1793             // Note: HCI init checks
1794             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_features)){
1795                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
1796 
1797 #ifdef ENABLE_CLASSIC
1798                 // determine usable ACL packet types based on host buffer size and supported features
1799                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
1800                 log_info("Packet types %04x, eSCO %u", hci_stack->packet_types, hci_extended_sco_link_supported());
1801 #endif
1802                 // Classic/LE
1803                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1804             }
1805             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_version_information)){
1806                 // hci_stack->hci_version    = little_endian_read_16(packet, 4);
1807                 // hci_stack->hci_revision   = little_endian_read_16(packet, 6);
1808                 // hci_stack->lmp_version    = little_endian_read_16(packet, 8);
1809                 hci_stack->manufacturer   = little_endian_read_16(packet, 10);
1810                 // hci_stack->lmp_subversion = little_endian_read_16(packet, 12);
1811                 log_info("Manufacturer: 0x%04x", hci_stack->manufacturer);
1812             }
1813             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_read_local_supported_commands)){
1814                 hci_stack->local_supported_commands[0] =
1815                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+14] & 0x80) >> 7 |  // bit 0 = Octet 14, bit 7
1816                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+24] & 0x40) >> 5 |  // bit 1 = Octet 24, bit 6
1817                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+10] & 0x10) >> 2 |  // bit 2 = Octet 10, bit 4
1818                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+18] & 0x08)      |  // bit 3 = Octet 18, bit 3
1819                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+34] & 0x01) << 4 |  // bit 4 = Octet 34, bit 0
1820                     (packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1+35] & 0x08) << 2;   // bit 5 = Octet 35, bit 3
1821                     log_info("Local supported commands summary 0x%02x", hci_stack->local_supported_commands[0]);
1822             }
1823 #ifdef ENABLE_CLASSIC
1824             if (HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_synchronous_flow_control_enable)){
1825                 if (packet[5] == 0){
1826                     hci_stack->synchronous_flow_control_enabled = 1;
1827                 }
1828             }
1829 #endif
1830             break;
1831 
1832         case HCI_EVENT_COMMAND_STATUS:
1833             // get num cmd packets - limit to 1 to reduce complexity
1834             hci_stack->num_cmd_packets = packet[3] ? 1 : 0;
1835             break;
1836 
1837         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
1838             int offset = 3;
1839             for (i=0; i<packet[2];i++){
1840                 handle = little_endian_read_16(packet, offset);
1841                 offset += 2;
1842                 uint16_t num_packets = little_endian_read_16(packet, offset);
1843                 offset += 2;
1844 
1845                 conn = hci_connection_for_handle(handle);
1846                 if (!conn){
1847                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
1848                     continue;
1849                 }
1850 
1851                 if (conn->address_type == BD_ADDR_TYPE_SCO){
1852 #ifdef ENABLE_CLASSIC
1853                     if (conn->num_sco_packets_sent >= num_packets){
1854                         conn->num_sco_packets_sent -= num_packets;
1855                     } else {
1856                         log_error("hci_number_completed_packets, more sco slots freed then sent.");
1857                         conn->num_sco_packets_sent = 0;
1858                     }
1859                     hci_notify_if_sco_can_send_now();
1860 #endif
1861                 } else {
1862                     if (conn->num_acl_packets_sent >= num_packets){
1863                         conn->num_acl_packets_sent -= num_packets;
1864                     } else {
1865                         log_error("hci_number_completed_packets, more acl slots freed then sent.");
1866                         conn->num_acl_packets_sent = 0;
1867                     }
1868                 }
1869                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
1870             }
1871             break;
1872         }
1873 
1874 #ifdef ENABLE_CLASSIC
1875         case HCI_EVENT_INQUIRY_COMPLETE:
1876             if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_ACTIVE){
1877                 hci_stack->inquiry_state = GAP_INQUIRY_STATE_IDLE;
1878                 uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
1879                 hci_emit_event(event, sizeof(event), 1);
1880             }
1881             break;
1882         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
1883             if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W4_COMPLETE){
1884                 hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_IDLE;
1885             }
1886             break;
1887         case HCI_EVENT_CONNECTION_REQUEST:
1888             reverse_bd_addr(&packet[2], addr);
1889             // TODO: eval COD 8-10
1890             link_type = packet[11];
1891             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
1892             addr_type = link_type == 1 ? BD_ADDR_TYPE_CLASSIC : BD_ADDR_TYPE_SCO;
1893             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1894             if (!conn) {
1895                 conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1896             }
1897             if (!conn) {
1898                 // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
1899                 hci_stack->decline_reason = 0x0d;
1900                 bd_addr_copy(hci_stack->decline_addr, addr);
1901                 break;
1902             }
1903             conn->role  = HCI_ROLE_SLAVE;
1904             conn->state = RECEIVED_CONNECTION_REQUEST;
1905             // store info about eSCO
1906             if (link_type == 0x02){
1907                 conn->remote_supported_feature_eSCO = 1;
1908             }
1909             hci_run();
1910             break;
1911 
1912         case HCI_EVENT_CONNECTION_COMPLETE:
1913             // Connection management
1914             reverse_bd_addr(&packet[5], addr);
1915             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1916             addr_type = BD_ADDR_TYPE_CLASSIC;
1917             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
1918             if (conn) {
1919                 if (!packet[2]){
1920                     conn->state = OPEN;
1921                     conn->con_handle = little_endian_read_16(packet, 3);
1922                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
1923 
1924                     // restart timer
1925                     btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1926                     btstack_run_loop_add_timer(&conn->timeout);
1927 
1928                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1929 
1930                     hci_emit_nr_connections_changed();
1931                 } else {
1932                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
1933                     uint8_t status = packet[2];
1934                     bd_addr_t bd_address;
1935                     memcpy(&bd_address, conn->address, 6);
1936 
1937                     // connection failed, remove entry
1938                     btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
1939                     btstack_memory_hci_connection_free( conn );
1940 
1941                     // notify client if dedicated bonding
1942                     if (notify_dedicated_bonding_failed){
1943                         log_info("hci notify_dedicated_bonding_failed");
1944                         hci_emit_dedicated_bonding_result(bd_address, status);
1945                     }
1946 
1947                     // if authentication error, also delete link key
1948                     if (packet[2] == 0x05) {
1949                         gap_drop_link_key_for_bd_addr(addr);
1950                     }
1951                 }
1952             }
1953             break;
1954 
1955         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
1956             reverse_bd_addr(&packet[5], addr);
1957             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1958             if (packet[2]){
1959                 // connection failed
1960                 break;
1961             }
1962             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1963             if (!conn) {
1964                 conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_SCO);
1965             }
1966             if (!conn) {
1967                 break;
1968             }
1969             conn->state = OPEN;
1970             conn->con_handle = little_endian_read_16(packet, 3);
1971 
1972 #ifdef ENABLE_SCO_OVER_HCI
1973             // update SCO
1974             if (conn->address_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
1975                 hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
1976             }
1977 #endif
1978             break;
1979 
1980         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1981             handle = little_endian_read_16(packet, 3);
1982             conn = hci_connection_for_handle(handle);
1983             if (!conn) break;
1984             if (!packet[2]){
1985                 uint8_t * features = &packet[5];
1986                 if (features[6] & (1 << 3)){
1987                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
1988                 }
1989                 if (features[3] & (1<<7)){
1990                     conn->remote_supported_feature_eSCO = 1;
1991                 }
1992             }
1993             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
1994             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x, eSCO %u", conn->bonding_flags, conn->remote_supported_feature_eSCO);
1995             if (conn->bonding_flags & BONDING_DEDICATED){
1996                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1997             }
1998             break;
1999 
2000         case HCI_EVENT_LINK_KEY_REQUEST:
2001             log_info("HCI_EVENT_LINK_KEY_REQUEST");
2002             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
2003             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
2004             if (hci_stack->bondable && !hci_stack->link_key_db) break;
2005             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
2006             hci_run();
2007             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
2008             return;
2009 
2010         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
2011             reverse_bd_addr(&packet[2], addr);
2012             conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2013             if (!conn) break;
2014             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
2015             link_key_type_t link_key_type = (link_key_type_t)packet[24];
2016             // Change Connection Encryption keeps link key type
2017             if (link_key_type != CHANGED_COMBINATION_KEY){
2018                 conn->link_key_type = link_key_type;
2019             }
2020             gap_store_link_key_for_bd_addr(addr, &packet[8], conn->link_key_type);
2021             // still forward event to allow dismiss of pairing dialog
2022             break;
2023         }
2024 
2025         case HCI_EVENT_PIN_CODE_REQUEST:
2026             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
2027             // non-bondable mode: pin code negative reply will be sent
2028             if (!hci_stack->bondable){
2029                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
2030                 hci_run();
2031                 return;
2032             }
2033             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
2034             if (!hci_stack->link_key_db) break;
2035             hci_event_pin_code_request_get_bd_addr(packet, addr);
2036             hci_stack->link_key_db->delete_link_key(addr);
2037             break;
2038 
2039         case HCI_EVENT_IO_CAPABILITY_REQUEST:
2040             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
2041             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
2042             break;
2043 
2044         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
2045             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2046             if (!hci_stack->ssp_auto_accept) break;
2047             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
2048             break;
2049 
2050         case HCI_EVENT_USER_PASSKEY_REQUEST:
2051             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
2052             if (!hci_stack->ssp_auto_accept) break;
2053             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
2054             break;
2055 #endif
2056 
2057         case HCI_EVENT_ENCRYPTION_CHANGE:
2058             handle = little_endian_read_16(packet, 3);
2059             conn = hci_connection_for_handle(handle);
2060             if (!conn) break;
2061             if (packet[2] == 0) {
2062                 if (packet[5]){
2063                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
2064                 } else {
2065                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
2066                 }
2067             }
2068 #ifdef ENABLE_CLASSIC
2069             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2070 #endif
2071             break;
2072 
2073 #ifdef ENABLE_CLASSIC
2074         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
2075             handle = little_endian_read_16(packet, 3);
2076             conn = hci_connection_for_handle(handle);
2077             if (!conn) break;
2078 
2079             // dedicated bonding: send result and disconnect
2080             if (conn->bonding_flags & BONDING_DEDICATED){
2081                 conn->bonding_flags &= ~BONDING_DEDICATED;
2082                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
2083                 conn->bonding_status = packet[2];
2084                 break;
2085             }
2086 
2087             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
2088                 // link key sufficient for requested security
2089                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2090                 break;
2091             }
2092             // not enough
2093             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
2094             break;
2095 #endif
2096 
2097         // HCI_EVENT_DISCONNECTION_COMPLETE
2098         // has been split, to first notify stack before shutting connection down
2099         // see end of function, too.
2100         case HCI_EVENT_DISCONNECTION_COMPLETE:
2101             if (packet[2]) break;   // status != 0
2102             handle = little_endian_read_16(packet, 3);
2103             // drop outgoing ACL fragments if it is for closed connection
2104             if (hci_stack->acl_fragmentation_total_size > 0) {
2105                 if (handle == READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer)){
2106                     log_info("hci: drop fragmented ACL data for closed connection");
2107                      hci_stack->acl_fragmentation_total_size = 0;
2108                      hci_stack->acl_fragmentation_pos = 0;
2109                 }
2110             }
2111 
2112             // re-enable advertisements for le connections if active
2113             conn = hci_connection_for_handle(handle);
2114             if (!conn) break;
2115 #ifdef ENABLE_BLE
2116 #ifdef ENABLE_LE_PERIPHERAL
2117             if (hci_is_le_connection(conn) && hci_stack->le_advertisements_enabled){
2118                 hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
2119             }
2120 #endif
2121 #endif
2122             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
2123             break;
2124 
2125         case HCI_EVENT_HARDWARE_ERROR:
2126             log_error("Hardware Error: 0x%02x", packet[2]);
2127             if (hci_stack->hardware_error_callback){
2128                 (*hci_stack->hardware_error_callback)(packet[2]);
2129             } else {
2130                 // if no special requests, just reboot stack
2131                 hci_power_control_off();
2132                 hci_power_control_on();
2133             }
2134             break;
2135 
2136 #ifdef ENABLE_CLASSIC
2137         case HCI_EVENT_ROLE_CHANGE:
2138             if (packet[2]) break;   // status != 0
2139             reverse_bd_addr(&packet[3], addr);
2140             addr_type = BD_ADDR_TYPE_CLASSIC;
2141             conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2142             if (!conn) break;
2143             conn->role = packet[9];
2144             break;
2145 #endif
2146 
2147         case HCI_EVENT_TRANSPORT_PACKET_SENT:
2148             // release packet buffer only for asynchronous transport and if there are not further fragements
2149             if (hci_transport_synchronous()) {
2150                 log_error("Synchronous HCI Transport shouldn't send HCI_EVENT_TRANSPORT_PACKET_SENT");
2151                 return; // instead of break: to avoid re-entering hci_run()
2152             }
2153             if (hci_stack->acl_fragmentation_total_size) break;
2154             hci_release_packet_buffer();
2155 
2156             // L2CAP receives this event via the hci_emit_event below
2157 
2158 #ifdef ENABLE_CLASSIC
2159             // For SCO, we do the can_send_now_check here
2160             hci_notify_if_sco_can_send_now();
2161 #endif
2162             break;
2163 
2164 #ifdef ENABLE_CLASSIC
2165         case HCI_EVENT_SCO_CAN_SEND_NOW:
2166             // For SCO, we do the can_send_now_check here
2167             hci_notify_if_sco_can_send_now();
2168             return;
2169 
2170         // explode inquriy results for easier consumption
2171         case HCI_EVENT_INQUIRY_RESULT:
2172         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
2173         case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
2174             gap_inquiry_explode(packet);
2175             break;
2176 #endif
2177 
2178 #ifdef ENABLE_BLE
2179         case HCI_EVENT_LE_META:
2180             switch (packet[2]){
2181 #ifdef ENABLE_LE_CENTRAL
2182                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
2183                     // log_info("advertising report received");
2184                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
2185                     le_handle_advertisement_report(packet, size);
2186                     break;
2187 #endif
2188                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
2189                     // Connection management
2190                     reverse_bd_addr(&packet[8], addr);
2191                     addr_type = (bd_addr_type_t)packet[7];
2192                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
2193                     conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2194 
2195 #ifdef ENABLE_LE_CENTRAL
2196                     // if auto-connect, remove from whitelist in both roles
2197                     if (hci_stack->le_connecting_state == LE_CONNECTING_WHITELIST){
2198                         hci_remove_from_whitelist(addr_type, addr);
2199                     }
2200                     // handle error: error is reported only to the initiator -> outgoing connection
2201                     if (packet[3]){
2202 
2203                         // handle cancelled outgoing connection
2204                         // "If the cancellation was successful then, after the Command Complete event for the LE_Create_Connection_Cancel command,
2205                         //  either an LE Connection Complete or an LE Enhanced Connection Complete event shall be generated.
2206                         //  In either case, the event shall be sent with the error code Unknown Connection Identifier (0x02)."
2207                         if (packet[3] == ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER){
2208                             conn = gap_get_outgoing_connection();
2209                         }
2210 
2211                         // outgoing connection establishment is done
2212                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2213                         // remove entry
2214                         if (conn){
2215                             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
2216                             btstack_memory_hci_connection_free( conn );
2217                         }
2218                         break;
2219                     }
2220 #endif
2221                     // on success, both hosts receive connection complete event
2222                     if (packet[6] == HCI_ROLE_MASTER){
2223 #ifdef ENABLE_LE_CENTRAL
2224                         // if we're master, it was an outgoing connection and we're done with it
2225                         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2226 #endif
2227                     } else {
2228 #ifdef ENABLE_LE_PERIPHERAL
2229                         // if we're slave, it was an incoming connection, advertisements have stopped
2230                         hci_stack->le_advertisements_active = 0;
2231                         // try to re-enable them
2232                         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
2233 #endif
2234                     }
2235                     // LE connections are auto-accepted, so just create a connection if there isn't one already
2236                     if (!conn){
2237                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
2238                     }
2239                     // no memory, sorry.
2240                     if (!conn){
2241                         break;
2242                     }
2243 
2244                     conn->state = OPEN;
2245                     conn->role  = packet[6];
2246                     conn->con_handle = little_endian_read_16(packet, 4);
2247 
2248                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
2249 
2250                     // restart timer
2251                     // btstack_run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
2252                     // btstack_run_loop_add_timer(&conn->timeout);
2253 
2254                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
2255 
2256                     hci_emit_nr_connections_changed();
2257                     break;
2258 
2259             // log_info("LE buffer size: %u, count %u", little_endian_read_16(packet,6), packet[8]);
2260 
2261                 default:
2262                     break;
2263             }
2264             break;
2265 #endif
2266         default:
2267             break;
2268     }
2269 
2270     // handle BT initialization
2271     if (hci_stack->state == HCI_STATE_INITIALIZING){
2272         hci_initializing_event_handler(packet, size);
2273     }
2274 
2275     // help with BT sleep
2276     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
2277         && hci_stack->substate == HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE
2278         && HCI_EVENT_IS_COMMAND_COMPLETE(packet, hci_write_scan_enable)){
2279         hci_initializing_next_state();
2280     }
2281 
2282     // notify upper stack
2283 	hci_emit_event(packet, size, 0);   // don't dump, already happened in packet handler
2284 
2285     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
2286     if (hci_event_packet_get_type(packet) == HCI_EVENT_DISCONNECTION_COMPLETE){
2287         if (!packet[2]){
2288             handle = little_endian_read_16(packet, 3);
2289             hci_connection_t * aConn = hci_connection_for_handle(handle);
2290             if (aConn) {
2291                 uint8_t status = aConn->bonding_status;
2292                 uint16_t flags = aConn->bonding_flags;
2293                 bd_addr_t bd_address;
2294                 memcpy(&bd_address, aConn->address, 6);
2295                 hci_shutdown_connection(aConn);
2296                 // connection struct is gone, don't access anymore
2297                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
2298                     hci_emit_dedicated_bonding_result(bd_address, status);
2299                 }
2300             }
2301         }
2302     }
2303 
2304 	// execute main loop
2305 	hci_run();
2306 }
2307 
2308 #ifdef ENABLE_CLASSIC
2309 static void sco_handler(uint8_t * packet, uint16_t size){
2310     if (!hci_stack->sco_packet_handler) return;
2311     hci_stack->sco_packet_handler(HCI_SCO_DATA_PACKET, 0, packet, size);
2312 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2313     hci_con_handle_t con_handle = READ_SCO_CONNECTION_HANDLE(packet);
2314     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
2315     if (conn){
2316         conn->num_packets_completed++;
2317         hci_stack->host_completed_packets = 1;
2318         hci_run();
2319     }
2320 #endif
2321 }
2322 #endif
2323 
2324 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
2325     hci_dump_packet(packet_type, 1, packet, size);
2326     switch (packet_type) {
2327         case HCI_EVENT_PACKET:
2328             event_handler(packet, size);
2329             break;
2330         case HCI_ACL_DATA_PACKET:
2331             acl_handler(packet, size);
2332             break;
2333 #ifdef ENABLE_CLASSIC
2334         case HCI_SCO_DATA_PACKET:
2335             sco_handler(packet, size);
2336             break;
2337 #endif
2338         default:
2339             break;
2340     }
2341 }
2342 
2343 /**
2344  * @brief Add event packet handler.
2345  */
2346 void hci_add_event_handler(btstack_packet_callback_registration_t * callback_handler){
2347     btstack_linked_list_add_tail(&hci_stack->event_handlers, (btstack_linked_item_t*) callback_handler);
2348 }
2349 
2350 
2351 /** Register HCI packet handlers */
2352 void hci_register_acl_packet_handler(btstack_packet_handler_t handler){
2353     hci_stack->acl_packet_handler = handler;
2354 }
2355 
2356 #ifdef ENABLE_CLASSIC
2357 /**
2358  * @brief Registers a packet handler for SCO data. Used for HSP and HFP profiles.
2359  */
2360 void hci_register_sco_packet_handler(btstack_packet_handler_t handler){
2361     hci_stack->sco_packet_handler = handler;
2362 }
2363 #endif
2364 
2365 static void hci_state_reset(void){
2366     // no connections yet
2367     hci_stack->connections = NULL;
2368 
2369     // keep discoverable/connectable as this has been requested by the client(s)
2370     // hci_stack->discoverable = 0;
2371     // hci_stack->connectable = 0;
2372     // hci_stack->bondable = 1;
2373     // hci_stack->own_addr_type = 0;
2374 
2375     // buffer is free
2376     hci_stack->hci_packet_buffer_reserved = 0;
2377 
2378     // no pending cmds
2379     hci_stack->decline_reason = 0;
2380     hci_stack->new_scan_enable_value = 0xff;
2381 
2382     // LE
2383 #ifdef ENABLE_BLE
2384     memset(hci_stack->le_random_address, 0, 6);
2385     hci_stack->le_random_address_set = 0;
2386 #endif
2387 #ifdef ENABLE_LE_CENTRAL
2388     hci_stack->le_scanning_state = LE_SCAN_IDLE;
2389     hci_stack->le_scan_type = 0xff;
2390     hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
2391     hci_stack->le_whitelist = 0;
2392     hci_stack->le_whitelist_capacity = 0;
2393 #endif
2394 }
2395 
2396 #ifdef ENABLE_CLASSIC
2397 /**
2398  * @brief Configure Bluetooth hardware control. Has to be called before power on.
2399  */
2400 void hci_set_link_key_db(btstack_link_key_db_t const * link_key_db){
2401     // store and open remote device db
2402     hci_stack->link_key_db = link_key_db;
2403     if (hci_stack->link_key_db) {
2404         hci_stack->link_key_db->open();
2405     }
2406 }
2407 #endif
2408 
2409 void hci_init(const hci_transport_t *transport, const void *config){
2410 
2411 #ifdef HAVE_MALLOC
2412     if (!hci_stack) {
2413         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
2414     }
2415 #else
2416     hci_stack = &hci_stack_static;
2417 #endif
2418     memset(hci_stack, 0, sizeof(hci_stack_t));
2419 
2420     // reference to use transport layer implementation
2421     hci_stack->hci_transport = transport;
2422 
2423     // reference to used config
2424     hci_stack->config = config;
2425 
2426     // setup pointer for outgoing packet buffer
2427     hci_stack->hci_packet_buffer = &hci_stack->hci_packet_buffer_data[HCI_OUTGOING_PRE_BUFFER_SIZE];
2428 
2429     // max acl payload size defined in config.h
2430     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
2431 
2432     // register packet handlers with transport
2433     transport->register_packet_handler(&packet_handler);
2434 
2435     hci_stack->state = HCI_STATE_OFF;
2436 
2437     // class of device
2438     hci_stack->class_of_device = 0x007a020c; // Smartphone
2439 
2440     // bondable by default
2441     hci_stack->bondable = 1;
2442 
2443 #ifdef ENABLE_CLASSIC
2444     // classic name
2445     hci_stack->local_name = default_classic_name;
2446 
2447     // Master slave policy
2448     hci_stack->master_slave_policy = 1;
2449 #endif
2450 
2451     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
2452     hci_stack->ssp_enable = 1;
2453     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
2454     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
2455     hci_stack->ssp_auto_accept = 1;
2456 
2457     // voice setting - signed 16 bit pcm data with CVSD over the air
2458     hci_stack->sco_voice_setting = 0x60;
2459 
2460 #ifdef ENABLE_LE_CENTRAL
2461     // connection parameter to use for outgoing connections
2462     hci_stack->le_connection_scan_interval = 0x0060;   // 60ms
2463     hci_stack->le_connection_scan_window  = 0x0030;    // 30ms
2464     hci_stack->le_connection_interval_min = 0x0008;    // 10 ms
2465     hci_stack->le_connection_interval_max = 0x0018;    // 30 ms
2466     hci_stack->le_connection_latency      = 4;         // 4
2467     hci_stack->le_supervision_timeout     = 0x0048;    // 720 ms
2468     hci_stack->le_minimum_ce_length       = 2;         // 1.25 ms
2469     hci_stack->le_maximum_ce_length       = 0x0030;    // 30 ms
2470 #endif
2471 
2472     // connection parameter range used to answer connection parameter update requests in l2cap
2473     hci_stack->le_connection_parameter_range.le_conn_interval_min =          6;
2474     hci_stack->le_connection_parameter_range.le_conn_interval_max =       3200;
2475     hci_stack->le_connection_parameter_range.le_conn_latency_min =           0;
2476     hci_stack->le_connection_parameter_range.le_conn_latency_max =         500;
2477     hci_stack->le_connection_parameter_range.le_supervision_timeout_min =   10;
2478     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 3200;
2479 
2480     hci_state_reset();
2481 }
2482 
2483 /**
2484  * @brief Configure Bluetooth chipset driver. Has to be called before power on, or right after receiving the local version information
2485  */
2486 void hci_set_chipset(const btstack_chipset_t *chipset_driver){
2487     hci_stack->chipset = chipset_driver;
2488 
2489     // reset chipset driver - init is also called on power_up
2490     if (hci_stack->chipset && hci_stack->chipset->init){
2491         hci_stack->chipset->init(hci_stack->config);
2492     }
2493 }
2494 
2495 /**
2496  * @brief Configure Bluetooth hardware control. Has to be called after hci_init() but before power on.
2497  */
2498 void hci_set_control(const btstack_control_t *hardware_control){
2499     // references to used control implementation
2500     hci_stack->control = hardware_control;
2501     // init with transport config
2502     hardware_control->init(hci_stack->config);
2503 }
2504 
2505 void hci_close(void){
2506     // close remote device db
2507     if (hci_stack->link_key_db) {
2508         hci_stack->link_key_db->close();
2509     }
2510 
2511     btstack_linked_list_iterator_t lit;
2512     btstack_linked_list_iterator_init(&lit, &hci_stack->connections);
2513     while (btstack_linked_list_iterator_has_next(&lit)){
2514         // cancel all l2cap connections by emitting dicsconnection complete before shutdown (free) connection
2515         hci_connection_t * connection = (hci_connection_t*) btstack_linked_list_iterator_next(&lit);
2516         hci_emit_disconnection_complete(connection->con_handle, 0x16); // terminated by local host
2517         hci_shutdown_connection(connection);
2518     }
2519 
2520     hci_power_control(HCI_POWER_OFF);
2521 
2522 #ifdef HAVE_MALLOC
2523     free(hci_stack);
2524 #endif
2525     hci_stack = NULL;
2526 }
2527 
2528 #ifdef ENABLE_CLASSIC
2529 void gap_set_class_of_device(uint32_t class_of_device){
2530     hci_stack->class_of_device = class_of_device;
2531 }
2532 
2533 void hci_disable_l2cap_timeout_check(void){
2534     disable_l2cap_timeouts = 1;
2535 }
2536 #endif
2537 
2538 #if !defined(HAVE_PLATFORM_IPHONE_OS) && !defined (HAVE_HOST_CONTROLLER_API)
2539 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
2540 void hci_set_bd_addr(bd_addr_t addr){
2541     memcpy(hci_stack->custom_bd_addr, addr, 6);
2542     hci_stack->custom_bd_addr_set = 1;
2543 }
2544 #endif
2545 
2546 // State-Module-Driver overview
2547 // state                    module  low-level
2548 // HCI_STATE_OFF             off      close
2549 // HCI_STATE_INITIALIZING,   on       open
2550 // HCI_STATE_WORKING,        on       open
2551 // HCI_STATE_HALTING,        on       open
2552 // HCI_STATE_SLEEPING,    off/sleep   close
2553 // HCI_STATE_FALLING_ASLEEP  on       open
2554 
2555 static int hci_power_control_on(void){
2556 
2557     // power on
2558     int err = 0;
2559     if (hci_stack->control && hci_stack->control->on){
2560         err = (*hci_stack->control->on)();
2561     }
2562     if (err){
2563         log_error( "POWER_ON failed");
2564         hci_emit_hci_open_failed();
2565         return err;
2566     }
2567 
2568     // int chipset driver
2569     if (hci_stack->chipset && hci_stack->chipset->init){
2570         hci_stack->chipset->init(hci_stack->config);
2571     }
2572 
2573     // init transport
2574     if (hci_stack->hci_transport->init){
2575         hci_stack->hci_transport->init(hci_stack->config);
2576     }
2577 
2578     // open transport
2579     err = hci_stack->hci_transport->open();
2580     if (err){
2581         log_error( "HCI_INIT failed, turning Bluetooth off again");
2582         if (hci_stack->control && hci_stack->control->off){
2583             (*hci_stack->control->off)();
2584         }
2585         hci_emit_hci_open_failed();
2586         return err;
2587     }
2588     return 0;
2589 }
2590 
2591 static void hci_power_control_off(void){
2592 
2593     log_info("hci_power_control_off");
2594 
2595     // close low-level device
2596     hci_stack->hci_transport->close();
2597 
2598     log_info("hci_power_control_off - hci_transport closed");
2599 
2600     // power off
2601     if (hci_stack->control && hci_stack->control->off){
2602         (*hci_stack->control->off)();
2603     }
2604 
2605     log_info("hci_power_control_off - control closed");
2606 
2607     hci_stack->state = HCI_STATE_OFF;
2608 }
2609 
2610 static void hci_power_control_sleep(void){
2611 
2612     log_info("hci_power_control_sleep");
2613 
2614 #if 0
2615     // don't close serial port during sleep
2616 
2617     // close low-level device
2618     hci_stack->hci_transport->close(hci_stack->config);
2619 #endif
2620 
2621     // sleep mode
2622     if (hci_stack->control && hci_stack->control->sleep){
2623         (*hci_stack->control->sleep)();
2624     }
2625 
2626     hci_stack->state = HCI_STATE_SLEEPING;
2627 }
2628 
2629 static int hci_power_control_wake(void){
2630 
2631     log_info("hci_power_control_wake");
2632 
2633     // wake on
2634     if (hci_stack->control && hci_stack->control->wake){
2635         (*hci_stack->control->wake)();
2636     }
2637 
2638 #if 0
2639     // open low-level device
2640     int err = hci_stack->hci_transport->open(hci_stack->config);
2641     if (err){
2642         log_error( "HCI_INIT failed, turning Bluetooth off again");
2643         if (hci_stack->control && hci_stack->control->off){
2644             (*hci_stack->control->off)();
2645         }
2646         hci_emit_hci_open_failed();
2647         return err;
2648     }
2649 #endif
2650 
2651     return 0;
2652 }
2653 
2654 static void hci_power_transition_to_initializing(void){
2655     // set up state machine
2656     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
2657     hci_stack->hci_packet_buffer_reserved = 0;
2658     hci_stack->state = HCI_STATE_INITIALIZING;
2659     hci_stack->substate = HCI_INIT_SEND_RESET;
2660 }
2661 
2662 int hci_power_control(HCI_POWER_MODE power_mode){
2663 
2664     log_info("hci_power_control: %d, current mode %u", power_mode, hci_stack->state);
2665 
2666     int err = 0;
2667     switch (hci_stack->state){
2668 
2669         case HCI_STATE_OFF:
2670             switch (power_mode){
2671                 case HCI_POWER_ON:
2672                     err = hci_power_control_on();
2673                     if (err) {
2674                         log_error("hci_power_control_on() error %d", err);
2675                         return err;
2676                     }
2677                     hci_power_transition_to_initializing();
2678                     break;
2679                 case HCI_POWER_OFF:
2680                     // do nothing
2681                     break;
2682                 case HCI_POWER_SLEEP:
2683                     // do nothing (with SLEEP == OFF)
2684                     break;
2685             }
2686             break;
2687 
2688         case HCI_STATE_INITIALIZING:
2689             switch (power_mode){
2690                 case HCI_POWER_ON:
2691                     // do nothing
2692                     break;
2693                 case HCI_POWER_OFF:
2694                     // no connections yet, just turn it off
2695                     hci_power_control_off();
2696                     break;
2697                 case HCI_POWER_SLEEP:
2698                     // no connections yet, just turn it off
2699                     hci_power_control_sleep();
2700                     break;
2701             }
2702             break;
2703 
2704         case HCI_STATE_WORKING:
2705             switch (power_mode){
2706                 case HCI_POWER_ON:
2707                     // do nothing
2708                     break;
2709                 case HCI_POWER_OFF:
2710                     // see hci_run
2711                     hci_stack->state = HCI_STATE_HALTING;
2712                     break;
2713                 case HCI_POWER_SLEEP:
2714                     // see hci_run
2715                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2716                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2717                     break;
2718             }
2719             break;
2720 
2721         case HCI_STATE_HALTING:
2722             switch (power_mode){
2723                 case HCI_POWER_ON:
2724                     hci_power_transition_to_initializing();
2725                     break;
2726                 case HCI_POWER_OFF:
2727                     // do nothing
2728                     break;
2729                 case HCI_POWER_SLEEP:
2730                     // see hci_run
2731                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
2732                     hci_stack->substate = HCI_FALLING_ASLEEP_DISCONNECT;
2733                     break;
2734             }
2735             break;
2736 
2737         case HCI_STATE_FALLING_ASLEEP:
2738             switch (power_mode){
2739                 case HCI_POWER_ON:
2740 
2741 #ifdef HAVE_PLATFORM_IPHONE_OS
2742                     // nothing to do, if H4 supports power management
2743                     if (btstack_control_iphone_power_management_enabled()){
2744                         hci_stack->state = HCI_STATE_INITIALIZING;
2745                         hci_stack->substate = HCI_INIT_WRITE_SCAN_ENABLE;   // init after sleep
2746                         break;
2747                     }
2748 #endif
2749                     hci_power_transition_to_initializing();
2750                     break;
2751                 case HCI_POWER_OFF:
2752                     // see hci_run
2753                     hci_stack->state = HCI_STATE_HALTING;
2754                     break;
2755                 case HCI_POWER_SLEEP:
2756                     // do nothing
2757                     break;
2758             }
2759             break;
2760 
2761         case HCI_STATE_SLEEPING:
2762             switch (power_mode){
2763                 case HCI_POWER_ON:
2764 
2765 #ifdef HAVE_PLATFORM_IPHONE_OS
2766                     // nothing to do, if H4 supports power management
2767                     if (btstack_control_iphone_power_management_enabled()){
2768                         hci_stack->state = HCI_STATE_INITIALIZING;
2769                         hci_stack->substate = HCI_INIT_AFTER_SLEEP;
2770                         hci_update_scan_enable();
2771                         break;
2772                     }
2773 #endif
2774                     err = hci_power_control_wake();
2775                     if (err) return err;
2776                     hci_power_transition_to_initializing();
2777                     break;
2778                 case HCI_POWER_OFF:
2779                     hci_stack->state = HCI_STATE_HALTING;
2780                     break;
2781                 case HCI_POWER_SLEEP:
2782                     // do nothing
2783                     break;
2784             }
2785             break;
2786     }
2787 
2788     // create internal event
2789 	hci_emit_state();
2790 
2791 	// trigger next/first action
2792 	hci_run();
2793 
2794     return 0;
2795 }
2796 
2797 
2798 #ifdef ENABLE_CLASSIC
2799 
2800 static void hci_update_scan_enable(void){
2801     // 2 = page scan, 1 = inq scan
2802     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
2803     hci_run();
2804 }
2805 
2806 void gap_discoverable_control(uint8_t enable){
2807     if (enable) enable = 1; // normalize argument
2808 
2809     if (hci_stack->discoverable == enable){
2810         hci_emit_discoverable_enabled(hci_stack->discoverable);
2811         return;
2812     }
2813 
2814     hci_stack->discoverable = enable;
2815     hci_update_scan_enable();
2816 }
2817 
2818 void gap_connectable_control(uint8_t enable){
2819     if (enable) enable = 1; // normalize argument
2820 
2821     // don't emit event
2822     if (hci_stack->connectable == enable) return;
2823 
2824     hci_stack->connectable = enable;
2825     hci_update_scan_enable();
2826 }
2827 #endif
2828 
2829 void gap_local_bd_addr(bd_addr_t address_buffer){
2830     memcpy(address_buffer, hci_stack->local_bd_addr, 6);
2831 }
2832 
2833 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2834 static void hci_host_num_completed_packets(void){
2835 
2836     // create packet manually as arrays are not supported and num_commands should not get reduced
2837     hci_reserve_packet_buffer();
2838     uint8_t * packet = hci_get_outgoing_packet_buffer();
2839 
2840     uint16_t size = 0;
2841     uint16_t num_handles = 0;
2842     packet[size++] = 0x35;
2843     packet[size++] = 0x0c;
2844     size++;  // skip param len
2845     size++;  // skip num handles
2846 
2847     // add { handle, packets } entries
2848     btstack_linked_item_t * it;
2849     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
2850         hci_connection_t * connection = (hci_connection_t *) it;
2851         if (connection->num_packets_completed){
2852             little_endian_store_16(packet, size, connection->con_handle);
2853             size += 2;
2854             little_endian_store_16(packet, size, connection->num_packets_completed);
2855             size += 2;
2856             //
2857             num_handles++;
2858             connection->num_packets_completed = 0;
2859         }
2860     }
2861 
2862     packet[2] = size - 3;
2863     packet[3] = num_handles;
2864 
2865     hci_stack->host_completed_packets = 0;
2866 
2867     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
2868     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
2869 
2870     // release packet buffer for synchronous transport implementations
2871     if (hci_transport_synchronous()){
2872         hci_stack->hci_packet_buffer_reserved = 0;
2873     }
2874 }
2875 #endif
2876 
2877 static void hci_run(void){
2878 
2879     // log_info("hci_run: entered");
2880     btstack_linked_item_t * it;
2881 
2882     // send continuation fragments first, as they block the prepared packet buffer
2883     if (hci_stack->acl_fragmentation_total_size > 0) {
2884         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
2885         hci_connection_t *connection = hci_connection_for_handle(con_handle);
2886         if (connection) {
2887             if (hci_can_send_prepared_acl_packet_now(con_handle)){
2888                 hci_send_acl_packet_fragments(connection);
2889                 return;
2890             }
2891         } else {
2892             // connection gone -> discard further fragments
2893             log_info("hci_run: fragmented ACL packet no connection -> discard fragment");
2894             hci_stack->acl_fragmentation_total_size = 0;
2895             hci_stack->acl_fragmentation_pos = 0;
2896         }
2897     }
2898 
2899 #ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
2900     // send host num completed packets next as they don't require num_cmd_packets > 0
2901     if (!hci_can_send_comand_packet_transport()) return;
2902     if (hci_stack->host_completed_packets){
2903         hci_host_num_completed_packets();
2904         return;
2905     }
2906 #endif
2907 
2908     if (!hci_can_send_command_packet_now()) return;
2909 
2910     // global/non-connection oriented commands
2911 
2912 #ifdef ENABLE_CLASSIC
2913     // decline incoming connections
2914     if (hci_stack->decline_reason){
2915         uint8_t reason = hci_stack->decline_reason;
2916         hci_stack->decline_reason = 0;
2917         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
2918         return;
2919     }
2920     // send scan enable
2921     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
2922         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
2923         hci_stack->new_scan_enable_value = 0xff;
2924         return;
2925     }
2926     // start/stop inquiry
2927     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN && hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX){
2928         uint8_t duration = hci_stack->inquiry_state;
2929         hci_stack->inquiry_state = GAP_INQUIRY_STATE_ACTIVE;
2930         hci_send_cmd(&hci_inquiry, HCI_INQUIRY_LAP, duration, 0);
2931         return;
2932     }
2933     if (hci_stack->inquiry_state == GAP_INQUIRY_STATE_W2_CANCEL){
2934         hci_stack->inquiry_state = GAP_INQUIRY_STATE_W4_CANCELLED;
2935         hci_send_cmd(&hci_inquiry_cancel);
2936         return;
2937     }
2938     // remote name request
2939     if (hci_stack->remote_name_state == GAP_REMOTE_NAME_STATE_W2_SEND){
2940         hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W4_COMPLETE;
2941         hci_send_cmd(&hci_remote_name_request, hci_stack->remote_name_addr,
2942             hci_stack->remote_name_page_scan_repetition_mode, 0, hci_stack->remote_name_clock_offset);
2943         return;
2944     }
2945     // pairing
2946     if (hci_stack->gap_pairing_state != GAP_PAIRING_STATE_IDLE){
2947         uint8_t state = hci_stack->gap_pairing_state;
2948         hci_stack->gap_pairing_state = GAP_PAIRING_STATE_IDLE;
2949         switch (state){
2950             case GAP_PAIRING_STATE_SEND_PIN:
2951                 hci_send_cmd(&hci_pin_code_request_reply, hci_stack->gap_pairing_addr, strlen(hci_stack->gap_pairing_pin), hci_stack->gap_pairing_pin);
2952                 break;
2953             case GAP_PAIRING_STATE_SEND_PIN_NEGATIVE:
2954                 hci_send_cmd(&hci_pin_code_request_negative_reply, hci_stack->gap_pairing_addr);
2955                 break;
2956             case GAP_PAIRING_STATE_SEND_PASSKEY:
2957                 hci_send_cmd(&hci_user_passkey_request_reply, hci_stack->gap_pairing_addr, hci_stack->gap_pairing_passkey);
2958                 break;
2959             case GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE:
2960                 hci_send_cmd(&hci_user_passkey_request_negative_reply, hci_stack->gap_pairing_addr);
2961                 break;
2962             case GAP_PAIRING_STATE_SEND_CONFIRMATION:
2963                 hci_send_cmd(&hci_user_confirmation_request_reply, hci_stack->gap_pairing_addr);
2964                 break;
2965             case GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE:
2966                 hci_send_cmd(&hci_user_confirmation_request_negative_reply, hci_stack->gap_pairing_addr);
2967                 break;
2968             default:
2969                 break;
2970         }
2971         return;
2972     }
2973 #endif
2974 
2975 #ifdef ENABLE_BLE
2976     // advertisements, active scanning, and creating connections requires randaom address to be set if using private address
2977     if ((hci_stack->state == HCI_STATE_WORKING)
2978     && (hci_stack->le_own_addr_type == BD_ADDR_TYPE_LE_PUBLIC || hci_stack->le_random_address_set)){
2979 
2980 #ifdef ENABLE_LE_CENTRAL
2981         // handle le scan
2982         switch(hci_stack->le_scanning_state){
2983             case LE_START_SCAN:
2984                 hci_stack->le_scanning_state = LE_SCANNING;
2985                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
2986                 return;
2987 
2988             case LE_STOP_SCAN:
2989                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
2990                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
2991                 return;
2992             default:
2993                 break;
2994         }
2995         if (hci_stack->le_scan_type != 0xff){
2996             // defaults: active scanning, accept all advertisement packets
2997             int scan_type = hci_stack->le_scan_type;
2998             hci_stack->le_scan_type = 0xff;
2999             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);
3000             return;
3001         }
3002 #endif
3003 #ifdef ENABLE_LE_PERIPHERAL
3004         // le advertisement control
3005         if (hci_stack->le_advertisements_todo){
3006             log_info("hci_run: gap_le: adv todo: %x", hci_stack->le_advertisements_todo );
3007         }
3008         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_DISABLE){
3009             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_DISABLE;
3010             hci_send_cmd(&hci_le_set_advertise_enable, 0);
3011             return;
3012         }
3013         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_PARAMS){
3014             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_PARAMS;
3015             hci_send_cmd(&hci_le_set_advertising_parameters,
3016                  hci_stack->le_advertisements_interval_min,
3017                  hci_stack->le_advertisements_interval_max,
3018                  hci_stack->le_advertisements_type,
3019                  hci_stack->le_own_addr_type,
3020                  hci_stack->le_advertisements_direct_address_type,
3021                  hci_stack->le_advertisements_direct_address,
3022                  hci_stack->le_advertisements_channel_map,
3023                  hci_stack->le_advertisements_filter_policy);
3024             return;
3025         }
3026         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_ADV_DATA){
3027             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
3028             uint8_t adv_data_clean[31];
3029             memset(adv_data_clean, 0, sizeof(adv_data_clean));
3030             memcpy(adv_data_clean, hci_stack->le_advertisements_data, hci_stack->le_advertisements_data_len);
3031             hci_replace_bd_addr_placeholder(adv_data_clean, hci_stack->le_advertisements_data_len);
3032             hci_send_cmd(&hci_le_set_advertising_data, hci_stack->le_advertisements_data_len, adv_data_clean);
3033             return;
3034         }
3035         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA){
3036             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
3037             uint8_t scan_data_clean[31];
3038             memset(scan_data_clean, 0, sizeof(scan_data_clean));
3039             memcpy(scan_data_clean, hci_stack->le_scan_response_data, hci_stack->le_scan_response_data_len);
3040             hci_replace_bd_addr_placeholder(scan_data_clean, hci_stack->le_scan_response_data_len);
3041             hci_send_cmd(&hci_le_set_scan_response_data, hci_stack->le_scan_response_data_len, hci_stack->le_scan_response_data);
3042             return;
3043         }
3044         if (hci_stack->le_advertisements_todo & LE_ADVERTISEMENT_TASKS_ENABLE){
3045             hci_stack->le_advertisements_todo &= ~LE_ADVERTISEMENT_TASKS_ENABLE;
3046             hci_send_cmd(&hci_le_set_advertise_enable, 1);
3047             return;
3048         }
3049 #endif
3050 
3051 #ifdef ENABLE_LE_CENTRAL
3052         //
3053         // LE Whitelist Management
3054         //
3055 
3056         // check if whitelist needs modification
3057         btstack_linked_list_iterator_t lit;
3058         int modification_pending = 0;
3059         btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3060         while (btstack_linked_list_iterator_has_next(&lit)){
3061             whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3062             if (entry->state & (LE_WHITELIST_REMOVE_FROM_CONTROLLER | LE_WHITELIST_ADD_TO_CONTROLLER)){
3063                 modification_pending = 1;
3064                 break;
3065             }
3066         }
3067 
3068         if (modification_pending){
3069             // stop connnecting if modification pending
3070             if (hci_stack->le_connecting_state != LE_CONNECTING_IDLE){
3071                 hci_send_cmd(&hci_le_create_connection_cancel);
3072                 return;
3073             }
3074 
3075             // add/remove entries
3076             btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3077             while (btstack_linked_list_iterator_has_next(&lit)){
3078                 whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3079                 if (entry->state & LE_WHITELIST_ADD_TO_CONTROLLER){
3080                     entry->state = LE_WHITELIST_ON_CONTROLLER;
3081                     hci_send_cmd(&hci_le_add_device_to_white_list, entry->address_type, entry->address);
3082                     return;
3083 
3084                 }
3085                 if (entry->state & LE_WHITELIST_REMOVE_FROM_CONTROLLER){
3086                     bd_addr_t address;
3087                     bd_addr_type_t address_type = entry->address_type;
3088                     memcpy(address, entry->address, 6);
3089                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3090                     btstack_memory_whitelist_entry_free(entry);
3091                     hci_send_cmd(&hci_le_remove_device_from_white_list, address_type, address);
3092                     return;
3093                 }
3094             }
3095         }
3096 
3097         // start connecting
3098         if ( hci_stack->le_connecting_state == LE_CONNECTING_IDLE &&
3099             !btstack_linked_list_empty(&hci_stack->le_whitelist)){
3100             bd_addr_t null_addr;
3101             memset(null_addr, 0, 6);
3102             hci_send_cmd(&hci_le_create_connection,
3103                 hci_stack->le_connection_scan_interval,    // scan interval: 60 ms
3104                 hci_stack->le_connection_scan_window,    // scan interval: 30 ms
3105                  1,         // use whitelist
3106                  0,         // peer address type
3107                  null_addr, // peer bd addr
3108                  hci_stack->le_own_addr_type, // our addr type:
3109                  hci_stack->le_connection_interval_min,    // conn interval min
3110                  hci_stack->le_connection_interval_max,    // conn interval max
3111                  hci_stack->le_connection_latency,         // conn latency
3112                  hci_stack->le_supervision_timeout,        // conn latency
3113                  hci_stack->le_minimum_ce_length,          // min ce length
3114                  hci_stack->le_maximum_ce_length           // max ce length
3115                 );
3116             return;
3117         }
3118 #endif
3119     }
3120 #endif
3121 
3122     // send pending HCI commands
3123     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
3124         hci_connection_t * connection = (hci_connection_t *) it;
3125 
3126         switch(connection->state){
3127             case SEND_CREATE_CONNECTION:
3128                 switch(connection->address_type){
3129 #ifdef ENABLE_CLASSIC
3130                     case BD_ADDR_TYPE_CLASSIC:
3131                         log_info("sending hci_create_connection");
3132                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
3133                         break;
3134 #endif
3135                     default:
3136 #ifdef ENABLE_BLE
3137 #ifdef ENABLE_LE_CENTRAL
3138                         log_info("sending hci_le_create_connection");
3139                         hci_send_cmd(&hci_le_create_connection,
3140                              hci_stack->le_connection_scan_interval,    // conn scan interval
3141                              hci_stack->le_connection_scan_window,      // conn scan windows
3142                              0,         // don't use whitelist
3143                              connection->address_type, // peer address type
3144                              connection->address,      // peer bd addr
3145                              hci_stack->le_own_addr_type, // our addr type:
3146                              hci_stack->le_connection_interval_min,    // conn interval min
3147                              hci_stack->le_connection_interval_max,    // conn interval max
3148                              hci_stack->le_connection_latency,         // conn latency
3149                              hci_stack->le_supervision_timeout,        // conn latency
3150                              hci_stack->le_minimum_ce_length,          // min ce length
3151                              hci_stack->le_maximum_ce_length          // max ce length
3152                              );
3153                         connection->state = SENT_CREATE_CONNECTION;
3154 #endif
3155 #endif
3156                         break;
3157                 }
3158                 return;
3159 
3160 #ifdef ENABLE_CLASSIC
3161             case RECEIVED_CONNECTION_REQUEST:
3162                 log_info("sending hci_accept_connection_request, remote eSCO %u", connection->remote_supported_feature_eSCO);
3163                 connection->state = ACCEPTED_CONNECTION_REQUEST;
3164                 connection->role  = HCI_ROLE_SLAVE;
3165                 if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
3166                     hci_send_cmd(&hci_accept_connection_request, connection->address, hci_stack->master_slave_policy);
3167                 }
3168                 return;
3169 #endif
3170 
3171 #ifdef ENABLE_BLE
3172 #ifdef ENABLE_LE_CENTRAL
3173             case SEND_CANCEL_CONNECTION:
3174                 connection->state = SENT_CANCEL_CONNECTION;
3175                 hci_send_cmd(&hci_le_create_connection_cancel);
3176                 return;
3177 #endif
3178 #endif
3179             case SEND_DISCONNECT:
3180                 connection->state = SENT_DISCONNECT;
3181                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
3182                 return;
3183 
3184             default:
3185                 break;
3186         }
3187 
3188 #ifdef ENABLE_CLASSIC
3189         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
3190             log_info("responding to link key request");
3191             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
3192             link_key_t link_key;
3193             link_key_type_t link_key_type;
3194             if ( hci_stack->link_key_db
3195               && hci_stack->link_key_db->get_link_key(connection->address, link_key, &link_key_type)
3196               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
3197                connection->link_key_type = link_key_type;
3198                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
3199             } else {
3200                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
3201             }
3202             return;
3203         }
3204 
3205         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
3206             log_info("denying to pin request");
3207             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
3208             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
3209             return;
3210         }
3211 
3212         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
3213             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
3214             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
3215             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
3216                 // tweak authentication requirements
3217                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
3218                 if (connection->bonding_flags & BONDING_DEDICATED){
3219                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
3220                 }
3221                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
3222                     authreq |= 1;
3223                 }
3224                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
3225             } else {
3226                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
3227             }
3228             return;
3229         }
3230 
3231         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
3232             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
3233             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
3234             return;
3235         }
3236 
3237         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
3238             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
3239             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
3240             return;
3241         }
3242 
3243         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
3244             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
3245             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
3246             return;
3247         }
3248 
3249         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
3250             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
3251             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
3252             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
3253             return;
3254         }
3255 
3256         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
3257             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
3258             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
3259             return;
3260         }
3261 
3262         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
3263             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
3264             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
3265             return;
3266         }
3267 #endif
3268 
3269         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
3270             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
3271             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
3272             return;
3273         }
3274 
3275 #ifdef ENABLE_BLE
3276         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
3277             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
3278 
3279             uint16_t connection_interval_min = connection->le_conn_interval_min;
3280             connection->le_conn_interval_min = 0;
3281             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
3282                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
3283                 0x0000, 0xffff);
3284         }
3285 #endif
3286     }
3287 
3288     hci_connection_t * connection;
3289     switch (hci_stack->state){
3290         case HCI_STATE_INITIALIZING:
3291             hci_initializing_run();
3292             break;
3293 
3294         case HCI_STATE_HALTING:
3295 
3296             log_info("HCI_STATE_HALTING");
3297 
3298             // free whitelist entries
3299 #ifdef ENABLE_BLE
3300 #ifdef ENABLE_LE_CENTRAL
3301             {
3302                 btstack_linked_list_iterator_t lit;
3303                 btstack_linked_list_iterator_init(&lit, &hci_stack->le_whitelist);
3304                 while (btstack_linked_list_iterator_has_next(&lit)){
3305                     whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&lit);
3306                     btstack_linked_list_remove(&hci_stack->le_whitelist, (btstack_linked_item_t *) entry);
3307                     btstack_memory_whitelist_entry_free(entry);
3308                 }
3309             }
3310 #endif
3311 #endif
3312             // close all open connections
3313             connection =  (hci_connection_t *) hci_stack->connections;
3314             if (connection){
3315                 hci_con_handle_t con_handle = (uint16_t) connection->con_handle;
3316                 if (!hci_can_send_command_packet_now()) return;
3317 
3318                 // check state
3319                 if (connection->state == SENT_DISCONNECT) return;
3320                 connection->state = SENT_DISCONNECT;
3321 
3322                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, con_handle);
3323 
3324                 // cancel all l2cap connections right away instead of waiting for disconnection complete event ...
3325                 hci_emit_disconnection_complete(con_handle, 0x16); // terminated by local host
3326 
3327                 // ... which would be ignored anyway as we shutdown (free) the connection now
3328                 hci_shutdown_connection(connection);
3329 
3330                 // finally, send the disconnect command
3331                 hci_send_cmd(&hci_disconnect, con_handle, 0x13);  // remote closed connection
3332                 return;
3333             }
3334             log_info("HCI_STATE_HALTING, calling off");
3335 
3336             // switch mode
3337             hci_power_control_off();
3338 
3339             log_info("HCI_STATE_HALTING, emitting state");
3340             hci_emit_state();
3341             log_info("HCI_STATE_HALTING, done");
3342             break;
3343 
3344         case HCI_STATE_FALLING_ASLEEP:
3345             switch(hci_stack->substate) {
3346                 case HCI_FALLING_ASLEEP_DISCONNECT:
3347                     log_info("HCI_STATE_FALLING_ASLEEP");
3348                     // close all open connections
3349                     connection =  (hci_connection_t *) hci_stack->connections;
3350 
3351 #ifdef HAVE_PLATFORM_IPHONE_OS
3352                     // don't close connections, if H4 supports power management
3353                     if (btstack_control_iphone_power_management_enabled()){
3354                         connection = NULL;
3355                     }
3356 #endif
3357                     if (connection){
3358 
3359                         // send disconnect
3360                         if (!hci_can_send_command_packet_now()) return;
3361 
3362                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
3363                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
3364 
3365                         // send disconnected event right away - causes higher layer connections to get closed, too.
3366                         hci_shutdown_connection(connection);
3367                         return;
3368                     }
3369 
3370                     if (hci_classic_supported()){
3371                         // disable page and inquiry scan
3372                         if (!hci_can_send_command_packet_now()) return;
3373 
3374                         log_info("HCI_STATE_HALTING, disabling inq scans");
3375                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
3376 
3377                         // continue in next sub state
3378                         hci_stack->substate = HCI_FALLING_ASLEEP_W4_WRITE_SCAN_ENABLE;
3379                         break;
3380                     }
3381                     // no break - fall through for ble-only chips
3382 
3383                 case HCI_FALLING_ASLEEP_COMPLETE:
3384                     log_info("HCI_STATE_HALTING, calling sleep");
3385 #ifdef HAVE_PLATFORM_IPHONE_OS
3386                     // don't actually go to sleep, if H4 supports power management
3387                     if (btstack_control_iphone_power_management_enabled()){
3388                         // SLEEP MODE reached
3389                         hci_stack->state = HCI_STATE_SLEEPING;
3390                         hci_emit_state();
3391                         break;
3392                     }
3393 #endif
3394                     // switch mode
3395                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
3396                     hci_emit_state();
3397                     break;
3398 
3399                 default:
3400                     break;
3401             }
3402             break;
3403 
3404         default:
3405             break;
3406     }
3407 }
3408 
3409 int hci_send_cmd_packet(uint8_t *packet, int size){
3410     // house-keeping
3411 
3412     if (IS_COMMAND(packet, hci_write_loopback_mode)){
3413         hci_stack->loopback_mode = packet[3];
3414     }
3415 
3416 #ifdef ENABLE_CLASSIC
3417     bd_addr_t addr;
3418     hci_connection_t * conn;
3419 
3420     // create_connection?
3421     if (IS_COMMAND(packet, hci_create_connection)){
3422         reverse_bd_addr(&packet[3], addr);
3423         log_info("Create_connection to %s", bd_addr_to_str(addr));
3424 
3425         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3426         if (!conn){
3427             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3428             if (!conn){
3429                 // notify client that alloc failed
3430                 hci_emit_connection_complete(addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
3431                 return 0; // don't sent packet to controller
3432             }
3433             conn->state = SEND_CREATE_CONNECTION;
3434         }
3435         log_info("conn state %u", conn->state);
3436         switch (conn->state){
3437             // if connection active exists
3438             case OPEN:
3439                 // and OPEN, emit connection complete command, don't send to controller
3440                 hci_emit_connection_complete(addr, conn->con_handle, 0);
3441                 return 0;
3442             case SEND_CREATE_CONNECTION:
3443                 // connection created by hci, e.g. dedicated bonding
3444                 break;
3445             default:
3446                 // otherwise, just ignore as it is already in the open process
3447                 return 0;
3448         }
3449         conn->state = SENT_CREATE_CONNECTION;
3450     }
3451 
3452     if (IS_COMMAND(packet, hci_link_key_request_reply)){
3453         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
3454     }
3455     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
3456         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
3457     }
3458 
3459     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
3460         if (hci_stack->link_key_db){
3461             reverse_bd_addr(&packet[3], addr);
3462             hci_stack->link_key_db->delete_link_key(addr);
3463         }
3464     }
3465 
3466     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
3467     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
3468         reverse_bd_addr(&packet[3], addr);
3469         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3470         if (conn){
3471             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
3472         }
3473     }
3474 
3475     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
3476     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
3477     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
3478     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
3479         reverse_bd_addr(&packet[3], addr);
3480         conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
3481         if (conn){
3482             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
3483         }
3484     }
3485 
3486 #ifdef ENABLE_SCO_OVER_HCI
3487     // setup_synchronous_connection? Voice setting at offset 22
3488     if (IS_COMMAND(packet, hci_setup_synchronous_connection)){
3489         // TODO: compare to current setting if sco connection already active
3490         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 15);
3491     }
3492     // accept_synchronus_connection? Voice setting at offset 18
3493     if (IS_COMMAND(packet, hci_accept_synchronous_connection)){
3494         // TODO: compare to current setting if sco connection already active
3495         hci_stack->sco_voice_setting_active = little_endian_read_16(packet, 19);
3496     }
3497 #endif
3498 #endif
3499 
3500 #ifdef ENABLE_BLE
3501 #ifdef ENABLE_LE_PERIPHERAL
3502     if (IS_COMMAND(packet, hci_le_set_random_address)){
3503         hci_stack->le_random_address_set = 1;
3504         reverse_bd_addr(&packet[3], hci_stack->le_random_address);
3505     }
3506     if (IS_COMMAND(packet, hci_le_set_advertise_enable)){
3507         hci_stack->le_advertisements_active = packet[3];
3508     }
3509 #endif
3510 #ifdef ENABLE_LE_CENTRAL
3511     if (IS_COMMAND(packet, hci_le_create_connection)){
3512         // white list used?
3513         uint8_t initiator_filter_policy = packet[7];
3514         switch (initiator_filter_policy){
3515             case 0:
3516                 // whitelist not used
3517                 hci_stack->le_connecting_state = LE_CONNECTING_DIRECT;
3518                 break;
3519             case 1:
3520                 hci_stack->le_connecting_state = LE_CONNECTING_WHITELIST;
3521                 break;
3522             default:
3523                 log_error("Invalid initiator_filter_policy in LE Create Connection %u", initiator_filter_policy);
3524                 break;
3525         }
3526     }
3527     if (IS_COMMAND(packet, hci_le_create_connection_cancel)){
3528         hci_stack->le_connecting_state = LE_CONNECTING_IDLE;
3529     }
3530 #endif
3531 #endif
3532 
3533     hci_stack->num_cmd_packets--;
3534 
3535     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
3536     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
3537 
3538     // release packet buffer for synchronous transport implementations
3539     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
3540         hci_stack->hci_packet_buffer_reserved = 0;
3541     }
3542 
3543     return err;
3544 }
3545 
3546 // disconnect because of security block
3547 void hci_disconnect_security_block(hci_con_handle_t con_handle){
3548     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3549     if (!connection) return;
3550     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
3551 }
3552 
3553 
3554 // Configure Secure Simple Pairing
3555 
3556 #ifdef ENABLE_CLASSIC
3557 
3558 // enable will enable SSP during init
3559 void gap_ssp_set_enable(int enable){
3560     hci_stack->ssp_enable = enable;
3561 }
3562 
3563 static int hci_local_ssp_activated(void){
3564     return gap_ssp_supported() && hci_stack->ssp_enable;
3565 }
3566 
3567 // if set, BTstack will respond to io capability request using authentication requirement
3568 void gap_ssp_set_io_capability(int io_capability){
3569     hci_stack->ssp_io_capability = io_capability;
3570 }
3571 void gap_ssp_set_authentication_requirement(int authentication_requirement){
3572     hci_stack->ssp_authentication_requirement = authentication_requirement;
3573 }
3574 
3575 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
3576 void gap_ssp_set_auto_accept(int auto_accept){
3577     hci_stack->ssp_auto_accept = auto_accept;
3578 }
3579 #endif
3580 
3581 // va_list part of hci_send_cmd
3582 int hci_send_cmd_va_arg(const hci_cmd_t *cmd, va_list argptr){
3583     if (!hci_can_send_command_packet_now()){
3584         log_error("hci_send_cmd called but cannot send packet now");
3585         return 0;
3586     }
3587 
3588     // for HCI INITIALIZATION
3589     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
3590     hci_stack->last_cmd_opcode = cmd->opcode;
3591 
3592     hci_reserve_packet_buffer();
3593     uint8_t * packet = hci_stack->hci_packet_buffer;
3594     uint16_t size = hci_cmd_create_from_template(packet, cmd, argptr);
3595     return hci_send_cmd_packet(packet, size);
3596 }
3597 
3598 /**
3599  * pre: numcmds >= 0 - it's allowed to send a command to the controller
3600  */
3601 int hci_send_cmd(const hci_cmd_t *cmd, ...){
3602     va_list argptr;
3603     va_start(argptr, cmd);
3604     int res = hci_send_cmd_va_arg(cmd, argptr);
3605     va_end(argptr);
3606     return res;
3607 }
3608 
3609 // Create various non-HCI events.
3610 // TODO: generalize, use table similar to hci_create_command
3611 
3612 static void hci_emit_event(uint8_t * event, uint16_t size, int dump){
3613     // dump packet
3614     if (dump) {
3615         hci_dump_packet( HCI_EVENT_PACKET, 0, event, size);
3616     }
3617 
3618     // dispatch to all event handlers
3619     btstack_linked_list_iterator_t it;
3620     btstack_linked_list_iterator_init(&it, &hci_stack->event_handlers);
3621     while (btstack_linked_list_iterator_has_next(&it)){
3622         btstack_packet_callback_registration_t * entry = (btstack_packet_callback_registration_t*) btstack_linked_list_iterator_next(&it);
3623         entry->callback(HCI_EVENT_PACKET, 0, event, size);
3624     }
3625 }
3626 
3627 static void hci_emit_acl_packet(uint8_t * packet, uint16_t size){
3628     if (!hci_stack->acl_packet_handler) return;
3629     hci_stack->acl_packet_handler(HCI_ACL_DATA_PACKET, 0, packet, size);
3630 }
3631 
3632 #ifdef ENABLE_CLASSIC
3633 static void hci_notify_if_sco_can_send_now(void){
3634     // notify SCO sender if waiting
3635     if (!hci_stack->sco_waiting_for_can_send_now) return;
3636     if (hci_can_send_sco_packet_now()){
3637         hci_stack->sco_waiting_for_can_send_now = 0;
3638         uint8_t event[2] = { HCI_EVENT_SCO_CAN_SEND_NOW, 0 };
3639         hci_dump_packet(HCI_EVENT_PACKET, 1, event, sizeof(event));
3640         hci_stack->sco_packet_handler(HCI_EVENT_PACKET, 0, event, sizeof(event));
3641     }
3642 }
3643 
3644 // parsing end emitting has been merged to reduce code size
3645 static void gap_inquiry_explode(uint8_t * packet){
3646     uint8_t event[15+GAP_INQUIRY_MAX_NAME_LEN];
3647 
3648     uint8_t * eir_data;
3649     ad_context_t context;
3650     const uint8_t * name;
3651     uint8_t         name_len;
3652 
3653     int event_type = hci_event_packet_get_type(packet);
3654     int num_reserved_fields = event_type == HCI_EVENT_INQUIRY_RESULT ? 2 : 1;    // 2 for old event, 1 otherwise
3655     int num_responses       = hci_event_inquiry_result_get_num_responses(packet);
3656 
3657     // event[1] is set at the end
3658     int i;
3659     for (i=0; i<num_responses;i++){
3660         memset(event, 0, sizeof(event));
3661         event[0] = GAP_EVENT_INQUIRY_RESULT;
3662         uint8_t event_size = 18;    // if name is not set by EIR
3663 
3664         memcpy(&event[2],  &packet[3 +                                             i*6], 6); // bd_addr
3665         event[8] =          packet[3 + num_responses*(6)                         + i*1];     // page_scan_repetition_mode
3666         memcpy(&event[9],  &packet[3 + num_responses*(6+1+num_reserved_fields)   + i*3], 3); // class of device
3667         memcpy(&event[12], &packet[3 + num_responses*(6+1+num_reserved_fields+3) + i*2], 2); // clock offset
3668 
3669         switch (event_type){
3670             case HCI_EVENT_INQUIRY_RESULT:
3671                 // 14,15,16,17 = 0, size 18
3672                 break;
3673             case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
3674                 event[14] = 1;
3675                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
3676                 // 16,17 = 0, size 18
3677                 break;
3678             case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE:
3679                 event[14] = 1;
3680                 event[15] = packet [3 + num_responses*(6+1+num_reserved_fields+3+2) + i*1]; // rssi
3681                 // for EIR packets, there is only one reponse in it
3682                 eir_data = &packet[3 + (6+1+num_reserved_fields+3+2+1)];
3683                 name = NULL;
3684                 // EIR data is 240 bytes in EIR event
3685                 for (ad_iterator_init(&context, 240, eir_data) ; ad_iterator_has_more(&context) ; ad_iterator_next(&context)){
3686                     uint8_t data_type    = ad_iterator_get_data_type(&context);
3687                     uint8_t data_size    = ad_iterator_get_data_len(&context);
3688                     const uint8_t * data = ad_iterator_get_data(&context);
3689                     // Prefer Complete Local Name over Shortend Local Name
3690                     switch (data_type){
3691                         case BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME:
3692                             if (name) continue;
3693                             /* explicit fall-through */
3694                         case BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME:
3695                             name = data;
3696                             name_len = data_size;
3697                             break;
3698                         default:
3699                             break;
3700                     }
3701                 }
3702                 if (name){
3703                     event[16] = 1;
3704                     // truncate name if needed
3705                     int len = btstack_min(name_len, GAP_INQUIRY_MAX_NAME_LEN);
3706                     event[17] = len;
3707                     memcpy(&event[18], name, len);
3708                     event_size += len;
3709                 }
3710                 break;
3711         }
3712         event[1] = event_size - 2;
3713         hci_emit_event(event, event_size, 1);
3714     }
3715 }
3716 #endif
3717 
3718 void hci_emit_state(void){
3719     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
3720     uint8_t event[3];
3721     event[0] = BTSTACK_EVENT_STATE;
3722     event[1] = sizeof(event) - 2;
3723     event[2] = hci_stack->state;
3724     hci_emit_event(event, sizeof(event), 1);
3725 }
3726 
3727 #ifdef ENABLE_CLASSIC
3728 static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3729     uint8_t event[13];
3730     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
3731     event[1] = sizeof(event) - 2;
3732     event[2] = status;
3733     little_endian_store_16(event, 3, con_handle);
3734     reverse_bd_addr(address, &event[5]);
3735     event[11] = 1; // ACL connection
3736     event[12] = 0; // encryption disabled
3737     hci_emit_event(event, sizeof(event), 1);
3738 }
3739 static void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
3740     if (disable_l2cap_timeouts) return;
3741     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
3742     uint8_t event[4];
3743     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
3744     event[1] = sizeof(event) - 2;
3745     little_endian_store_16(event, 2, conn->con_handle);
3746     hci_emit_event(event, sizeof(event), 1);
3747 }
3748 #endif
3749 
3750 #ifdef ENABLE_BLE
3751 #ifdef ENABLE_LE_CENTRAL
3752 static void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t address, hci_con_handle_t con_handle, uint8_t status){
3753     uint8_t event[21];
3754     event[0] = HCI_EVENT_LE_META;
3755     event[1] = sizeof(event) - 2;
3756     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
3757     event[3] = status;
3758     little_endian_store_16(event, 4, con_handle);
3759     event[6] = 0; // TODO: role
3760     event[7] = address_type;
3761     reverse_bd_addr(address, &event[8]);
3762     little_endian_store_16(event, 14, 0); // interval
3763     little_endian_store_16(event, 16, 0); // latency
3764     little_endian_store_16(event, 18, 0); // supervision timeout
3765     event[20] = 0; // master clock accuracy
3766     hci_emit_event(event, sizeof(event), 1);
3767 }
3768 #endif
3769 #endif
3770 
3771 static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason){
3772     uint8_t event[6];
3773     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
3774     event[1] = sizeof(event) - 2;
3775     event[2] = 0; // status = OK
3776     little_endian_store_16(event, 3, con_handle);
3777     event[5] = reason;
3778     hci_emit_event(event, sizeof(event), 1);
3779 }
3780 
3781 static void hci_emit_nr_connections_changed(void){
3782     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
3783     uint8_t event[3];
3784     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
3785     event[1] = sizeof(event) - 2;
3786     event[2] = nr_hci_connections();
3787     hci_emit_event(event, sizeof(event), 1);
3788 }
3789 
3790 static void hci_emit_hci_open_failed(void){
3791     log_info("BTSTACK_EVENT_POWERON_FAILED");
3792     uint8_t event[2];
3793     event[0] = BTSTACK_EVENT_POWERON_FAILED;
3794     event[1] = sizeof(event) - 2;
3795     hci_emit_event(event, sizeof(event), 1);
3796 }
3797 
3798 static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
3799     log_info("hci_emit_dedicated_bonding_result %u ", status);
3800     uint8_t event[9];
3801     int pos = 0;
3802     event[pos++] = GAP_EVENT_DEDICATED_BONDING_COMPLETED;
3803     event[pos++] = sizeof(event) - 2;
3804     event[pos++] = status;
3805     reverse_bd_addr(address, &event[pos]);
3806     hci_emit_event(event, sizeof(event), 1);
3807 }
3808 
3809 
3810 #ifdef ENABLE_CLASSIC
3811 
3812 static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
3813     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
3814     uint8_t event[5];
3815     int pos = 0;
3816     event[pos++] = GAP_EVENT_SECURITY_LEVEL;
3817     event[pos++] = sizeof(event) - 2;
3818     little_endian_store_16(event, 2, con_handle);
3819     pos += 2;
3820     event[pos++] = level;
3821     hci_emit_event(event, sizeof(event), 1);
3822 }
3823 
3824 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
3825     if (!connection) return LEVEL_0;
3826     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
3827     return gap_security_level_for_link_key_type(connection->link_key_type);
3828 }
3829 
3830 static void hci_emit_discoverable_enabled(uint8_t enabled){
3831     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
3832     uint8_t event[3];
3833     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
3834     event[1] = sizeof(event) - 2;
3835     event[2] = enabled;
3836     hci_emit_event(event, sizeof(event), 1);
3837 }
3838 
3839 #ifdef ENABLE_CLASSIC
3840 // query if remote side supports eSCO
3841 int hci_remote_esco_supported(hci_con_handle_t con_handle){
3842     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3843     if (!connection) return 0;
3844     return connection->remote_supported_feature_eSCO;
3845 }
3846 
3847 // query if remote side supports SSP
3848 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
3849     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3850     if (!connection) return 0;
3851     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
3852 }
3853 
3854 int gap_ssp_supported_on_both_sides(hci_con_handle_t handle){
3855     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
3856 }
3857 #endif
3858 
3859 // GAP API
3860 /**
3861  * @bbrief enable/disable bonding. default is enabled
3862  * @praram enabled
3863  */
3864 void gap_set_bondable_mode(int enable){
3865     hci_stack->bondable = enable ? 1 : 0;
3866 }
3867 /**
3868  * @brief Get bondable mode.
3869  * @return 1 if bondable
3870  */
3871 int gap_get_bondable_mode(void){
3872     return hci_stack->bondable;
3873 }
3874 
3875 /**
3876  * @brief map link keys to security levels
3877  */
3878 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
3879     switch (link_key_type){
3880         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
3881             return LEVEL_4;
3882         case COMBINATION_KEY:
3883         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
3884             return LEVEL_3;
3885         default:
3886             return LEVEL_2;
3887     }
3888 }
3889 
3890 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
3891     log_info("gap_mitm_protection_required_for_security_level %u", level);
3892     return level > LEVEL_2;
3893 }
3894 
3895 /**
3896  * @brief get current security level
3897  */
3898 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
3899     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3900     if (!connection) return LEVEL_0;
3901     return gap_security_level_for_connection(connection);
3902 }
3903 
3904 /**
3905  * @brief request connection to device to
3906  * @result GAP_AUTHENTICATION_RESULT
3907  */
3908 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
3909     hci_connection_t * connection = hci_connection_for_handle(con_handle);
3910     if (!connection){
3911         hci_emit_security_level(con_handle, LEVEL_0);
3912         return;
3913     }
3914     gap_security_level_t current_level = gap_security_level(con_handle);
3915     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
3916     if (current_level >= requested_level){
3917         hci_emit_security_level(con_handle, current_level);
3918         return;
3919     }
3920 
3921     connection->requested_security_level = requested_level;
3922 
3923 #if 0
3924     // sending encryption request without a link key results in an error.
3925     // TODO: figure out how to use it properly
3926 
3927     // would enabling ecnryption suffice (>= LEVEL_2)?
3928     if (hci_stack->link_key_db){
3929         link_key_type_t link_key_type;
3930         link_key_t      link_key;
3931         if (hci_stack->link_key_db->get_link_key( &connection->address, &link_key, &link_key_type)){
3932             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
3933                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
3934                 return;
3935             }
3936         }
3937     }
3938 #endif
3939 
3940     // try to authenticate connection
3941     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
3942     hci_run();
3943 }
3944 
3945 /**
3946  * @brief start dedicated bonding with device. disconnect after bonding
3947  * @param device
3948  * @param request MITM protection
3949  * @result GAP_DEDICATED_BONDING_COMPLETE
3950  */
3951 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
3952 
3953     // create connection state machine
3954     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
3955 
3956     if (!connection){
3957         return BTSTACK_MEMORY_ALLOC_FAILED;
3958     }
3959 
3960     // delete linkn key
3961     gap_drop_link_key_for_bd_addr(device);
3962 
3963     // configure LEVEL_2/3, dedicated bonding
3964     connection->state = SEND_CREATE_CONNECTION;
3965     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
3966     log_info("gap_dedicated_bonding, mitm %d -> level %u", mitm_protection_required, connection->requested_security_level);
3967     connection->bonding_flags = BONDING_DEDICATED;
3968 
3969     // wait for GAP Security Result and send GAP Dedicated Bonding complete
3970 
3971     // handle: connnection failure (connection complete != ok)
3972     // handle: authentication failure
3973     // handle: disconnect on done
3974 
3975     hci_run();
3976 
3977     return 0;
3978 }
3979 #endif
3980 
3981 void gap_set_local_name(const char * local_name){
3982     hci_stack->local_name = local_name;
3983 }
3984 
3985 
3986 #ifdef ENABLE_BLE
3987 
3988 #ifdef ENABLE_LE_CENTRAL
3989 void gap_start_scan(void){
3990     if (hci_stack->le_scanning_state == LE_SCANNING) return;
3991     hci_stack->le_scanning_state = LE_START_SCAN;
3992     hci_run();
3993 }
3994 
3995 void gap_stop_scan(void){
3996     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return;
3997     hci_stack->le_scanning_state = LE_STOP_SCAN;
3998     hci_run();
3999 }
4000 
4001 void gap_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
4002     hci_stack->le_scan_type     = scan_type;
4003     hci_stack->le_scan_interval = scan_interval;
4004     hci_stack->le_scan_window   = scan_window;
4005     hci_run();
4006 }
4007 
4008 uint8_t gap_connect(bd_addr_t addr, bd_addr_type_t addr_type){
4009     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
4010     if (!conn){
4011         log_info("gap_connect: no connection exists yet, creating context");
4012         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
4013         if (!conn){
4014             // notify client that alloc failed
4015             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
4016             log_info("gap_connect: failed to alloc hci_connection_t");
4017             return GATT_CLIENT_NOT_CONNECTED; // don't sent packet to controller
4018         }
4019         conn->state = SEND_CREATE_CONNECTION;
4020         log_info("gap_connect: send create connection next");
4021         hci_run();
4022         return 0;
4023     }
4024 
4025     if (!hci_is_le_connection(conn) ||
4026         conn->state == SEND_CREATE_CONNECTION ||
4027         conn->state == SENT_CREATE_CONNECTION) {
4028         hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
4029         log_error("gap_connect: classic connection or connect is already being created");
4030         return GATT_CLIENT_IN_WRONG_STATE;
4031     }
4032 
4033     log_info("gap_connect: context exists with state %u", conn->state);
4034     hci_emit_le_connection_complete(conn->address_type, conn->address, conn->con_handle, 0);
4035     hci_run();
4036     return 0;
4037 }
4038 
4039 // @assumption: only a single outgoing LE Connection exists
4040 static hci_connection_t * gap_get_outgoing_connection(void){
4041     btstack_linked_item_t *it;
4042     for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
4043         hci_connection_t * conn = (hci_connection_t *) it;
4044         if (!hci_is_le_connection(conn)) continue;
4045         switch (conn->state){
4046             case SEND_CREATE_CONNECTION:
4047             case SENT_CREATE_CONNECTION:
4048             case SENT_CANCEL_CONNECTION:
4049                 return conn;
4050             default:
4051                 break;
4052         };
4053     }
4054     return NULL;
4055 }
4056 
4057 uint8_t gap_connect_cancel(void){
4058     hci_connection_t * conn = gap_get_outgoing_connection();
4059     if (!conn) return 0;
4060     switch (conn->state){
4061         case SEND_CREATE_CONNECTION:
4062             // skip sending create connection and emit event instead
4063             hci_emit_le_connection_complete(conn->address_type, conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
4064             btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
4065             btstack_memory_hci_connection_free( conn );
4066             break;
4067         case SENT_CREATE_CONNECTION:
4068             // request to send cancel connection
4069             conn->state = SEND_CANCEL_CONNECTION;
4070             hci_run();
4071             break;
4072         default:
4073             break;
4074     }
4075     return 0;
4076 }
4077 #endif
4078 
4079 #ifdef ENABLE_LE_CENTRAL
4080 /**
4081  * @brief Set connection parameters for outgoing connections
4082  * @param conn_scan_interval (unit: 0.625 msec), default: 60 ms
4083  * @param conn_scan_window (unit: 0.625 msec), default: 30 ms
4084  * @param conn_interval_min (unit: 1.25ms), default: 10 ms
4085  * @param conn_interval_max (unit: 1.25ms), default: 30 ms
4086  * @param conn_latency, default: 4
4087  * @param supervision_timeout (unit: 10ms), default: 720 ms
4088  * @param min_ce_length (unit: 0.625ms), default: 10 ms
4089  * @param max_ce_length (unit: 0.625ms), default: 30 ms
4090  */
4091 
4092 void gap_set_connection_parameters(uint16_t conn_scan_interval, uint16_t conn_scan_window,
4093     uint16_t conn_interval_min, uint16_t conn_interval_max, uint16_t conn_latency,
4094     uint16_t supervision_timeout, uint16_t min_ce_length, uint16_t max_ce_length){
4095     hci_stack->le_connection_scan_interval = conn_scan_interval;
4096     hci_stack->le_connection_scan_window = conn_scan_window;
4097     hci_stack->le_connection_interval_min = conn_interval_min;
4098     hci_stack->le_connection_interval_max = conn_interval_max;
4099     hci_stack->le_connection_latency = conn_latency;
4100     hci_stack->le_supervision_timeout = supervision_timeout;
4101     hci_stack->le_minimum_ce_length = min_ce_length;
4102     hci_stack->le_maximum_ce_length = max_ce_length;
4103 }
4104 #endif
4105 
4106 /**
4107  * @brief Updates the connection parameters for a given LE connection
4108  * @param handle
4109  * @param conn_interval_min (unit: 1.25ms)
4110  * @param conn_interval_max (unit: 1.25ms)
4111  * @param conn_latency
4112  * @param supervision_timeout (unit: 10ms)
4113  * @returns 0 if ok
4114  */
4115 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4116     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4117     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4118     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4119     connection->le_conn_interval_min = conn_interval_min;
4120     connection->le_conn_interval_max = conn_interval_max;
4121     connection->le_conn_latency = conn_latency;
4122     connection->le_supervision_timeout = supervision_timeout;
4123     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS;
4124     hci_run();
4125     return 0;
4126 }
4127 
4128 /**
4129  * @brief Request an update of the connection parameter for a given LE connection
4130  * @param handle
4131  * @param conn_interval_min (unit: 1.25ms)
4132  * @param conn_interval_max (unit: 1.25ms)
4133  * @param conn_latency
4134  * @param supervision_timeout (unit: 10ms)
4135  * @returns 0 if ok
4136  */
4137 int gap_request_connection_parameter_update(hci_con_handle_t con_handle, uint16_t conn_interval_min,
4138     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
4139     hci_connection_t * connection = hci_connection_for_handle(con_handle);
4140     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
4141     connection->le_conn_interval_min = conn_interval_min;
4142     connection->le_conn_interval_max = conn_interval_max;
4143     connection->le_conn_latency = conn_latency;
4144     connection->le_supervision_timeout = supervision_timeout;
4145     connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_SEND_REQUEST;
4146     hci_run();
4147     return 0;
4148 }
4149 
4150 #ifdef ENABLE_LE_PERIPHERAL
4151 
4152 static void gap_advertisments_changed(void){
4153     // disable advertisements before updating adv, scan data, or adv params
4154     if (hci_stack->le_advertisements_active){
4155         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE | LE_ADVERTISEMENT_TASKS_ENABLE;
4156     }
4157     hci_run();
4158 }
4159 
4160 /**
4161  * @brief Set Advertisement Data
4162  * @param advertising_data_length
4163  * @param advertising_data (max 31 octets)
4164  * @note data is not copied, pointer has to stay valid
4165  */
4166 void gap_advertisements_set_data(uint8_t advertising_data_length, uint8_t * advertising_data){
4167     hci_stack->le_advertisements_data_len = advertising_data_length;
4168     hci_stack->le_advertisements_data = advertising_data;
4169     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_ADV_DATA;
4170     gap_advertisments_changed();
4171 }
4172 
4173 /**
4174  * @brief Set Scan Response Data
4175  * @param advertising_data_length
4176  * @param advertising_data (max 31 octets)
4177  * @note data is not copied, pointer has to stay valid
4178  */
4179 void gap_scan_response_set_data(uint8_t scan_response_data_length, uint8_t * scan_response_data){
4180     hci_stack->le_scan_response_data_len = scan_response_data_length;
4181     hci_stack->le_scan_response_data = scan_response_data;
4182     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_SCAN_DATA;
4183     gap_advertisments_changed();
4184 }
4185 
4186 /**
4187  * @brief Set Advertisement Parameters
4188  * @param adv_int_min
4189  * @param adv_int_max
4190  * @param adv_type
4191  * @param direct_address_type
4192  * @param direct_address
4193  * @param channel_map
4194  * @param filter_policy
4195  *
4196  * @note internal use. use gap_advertisements_set_params from gap_le.h instead.
4197  */
4198  void hci_le_advertisements_set_params(uint16_t adv_int_min, uint16_t adv_int_max, uint8_t adv_type,
4199     uint8_t direct_address_typ, bd_addr_t direct_address,
4200     uint8_t channel_map, uint8_t filter_policy) {
4201 
4202     hci_stack->le_advertisements_interval_min = adv_int_min;
4203     hci_stack->le_advertisements_interval_max = adv_int_max;
4204     hci_stack->le_advertisements_type = adv_type;
4205     hci_stack->le_advertisements_direct_address_type = direct_address_typ;
4206     hci_stack->le_advertisements_channel_map = channel_map;
4207     hci_stack->le_advertisements_filter_policy = filter_policy;
4208     memcpy(hci_stack->le_advertisements_direct_address, direct_address, 6);
4209 
4210     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4211     gap_advertisments_changed();
4212  }
4213 
4214 /**
4215  * @brief Enable/Disable Advertisements
4216  * @param enabled
4217  */
4218 void gap_advertisements_enable(int enabled){
4219     hci_stack->le_advertisements_enabled = enabled;
4220     if (enabled && !hci_stack->le_advertisements_active){
4221         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_ENABLE;
4222     }
4223     if (!enabled && hci_stack->le_advertisements_active){
4224         hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_DISABLE;
4225     }
4226     hci_run();
4227 }
4228 
4229 #endif
4230 
4231 void hci_le_set_own_address_type(uint8_t own_address_type){
4232     log_info("hci_le_set_own_address_type: old %u, new %u", hci_stack->le_own_addr_type, own_address_type);
4233     if (own_address_type == hci_stack->le_own_addr_type) return;
4234     hci_stack->le_own_addr_type = own_address_type;
4235 
4236 #ifdef ENABLE_LE_PERIPHERAL
4237     // update advertisement parameters, too
4238     hci_stack->le_advertisements_todo |= LE_ADVERTISEMENT_TASKS_SET_PARAMS;
4239     gap_advertisments_changed();
4240 #endif
4241 #ifdef ENABLE_LE_CENTRAL
4242     // note: we don't update scan parameters or modify ongoing connection attempts
4243 #endif
4244 }
4245 
4246 #endif
4247 
4248 uint8_t gap_disconnect(hci_con_handle_t handle){
4249     hci_connection_t * conn = hci_connection_for_handle(handle);
4250     if (!conn){
4251         hci_emit_disconnection_complete(handle, 0);
4252         return 0;
4253     }
4254     conn->state = SEND_DISCONNECT;
4255     hci_run();
4256     return 0;
4257 }
4258 
4259 /**
4260  * @brief Get connection type
4261  * @param con_handle
4262  * @result connection_type
4263  */
4264 gap_connection_type_t gap_get_connection_type(hci_con_handle_t connection_handle){
4265     hci_connection_t * conn = hci_connection_for_handle(connection_handle);
4266     if (!conn) return GAP_CONNECTION_INVALID;
4267     switch (conn->address_type){
4268         case BD_ADDR_TYPE_LE_PUBLIC:
4269         case BD_ADDR_TYPE_LE_RANDOM:
4270             return GAP_CONNECTION_LE;
4271         case BD_ADDR_TYPE_SCO:
4272             return GAP_CONNECTION_SCO;
4273         case BD_ADDR_TYPE_CLASSIC:
4274             return GAP_CONNECTION_ACL;
4275         default:
4276             return GAP_CONNECTION_INVALID;
4277     }
4278 }
4279 
4280 #ifdef ENABLE_BLE
4281 
4282 #ifdef ENABLE_LE_CENTRAL
4283 /**
4284  * @brief Auto Connection Establishment - Start Connecting to device
4285  * @param address_typ
4286  * @param address
4287  * @returns 0 if ok
4288  */
4289 int gap_auto_connection_start(bd_addr_type_t address_type, bd_addr_t address){
4290     // check capacity
4291     int num_entries = btstack_linked_list_count(&hci_stack->le_whitelist);
4292     if (num_entries >= hci_stack->le_whitelist_capacity) return ERROR_CODE_MEMORY_CAPACITY_EXCEEDED;
4293     whitelist_entry_t * entry = btstack_memory_whitelist_entry_get();
4294     if (!entry) return BTSTACK_MEMORY_ALLOC_FAILED;
4295     entry->address_type = address_type;
4296     memcpy(entry->address, address, 6);
4297     entry->state = LE_WHITELIST_ADD_TO_CONTROLLER;
4298     btstack_linked_list_add(&hci_stack->le_whitelist, (btstack_linked_item_t*) entry);
4299     hci_run();
4300     return 0;
4301 }
4302 
4303 static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address){
4304     btstack_linked_list_iterator_t it;
4305     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4306     while (btstack_linked_list_iterator_has_next(&it)){
4307         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4308         if (entry->address_type != address_type) continue;
4309         if (memcmp(entry->address, address, 6) != 0) continue;
4310         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4311             // remove from controller if already present
4312             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4313             continue;
4314         }
4315         // direclty remove entry from whitelist
4316         btstack_linked_list_iterator_remove(&it);
4317         btstack_memory_whitelist_entry_free(entry);
4318     }
4319 }
4320 
4321 /**
4322  * @brief Auto Connection Establishment - Stop Connecting to device
4323  * @param address_typ
4324  * @param address
4325  * @returns 0 if ok
4326  */
4327 int gap_auto_connection_stop(bd_addr_type_t address_type, bd_addr_t address){
4328     hci_remove_from_whitelist(address_type, address);
4329     hci_run();
4330     return 0;
4331 }
4332 
4333 /**
4334  * @brief Auto Connection Establishment - Stop everything
4335  * @note  Convenience function to stop all active auto connection attempts
4336  */
4337 void gap_auto_connection_stop_all(void){
4338     btstack_linked_list_iterator_t it;
4339     btstack_linked_list_iterator_init(&it, &hci_stack->le_whitelist);
4340     while (btstack_linked_list_iterator_has_next(&it)){
4341         whitelist_entry_t * entry = (whitelist_entry_t*) btstack_linked_list_iterator_next(&it);
4342         if (entry->state & LE_WHITELIST_ON_CONTROLLER){
4343             // remove from controller if already present
4344             entry->state |= LE_WHITELIST_REMOVE_FROM_CONTROLLER;
4345             continue;
4346         }
4347         // directly remove entry from whitelist
4348         btstack_linked_list_iterator_remove(&it);
4349         btstack_memory_whitelist_entry_free(entry);
4350     }
4351     hci_run();
4352 }
4353 #endif
4354 #endif
4355 
4356 #ifdef ENABLE_CLASSIC
4357 /**
4358  * @brief Set Extended Inquiry Response data
4359  * @param eir_data size 240 bytes, is not copied make sure memory is accessible during stack startup
4360  * @note has to be done before stack starts up
4361  */
4362 void gap_set_extended_inquiry_response(const uint8_t * data){
4363     hci_stack->eir_data = data;
4364 }
4365 
4366 /**
4367  * @brief Start GAP Classic Inquiry
4368  * @param duration in 1.28s units
4369  * @return 0 if ok
4370  * @events: GAP_EVENT_INQUIRY_RESULT, GAP_EVENT_INQUIRY_COMPLETE
4371  */
4372 int gap_inquiry_start(uint8_t duration_in_1280ms_units){
4373     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4374     if (duration_in_1280ms_units < GAP_INQUIRY_DURATION_MIN || duration_in_1280ms_units > GAP_INQUIRY_DURATION_MAX){
4375         return ERROR_CODE_INVALID_HCI_COMMAND_PARAMETERS;
4376     }
4377     hci_stack->inquiry_state = duration_in_1280ms_units;
4378     hci_run();
4379     return 0;
4380 }
4381 
4382 /**
4383  * @brief Stop GAP Classic Inquiry
4384  * @returns 0 if ok
4385  */
4386 int gap_inquiry_stop(void){
4387     if (hci_stack->inquiry_state >= GAP_INQUIRY_DURATION_MIN || hci_stack->inquiry_state <= GAP_INQUIRY_DURATION_MAX) {
4388         // emit inquiry complete event, before it even started
4389         uint8_t event[] = { GAP_EVENT_INQUIRY_COMPLETE, 1, 0};
4390         hci_emit_event(event, sizeof(event), 1);
4391         return 0;
4392     }
4393     if (hci_stack->inquiry_state != GAP_INQUIRY_STATE_ACTIVE) return ERROR_CODE_COMMAND_DISALLOWED;
4394     hci_stack->inquiry_state = GAP_INQUIRY_STATE_W2_CANCEL;
4395     hci_run();
4396     return 0;
4397 }
4398 
4399 
4400 /**
4401  * @brief Remote Name Request
4402  * @param addr
4403  * @param page_scan_repetition_mode
4404  * @param clock_offset only used when bit 15 is set
4405  * @events: HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
4406  */
4407 int gap_remote_name_request(bd_addr_t addr, uint8_t page_scan_repetition_mode, uint16_t clock_offset){
4408     if (hci_stack->remote_name_state != GAP_REMOTE_NAME_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4409     memcpy(hci_stack->remote_name_addr, addr, 6);
4410     hci_stack->remote_name_page_scan_repetition_mode = page_scan_repetition_mode;
4411     hci_stack->remote_name_clock_offset = clock_offset;
4412     hci_stack->remote_name_state = GAP_REMOTE_NAME_STATE_W2_SEND;
4413     hci_run();
4414     return 0;
4415 }
4416 
4417 static int gap_pairing_set_state_and_run(bd_addr_t addr, uint8_t state){
4418     hci_stack->gap_pairing_state = state;
4419     memcpy(hci_stack->gap_pairing_addr, addr, 6);
4420     hci_run();
4421     return 0;
4422 }
4423 
4424 /**
4425  * @brief Legacy Pairing Pin Code Response
4426  * @param addr
4427  * @param pin
4428  * @return 0 if ok
4429  */
4430 int gap_pin_code_response(bd_addr_t addr, const char * pin){
4431     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4432     hci_stack->gap_pairing_pin = pin;
4433     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN);
4434 }
4435 
4436 /**
4437  * @brief Abort Legacy Pairing
4438  * @param addr
4439  * @param pin
4440  * @return 0 if ok
4441  */
4442 int gap_pin_code_negative(bd_addr_t addr){
4443     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4444     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PIN_NEGATIVE);
4445 }
4446 
4447 /**
4448  * @brief SSP Passkey Response
4449  * @param addr
4450  * @param passkey
4451  * @return 0 if ok
4452  */
4453 int gap_ssp_passkey_response(bd_addr_t addr, uint32_t passkey){
4454     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4455     hci_stack->gap_pairing_passkey = passkey;
4456     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY);
4457 }
4458 
4459 /**
4460  * @brief Abort SSP Passkey Entry/Pairing
4461  * @param addr
4462  * @param pin
4463  * @return 0 if ok
4464  */
4465 int gap_ssp_passkey_negative(bd_addr_t addr){
4466     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4467     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE);
4468 }
4469 
4470 /**
4471  * @brief Accept SSP Numeric Comparison
4472  * @param addr
4473  * @param passkey
4474  * @return 0 if ok
4475  */
4476 int gap_ssp_confirmation_response(bd_addr_t addr){
4477     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4478     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION);
4479 }
4480 
4481 /**
4482  * @brief Abort SSP Numeric Comparison/Pairing
4483  * @param addr
4484  * @param pin
4485  * @return 0 if ok
4486  */
4487 int gap_ssp_confirmation_negative(bd_addr_t addr){
4488     if (hci_stack->gap_pairing_state != GAP_INQUIRY_STATE_IDLE) return ERROR_CODE_COMMAND_DISALLOWED;
4489     return gap_pairing_set_state_and_run(addr, GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE);
4490 }
4491 
4492 /**
4493  * @brief Set inquiry mode: standard, with RSSI, with RSSI + Extended Inquiry Results. Has to be called before power on.
4494  * @param inquiry_mode see bluetooth_defines.h
4495  */
4496 void hci_set_inquiry_mode(inquiry_mode_t mode){
4497     hci_stack->inquiry_mode = mode;
4498 }
4499 
4500 /**
4501  * @brief Configure Voice Setting for use with SCO data in HSP/HFP
4502  */
4503 void hci_set_sco_voice_setting(uint16_t voice_setting){
4504     hci_stack->sco_voice_setting = voice_setting;
4505 }
4506 
4507 /**
4508  * @brief Get SCO Voice Setting
4509  * @return current voice setting
4510  */
4511 uint16_t hci_get_sco_voice_setting(void){
4512     return hci_stack->sco_voice_setting;
4513 }
4514 
4515 /** @brief Get SCO packet length for current SCO Voice setting
4516  *  @note  Using SCO packets of the exact length is required for USB transfer
4517  *  @return Length of SCO packets in bytes (not audio frames)
4518  */
4519 int hci_get_sco_packet_length(void){
4520     // see Core Spec for H2 USB Transfer.
4521     if (hci_stack->sco_voice_setting & 0x0020) return 51;
4522     return 27;
4523 }
4524 
4525 /**
4526 * @brief Sets the master/slave policy
4527 * @param policy (0: attempt to become master, 1: let connecting device decide)
4528 */
4529 void hci_set_master_slave_policy(uint8_t policy){
4530     hci_stack->master_slave_policy = policy;
4531 }
4532 
4533 #endif
4534 
4535 HCI_STATE hci_get_state(void){
4536     return hci_stack->state;
4537 }
4538 
4539 
4540 /**
4541  * @brief Set callback for Bluetooth Hardware Error
4542  */
4543 void hci_set_hardware_error_callback(void (*fn)(uint8_t error)){
4544     hci_stack->hardware_error_callback = fn;
4545 }
4546 
4547 void hci_disconnect_all(void){
4548     btstack_linked_list_iterator_t it;
4549     btstack_linked_list_iterator_init(&it, &hci_stack->connections);
4550     while (btstack_linked_list_iterator_has_next(&it)){
4551         hci_connection_t * con = (hci_connection_t*) btstack_linked_list_iterator_next(&it);
4552         if (con->state == SENT_DISCONNECT) continue;
4553         con->state = SEND_DISCONNECT;
4554     }
4555     hci_run();
4556 }
4557 
4558 uint16_t hci_get_manufacturer(void){
4559     return hci_stack->manufacturer;
4560 }
4561 
4562 static sm_connection_t * sm_get_connection_for_handle(hci_con_handle_t con_handle){
4563     hci_connection_t * hci_con = hci_connection_for_handle(con_handle);
4564     if (!hci_con) return NULL;
4565     return &hci_con->sm_connection;
4566 }
4567 
4568 #ifdef ENABLE_BLE
4569 
4570 // extracted from sm.c to allow enabling of l2cap le data channels without adding sm.c to the build
4571 // without sm.c default values from create_connection_for_bd_addr_and_type() resulg in non-encrypted, not-authenticated
4572 
4573 int gap_encryption_key_size(hci_con_handle_t con_handle){
4574     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4575     if (!sm_conn) return 0;     // wrong connection
4576     if (!sm_conn->sm_connection_encrypted) return 0;
4577     return sm_conn->sm_actual_encryption_key_size;
4578 }
4579 
4580 int gap_authenticated(hci_con_handle_t con_handle){
4581     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4582     if (!sm_conn) return 0;     // wrong connection
4583     if (!sm_conn->sm_connection_encrypted) return 0; // unencrypted connection cannot be authenticated
4584     return sm_conn->sm_connection_authenticated;
4585 }
4586 
4587 authorization_state_t gap_authorization_state(hci_con_handle_t con_handle){
4588     sm_connection_t * sm_conn = sm_get_connection_for_handle(con_handle);
4589     if (!sm_conn) return AUTHORIZATION_UNKNOWN;     // wrong connection
4590     if (!sm_conn->sm_connection_encrypted)               return AUTHORIZATION_UNKNOWN; // unencrypted connection cannot be authorized
4591     if (!sm_conn->sm_connection_authenticated)           return AUTHORIZATION_UNKNOWN; // unauthenticatd connection cannot be authorized
4592     return sm_conn->sm_connection_authorization_state;
4593 }
4594 #endif
4595