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