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