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