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