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