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