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