xref: /btstack/src/hci.c (revision 44d0e3d5563b48ea294b42aafafb76d4ebb7e379)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 /*
39  *  hci.c
40  *
41  *  Created by Matthias Ringwald on 4/29/09.
42  *
43  */
44 
45 #include "btstack-config.h"
46 
47 #include "hci.h"
48 #include "gap.h"
49 
50 #include <stdarg.h>
51 #include <string.h>
52 #include <stdio.h>
53 
54 #ifndef EMBEDDED
55 #ifdef _WIN32
56 #include "Winsock2.h"
57 #else
58 #include <unistd.h> // gethostbyname
59 #endif
60 #include <btstack/version.h>
61 #endif
62 
63 #include "btstack_memory.h"
64 #include "debug.h"
65 #include "hci_dump.h"
66 
67 #include <btstack/linked_list.h>
68 #include <btstack/hci_cmds.h>
69 
70 #define HCI_CONNECTION_TIMEOUT_MS 10000
71 
72 #define HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP 11
73 
74 #ifdef USE_BLUETOOL
75 #include "../platforms/ios/src/bt_control_iphone.h"
76 #endif
77 
78 static void hci_update_scan_enable(void);
79 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
80 static void hci_connection_timeout_handler(timer_source_t *timer);
81 static void hci_connection_timestamp(hci_connection_t *connection);
82 static int  hci_power_control_on(void);
83 static void hci_power_control_off(void);
84 static void hci_state_reset();
85 
86 // the STACK is here
87 #ifndef HAVE_MALLOC
88 static hci_stack_t   hci_stack_static;
89 #endif
90 static hci_stack_t * hci_stack = NULL;
91 
92 // test helper
93 static uint8_t disable_l2cap_timeouts = 0;
94 
95 /**
96  * create connection for given address
97  *
98  * @return connection OR NULL, if no memory left
99  */
100 static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
101     log_info("create_connection_for_addr %s", bd_addr_to_str(addr));
102     hci_connection_t * conn = btstack_memory_hci_connection_get();
103     if (!conn) return NULL;
104     memset(conn, 0, sizeof(hci_connection_t));
105     BD_ADDR_COPY(conn->address, addr);
106     conn->address_type = addr_type;
107     conn->con_handle = 0xffff;
108     conn->authentication_flags = AUTH_FLAGS_NONE;
109     conn->bonding_flags = 0;
110     conn->requested_security_level = LEVEL_0;
111     linked_item_set_user(&conn->timeout.item, conn);
112     conn->timeout.process = hci_connection_timeout_handler;
113     hci_connection_timestamp(conn);
114     conn->acl_recombination_length = 0;
115     conn->acl_recombination_pos = 0;
116     conn->num_acl_packets_sent = 0;
117     conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
118     linked_list_add(&hci_stack->connections, (linked_item_t *) conn);
119     return conn;
120 }
121 
122 
123 /**
124  * get le connection parameter range
125 *
126  * @return le connection parameter range struct
127  */
128 le_connection_parameter_range_t gap_le_get_connection_parameter_range(){
129     return hci_stack->le_connection_parameter_range;
130 }
131 
132 /**
133  * set le connection parameter range
134  *
135  */
136 
137 void gap_le_set_connection_parameter_range(le_connection_parameter_range_t range){
138     hci_stack->le_connection_parameter_range.le_conn_interval_min = range.le_conn_interval_min;
139     hci_stack->le_connection_parameter_range.le_conn_interval_max = range.le_conn_interval_max;
140     hci_stack->le_connection_parameter_range.le_conn_interval_min = range.le_conn_latency_min;
141     hci_stack->le_connection_parameter_range.le_conn_interval_max = range.le_conn_latency_max;
142     hci_stack->le_connection_parameter_range.le_supervision_timeout_min = range.le_supervision_timeout_min;
143     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = range.le_supervision_timeout_max;
144 }
145 
146 /**
147  * get hci connections iterator
148  *
149  * @return hci connections iterator
150  */
151 
152 void hci_connections_get_iterator(linked_list_iterator_t *it){
153     linked_list_iterator_init(it, &hci_stack->connections);
154 }
155 
156 /**
157  * get connection for a given handle
158  *
159  * @return connection OR NULL, if not found
160  */
161 hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
162     linked_list_iterator_t it;
163     linked_list_iterator_init(&it, &hci_stack->connections);
164     while (linked_list_iterator_has_next(&it)){
165         hci_connection_t * item = (hci_connection_t *) linked_list_iterator_next(&it);
166         if ( item->con_handle == con_handle ) {
167             return item;
168         }
169     }
170     return NULL;
171 }
172 
173 /**
174  * get connection for given address
175  *
176  * @return connection OR NULL, if not found
177  */
178 hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t * addr, bd_addr_type_t addr_type){
179     linked_list_iterator_t it;
180     linked_list_iterator_init(&it, &hci_stack->connections);
181     while (linked_list_iterator_has_next(&it)){
182         hci_connection_t * connection = (hci_connection_t *) linked_list_iterator_next(&it);
183         if (connection->address_type != addr_type)  continue;
184         if (memcmp(addr, connection->address, 6) != 0) continue;
185         return connection;
186     }
187     return NULL;
188 }
189 
190 static void hci_connection_timeout_handler(timer_source_t *timer){
191     hci_connection_t * connection = (hci_connection_t *) linked_item_get_user(&timer->item);
192 #ifdef HAVE_TIME
193     struct timeval tv;
194     gettimeofday(&tv, NULL);
195     if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) {
196         // connections might be timed out
197         hci_emit_l2cap_check_timeout(connection);
198     }
199 #endif
200 #ifdef HAVE_TICK
201     if (embedded_get_ticks() > connection->timestamp + embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
202         // connections might be timed out
203         hci_emit_l2cap_check_timeout(connection);
204     }
205 #endif
206     run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS);
207     run_loop_add_timer(timer);
208 }
209 
210 static void hci_connection_timestamp(hci_connection_t *connection){
211 #ifdef HAVE_TIME
212     gettimeofday(&connection->timestamp, NULL);
213 #endif
214 #ifdef HAVE_TICK
215     connection->timestamp = embedded_get_ticks();
216 #endif
217 }
218 
219 
220 inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
221     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
222 }
223 
224 inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
225     conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
226 }
227 
228 
229 /**
230  * add authentication flags and reset timer
231  * @note: assumes classic connection
232  */
233 static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
234     bd_addr_t addr;
235     bt_flip_addr(addr, *(bd_addr_t *) bd_addr);
236     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
237     if (conn) {
238         connectionSetAuthenticationFlags(conn, flags);
239         hci_connection_timestamp(conn);
240     }
241 }
242 
243 int  hci_authentication_active_for_handle(hci_con_handle_t handle){
244     hci_connection_t * conn = hci_connection_for_handle(handle);
245     if (!conn) return 0;
246     if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
247     if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
248     return 0;
249 }
250 
251 void hci_drop_link_key_for_bd_addr(bd_addr_t *addr){
252     if (hci_stack->remote_device_db) {
253         hci_stack->remote_device_db->delete_link_key(addr);
254     }
255 }
256 
257 int hci_is_le_connection(hci_connection_t * connection){
258     return  connection->address_type == BD_ADDR_TYPE_LE_PUBLIC ||
259     connection->address_type == BD_ADDR_TYPE_LE_RANDOM;
260 }
261 
262 
263 /**
264  * count connections
265  */
266 static int nr_hci_connections(void){
267     int count = 0;
268     linked_item_t *it;
269     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next, count++);
270     return count;
271 }
272 
273 /**
274  * Dummy handler called by HCI
275  */
276 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
277 }
278 
279 uint8_t hci_number_outgoing_packets(hci_con_handle_t handle){
280     hci_connection_t * connection = hci_connection_for_handle(handle);
281     if (!connection) {
282         log_error("hci_number_outgoing_packets: connection for handle %u does not exist!", handle);
283         return 0;
284     }
285     return connection->num_acl_packets_sent;
286 }
287 
288 uint8_t hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
289 
290     int num_packets_sent_classic = 0;
291     int num_packets_sent_le = 0;
292 
293     bd_addr_type_t address_type = BD_ADDR_TYPE_UNKNOWN;
294 
295     linked_item_t *it;
296     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
297         hci_connection_t * connection = (hci_connection_t *) it;
298         if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
299             num_packets_sent_classic += connection->num_acl_packets_sent;
300         } else {
301             num_packets_sent_le += connection->num_acl_packets_sent;
302         }
303         // ignore connections that are not open, e.g., in state RECEIVED_DISCONNECTION_COMPLETE
304         if (connection->con_handle == con_handle && connection->state == OPEN){
305             address_type = connection->address_type;
306         }
307     }
308 
309     int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
310     int free_slots_le = 0;
311 
312     if (free_slots_classic < 0){
313         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);
314         return 0;
315     }
316 
317     if (hci_stack->le_acl_packets_total_num){
318         // if we have LE slots, they are used
319         free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
320         if (free_slots_le < 0){
321             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);
322             return 0;
323         }
324     } else {
325         // otherwise, classic slots are used for LE, too
326         free_slots_classic -= num_packets_sent_le;
327         if (free_slots_classic < 0){
328             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);
329             return 0;
330         }
331     }
332 
333     switch (address_type){
334         case BD_ADDR_TYPE_UNKNOWN:
335             log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
336             return 0;
337 
338         case BD_ADDR_TYPE_CLASSIC:
339             return free_slots_classic;
340 
341         default:
342            if (hci_stack->le_acl_packets_total_num){
343                return free_slots_le;
344            }
345            return free_slots_classic;
346     }
347 }
348 
349 int hci_number_free_sco_slots_for_handle(hci_con_handle_t handle){
350     // int num_sco_packets_sent = basic_num_sco_packets_sent;
351     // if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
352     //     log_info("hci_number_free_sco_slots_for_handle: outgoing packets (%u) > total packets ()", num_sco_packets_sent, hci_stack->sco_packets_total_num);
353     //     return 0;
354     // }
355     // return hci_stack->sco_packets_total_num - num_sco_packets_sent;
356     return 0;
357 }
358 
359 // new functions replacing hci_can_send_packet_now[_using_packet_buffer]
360 int hci_can_send_command_packet_now(void){
361     if (hci_stack->hci_packet_buffer_reserved) return 0;
362 
363     // check for async hci transport implementations
364     if (hci_stack->hci_transport->can_send_packet_now){
365         if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
366             return 0;
367         }
368     }
369 
370     return hci_stack->num_cmd_packets > 0;
371 }
372 
373 int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
374     // check for async hci transport implementations
375     if (hci_stack->hci_transport->can_send_packet_now){
376         if (!hci_stack->hci_transport->can_send_packet_now(HCI_ACL_DATA_PACKET)){
377             return 0;
378         }
379     }
380     return hci_number_free_acl_slots_for_handle(con_handle) > 0;
381 }
382 
383 int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
384     if (hci_stack->hci_packet_buffer_reserved) return 0;
385     return hci_can_send_prepared_acl_packet_now(con_handle);
386 }
387 
388 int hci_can_send_prepared_sco_packet_now(hci_con_handle_t con_handle){
389     if (hci_stack->hci_transport->can_send_packet_now){
390         if (!hci_stack->hci_transport->can_send_packet_now(HCI_SCO_DATA_PACKET)){
391             return 0;
392         }
393     }
394     return hci_number_free_sco_slots_for_handle(con_handle) > 0;
395 }
396 
397 int hci_can_send_sco_packet_now(hci_con_handle_t con_handle){
398     if (hci_stack->hci_packet_buffer_reserved) return 0;
399     return hci_can_send_prepared_sco_packet_now(con_handle);
400 }
401 
402 // used for internal checks in l2cap[-le].c
403 int hci_is_packet_buffer_reserved(void){
404     return hci_stack->hci_packet_buffer_reserved;
405 }
406 
407 // reserves outgoing packet buffer. @returns 1 if successful
408 int hci_reserve_packet_buffer(void){
409     if (hci_stack->hci_packet_buffer_reserved) {
410         log_error("hci_reserve_packet_buffer called but buffer already reserved");
411         return 0;
412     }
413     hci_stack->hci_packet_buffer_reserved = 1;
414     return 1;
415 }
416 
417 void hci_release_packet_buffer(void){
418     hci_stack->hci_packet_buffer_reserved = 0;
419 }
420 
421 // assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
422 int hci_transport_synchronous(void){
423     return hci_stack->hci_transport->can_send_packet_now == NULL;
424 }
425 
426 uint16_t hci_max_acl_le_data_packet_length(void){
427     return hci_stack->le_data_packets_length > 0 ? hci_stack->le_data_packets_length : hci_stack->acl_data_packet_length;
428 }
429 
430 static int hci_send_acl_packet_fragments(hci_connection_t *connection){
431 
432     // 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);
433 
434     // max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
435     uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
436     if (hci_is_le_connection(connection) && hci_stack->le_data_packets_length > 0){
437         max_acl_data_packet_length = hci_stack->le_data_packets_length;
438     }
439 
440     // testing: reduce buffer to minimum
441     // max_acl_data_packet_length = 52;
442 
443     int err;
444     // multiple packets could be send on a synchronous HCI transport
445     while (1){
446 
447         // get current data
448         const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4;
449         int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
450         int more_fragments = 0;
451 
452         // if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
453         if (current_acl_data_packet_length > max_acl_data_packet_length){
454             more_fragments = 1;
455             current_acl_data_packet_length = max_acl_data_packet_length;
456         }
457 
458         // copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
459         if (acl_header_pos > 0){
460             uint16_t handle_and_flags = READ_BT_16(hci_stack->hci_packet_buffer, 0);
461             handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12);
462             bt_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
463         }
464 
465         // update header len
466         bt_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length);
467 
468         // count packet
469         connection->num_acl_packets_sent++;
470 
471         // send packet
472         uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
473         const int size = current_acl_data_packet_length + 4;
474         hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
475         err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
476 
477         // done yet?
478         if (!more_fragments) break;
479 
480         // update start of next fragment to send
481         hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
482 
483         // can send more?
484         if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
485     }
486 
487     // done
488     hci_stack->acl_fragmentation_pos = 0;
489     hci_stack->acl_fragmentation_total_size = 0;
490 
491     // release buffer now for synchronous transport
492     if (hci_transport_synchronous()){
493         hci_release_packet_buffer();
494     }
495 
496     return err;
497 }
498 
499 // pre: caller has reserved the packet buffer
500 int hci_send_acl_packet_buffer(int size){
501 
502     // log_info("hci_send_acl_packet_buffer size %u", size);
503 
504     if (!hci_stack->hci_packet_buffer_reserved) {
505         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
506         return 0;
507     }
508 
509     uint8_t * packet = hci_stack->hci_packet_buffer;
510     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
511 
512     // check for free places on Bluetooth module
513     if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
514         log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
515         hci_release_packet_buffer();
516         return BTSTACK_ACL_BUFFERS_FULL;
517     }
518 
519     hci_connection_t *connection = hci_connection_for_handle( con_handle);
520     if (!connection) {
521         log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
522         hci_release_packet_buffer();
523         return 0;
524     }
525     hci_connection_timestamp(connection);
526 
527     // hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
528 
529     // setup data
530     hci_stack->acl_fragmentation_total_size = size;
531     hci_stack->acl_fragmentation_pos = 4;   // start of L2CAP packet
532 
533     return hci_send_acl_packet_fragments(connection);
534 }
535 
536 // pre: caller has reserved the packet buffer
537 int hci_send_sco_packet_buffer(int size){
538 
539     // log_info("hci_send_acl_packet_buffer size %u", size);
540 
541     if (!hci_stack->hci_packet_buffer_reserved) {
542         log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
543         return 0;
544     }
545 
546     uint8_t * packet = hci_stack->hci_packet_buffer;
547     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);   // same for ACL and SCO
548 
549     // check for free places on Bluetooth module
550     if (!hci_can_send_prepared_sco_packet_now(con_handle)) {
551         log_error("hci_send_sco_packet_buffer called but no free ACL buffers on controller");
552         hci_release_packet_buffer();
553         return BTSTACK_ACL_BUFFERS_FULL;
554     }
555 
556     // TODO: track send packet in connection struct
557     // hci_connection_t *connection = hci_connection_for_handle( con_handle);
558     // if (!connection) {
559     //     log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
560     //     hci_release_packet_buffer();
561     //     return 0;
562     // }
563     // hci_connection_timestamp(connection);
564 
565     hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
566     return hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
567 }
568 
569 static void acl_handler(uint8_t *packet, int size){
570 
571     // log_info("acl_handler: size %u", size);
572 
573     // get info
574     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
575     hci_connection_t *conn      = hci_connection_for_handle(con_handle);
576     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
577     uint16_t acl_length         = READ_ACL_LENGTH(packet);
578 
579     // ignore non-registered handle
580     if (!conn){
581         log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle);
582         return;
583     }
584 
585     // assert packet is complete
586     if (acl_length + 4 != size){
587         log_error("hci.c: acl_handler called with ACL packet of wrong size %u, expected %u => dropping packet", size, acl_length + 4);
588         return;
589     }
590 
591     // update idle timestamp
592     hci_connection_timestamp(conn);
593 
594     // handle different packet types
595     switch (acl_flags & 0x03) {
596 
597         case 0x01: // continuation fragment
598 
599             // sanity checks
600             if (conn->acl_recombination_pos == 0) {
601                 log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
602                 return;
603             }
604             if (conn->acl_recombination_pos + acl_length > 4 + HCI_ACL_BUFFER_SIZE){
605                 log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
606                     conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
607                 conn->acl_recombination_pos = 0;
608                 return;
609             }
610 
611             // append fragment payload (header already stored)
612             memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos], &packet[4], acl_length );
613             conn->acl_recombination_pos += acl_length;
614 
615             // log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length,
616             //        conn->acl_recombination_pos, conn->acl_recombination_length);
617 
618             // forward complete L2CAP packet if complete.
619             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
620 
621                 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, &conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
622                 // reset recombination buffer
623                 conn->acl_recombination_length = 0;
624                 conn->acl_recombination_pos = 0;
625             }
626             break;
627 
628         case 0x02: { // first fragment
629 
630             // sanity check
631             if (conn->acl_recombination_pos) {
632                 log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
633                 conn->acl_recombination_pos = 0;
634             }
635 
636             // peek into L2CAP packet!
637             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
638 
639             // log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length);
640 
641             // compare fragment size to L2CAP packet size
642             if (acl_length >= l2cap_length + 4){
643 
644                 // forward fragment as L2CAP packet
645                 hci_stack->packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4);
646 
647             } else {
648 
649                 if (acl_length > HCI_ACL_BUFFER_SIZE){
650                     log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
651                         4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
652                     return;
653                 }
654 
655                 // store first fragment and tweak acl length for complete package
656                 memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], packet, acl_length + 4);
657                 conn->acl_recombination_pos    = acl_length + 4;
658                 conn->acl_recombination_length = l2cap_length;
659                 bt_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2, l2cap_length +4);
660             }
661             break;
662 
663         }
664         default:
665             log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
666             return;
667     }
668 
669     // execute main loop
670     hci_run();
671 }
672 
673 static void hci_shutdown_connection(hci_connection_t *conn){
674     log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
675 
676     run_loop_remove_timer(&conn->timeout);
677 
678     linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
679     btstack_memory_hci_connection_free( conn );
680 
681     // now it's gone
682     hci_emit_nr_connections_changed();
683 }
684 
685 static const uint16_t packet_type_sizes[] = {
686     0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
687     HCI_ACL_DH1_SIZE, 0, 0, 0,
688     HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
689     HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
690 };
691 static const uint8_t  packet_type_feature_requirement_bit[] = {
692      0, // 3 slot packets
693      1, // 5 slot packets
694     25, // EDR 2 mpbs
695     26, // EDR 3 mbps
696     39, // 3 slot EDR packts
697     40, // 5 slot EDR packet
698 };
699 static const uint16_t packet_type_feature_packet_mask[] = {
700     0x0f00, // 3 slot packets
701     0xf000, // 5 slot packets
702     0x1102, // EDR 2 mpbs
703     0x2204, // EDR 3 mbps
704     0x0300, // 3 slot EDR packts
705     0x3000, // 5 slot EDR packet
706 };
707 
708 static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
709     // enable packet types based on size
710     uint16_t packet_types = 0;
711     unsigned int i;
712     for (i=0;i<16;i++){
713         if (packet_type_sizes[i] == 0) continue;
714         if (packet_type_sizes[i] <= buffer_size){
715             packet_types |= 1 << i;
716         }
717     }
718     // disable packet types due to missing local supported features
719     for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
720         int bit_idx = packet_type_feature_requirement_bit[i];
721         int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
722         if (feature_set) continue;
723         log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
724         packet_types &= ~packet_type_feature_packet_mask[i];
725     }
726     // flip bits for "may not be used"
727     packet_types ^= 0x3306;
728     return packet_types;
729 }
730 
731 uint16_t hci_usable_acl_packet_types(void){
732     return hci_stack->packet_types;
733 }
734 
735 uint8_t* hci_get_outgoing_packet_buffer(void){
736     // hci packet buffer is >= acl data packet length
737     return hci_stack->hci_packet_buffer;
738 }
739 
740 uint16_t hci_max_acl_data_packet_length(void){
741     return hci_stack->acl_data_packet_length;
742 }
743 
744 int hci_non_flushable_packet_boundary_flag_supported(void){
745     // No. 54, byte 6, bit 6
746     return (hci_stack->local_supported_features[6] & (1 << 6)) != 0;
747 }
748 
749 int hci_ssp_supported(void){
750     // No. 51, byte 6, bit 3
751     return (hci_stack->local_supported_features[6] & (1 << 3)) != 0;
752 }
753 
754 int hci_classic_supported(void){
755     // No. 37, byte 4, bit 5, = No BR/EDR Support
756     return (hci_stack->local_supported_features[4] & (1 << 5)) == 0;
757 }
758 
759 int hci_le_supported(void){
760 #ifdef HAVE_BLE
761     // No. 37, byte 4, bit 6 = LE Supported (Controller)
762     return (hci_stack->local_supported_features[4] & (1 << 6)) != 0;
763 #else
764     return 0;
765 #endif
766 }
767 
768 // get addr type and address used in advertisement packets
769 void hci_le_advertisement_address(uint8_t * addr_type, bd_addr_t * addr){
770     *addr_type = hci_stack->adv_addr_type;
771     if (hci_stack->adv_addr_type){
772         memcpy(addr, hci_stack->adv_address, 6);
773     } else {
774         memcpy(addr, hci_stack->local_bd_addr, 6);
775     }
776 }
777 
778 #ifdef HAVE_BLE
779 void le_handle_advertisement_report(uint8_t *packet, int size){
780     int offset = 3;
781     int num_reports = packet[offset];
782     offset += 1;
783 
784     int i;
785     log_info("HCI: handle adv report with num reports: %d", num_reports);
786     uint8_t event[12 + LE_ADVERTISING_DATA_SIZE]; // use upper bound to avoid var size automatic var
787     for (i=0; i<num_reports;i++){
788         uint8_t data_length = packet[offset + 8];
789         uint8_t event_size = 10 + data_length;
790         int pos = 0;
791         event[pos++] = GAP_LE_ADVERTISING_REPORT;
792         event[pos++] = event_size;
793         memcpy(&event[pos], &packet[offset], 1+1+6); // event type + address type + address
794         offset += 8;
795         pos += 8;
796         event[pos++] = packet[offset + 1 + data_length]; // rssi
797         event[pos++] = packet[offset++]; //data_length;
798         memcpy(&event[pos], &packet[offset], data_length);
799         pos += data_length;
800         offset += data_length + 1; // rssi
801         hci_dump_packet( HCI_EVENT_PACKET, 0, event, pos);
802         hci_stack->packet_handler(HCI_EVENT_PACKET, event, pos);
803     }
804 }
805 #endif
806 
807 static void hci_initializing_event_handler(uint8_t * packet, uint16_t size){
808     uint8_t command_completed = 0;
809     if ((hci_stack->substate % 2) == 0) return;
810     // odd: waiting for event
811     if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){
812         uint16_t opcode = READ_BT_16(packet,3);
813         if (opcode == hci_stack->last_cmd_opcode){
814             command_completed = 1;
815             log_info("Command complete for expected opcode %04x -> new substate %u", opcode, hci_stack->substate >> 1);
816         } else {
817             log_info("Command complete for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
818         }
819     }
820     if (packet[0] == HCI_EVENT_COMMAND_STATUS){
821         uint8_t  status = packet[2];
822         uint16_t opcode = READ_BT_16(packet,4);
823         if (opcode == hci_stack->last_cmd_opcode){
824             if (status){
825                 command_completed = 1;
826                 log_error("Command status error 0x%02x for expected opcode %04x -> new substate %u", status, opcode, hci_stack->substate >> 1);
827             } else {
828                 log_info("Command status OK for expected opcode %04x, waiting for command complete", opcode);
829             }
830         } else {
831             log_info("Command status for opcode %04x, expected %04x", opcode, hci_stack->last_cmd_opcode);
832         }
833     }
834 
835     if (!command_completed) return;
836 
837     switch(hci_stack->substate >> 1){
838         default:
839             hci_stack->substate++;
840             break;
841     }
842 }
843 
844 static void hci_initializing_state_machine(){
845     if (hci_stack->substate % 2) {
846         // odd: waiting for command completion
847         return;
848     }
849     // log_info("hci_init: substate %u", hci_stack->substate >> 1);
850     switch (hci_stack->substate >> 1){
851         case 0: // RESET
852             hci_state_reset();
853 
854             hci_send_cmd(&hci_reset);
855             if (hci_stack->config == NULL || ((hci_uart_config_t *)hci_stack->config)->baudrate_main == 0){
856                 // skip baud change
857                 hci_stack->substate = 2 << 1;
858             }
859             break;
860         case 1: // SEND BAUD CHANGE
861             hci_stack->control->baudrate_cmd(hci_stack->config, ((hci_uart_config_t *)hci_stack->config)->baudrate_main, hci_stack->hci_packet_buffer);
862             hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
863             hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
864             break;
865         case 2: // LOCAL BAUD CHANGE
866             log_info("Local baud rate change");
867             hci_stack->hci_transport->set_baudrate(((hci_uart_config_t *)hci_stack->config)->baudrate_main);
868             hci_stack->substate += 2;
869             // break missing here for fall through
870 
871         case 3: // SET BD ADDR
872             if ( hci_stack->custom_bd_addr_set && hci_stack->control && hci_stack->control->set_bd_addr_cmd){
873                 log_info("Set Public BD ADDR to %s", bd_addr_to_str(hci_stack->custom_bd_addr));
874                 hci_stack->control->set_bd_addr_cmd(hci_stack->config, hci_stack->custom_bd_addr, hci_stack->hci_packet_buffer);
875                 hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
876                 hci_send_cmd_packet(hci_stack->hci_packet_buffer, 3 + hci_stack->hci_packet_buffer[2]);
877                 break;
878             }
879             hci_stack->substate += 2;
880             // break missing here for fall through
881 
882         case 4:
883             log_info("Custom init");
884             // Custom initialization
885             if (hci_stack->control && hci_stack->control->next_cmd){
886                 int valid_cmd = (*hci_stack->control->next_cmd)(hci_stack->config, hci_stack->hci_packet_buffer);
887                 if (valid_cmd){
888                     int size = 3 + hci_stack->hci_packet_buffer[2];
889                     hci_stack->last_cmd_opcode = READ_BT_16(hci_stack->hci_packet_buffer, 0);
890                     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, hci_stack->hci_packet_buffer, size);
891                     hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, hci_stack->hci_packet_buffer, size);
892                     hci_stack->substate = 3 << 1; // more init commands
893                     break;
894                 }
895                 log_info("hci_run: init script done");
896             }
897             // otherwise continue
898             hci_send_cmd(&hci_read_bd_addr);
899             break;
900         case 5:
901             hci_send_cmd(&hci_read_buffer_size);
902             break;
903         case 6:
904             hci_send_cmd(&hci_read_local_supported_features);
905             break;
906         case 7:
907             if (hci_le_supported()){
908                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x3FFFFFFF);
909             } else {
910                 // Kensington Bluetooth 2.1 USB Dongle (CSR Chipset) returns an error for 0xffff...
911                 hci_send_cmd(&hci_set_event_mask,0xffffffff, 0x1FFFFFFF);
912             }
913 
914             // skip Classic init commands for LE only chipsets
915             if (!hci_classic_supported()){
916                 if (hci_le_supported()){
917                     hci_stack->substate = 12 << 1;    // skip all classic command
918                 } else {
919                     log_error("Neither BR/EDR nor LE supported");
920                     hci_stack->substate = 15 << 1;    // skip all
921                 }
922             }
923             break;
924         case 8:
925             if (hci_ssp_supported()){
926                 hci_send_cmd(&hci_write_simple_pairing_mode, hci_stack->ssp_enable);
927                 break;
928             }
929             hci_stack->substate += 2;
930             // break missing here for fall through
931 
932         case 9:
933             // ca. 15 sec
934             hci_send_cmd(&hci_write_page_timeout, 0x6000);
935             break;
936         case 10:
937             hci_send_cmd(&hci_write_class_of_device, hci_stack->class_of_device);
938             break;
939         case 11:
940             if (hci_stack->local_name){
941                 hci_send_cmd(&hci_write_local_name, hci_stack->local_name);
942             } else {
943                 char hostname[30];
944 #ifdef EMBEDDED
945                 // BTstack-11:22:33:44:55:66
946                 strcpy(hostname, "BTstack ");
947                 strcat(hostname, bd_addr_to_str(hci_stack->local_bd_addr));
948                 log_info("---> Name %s", hostname);
949 #else
950                 // hostname for POSIX systems
951                 gethostname(hostname, 30);
952                 hostname[29] = '\0';
953 #endif
954                 hci_send_cmd(&hci_write_local_name, hostname);
955             }
956             break;
957         case 12:
958             hci_send_cmd(&hci_write_scan_enable, (hci_stack->connectable << 1) | hci_stack->discoverable); // page scan
959             if (!hci_le_supported()){
960                 // SKIP LE init for Classic only configuration
961                 hci_stack->substate = 15 << 1;
962             }
963             break;
964 
965 #ifdef HAVE_BLE
966         // LE INIT
967         case 13:
968             hci_send_cmd(&hci_le_read_buffer_size);
969             break;
970         case 14:
971             // LE Supported Host = 1, Simultaneous Host = 0
972             hci_send_cmd(&hci_write_le_host_supported, 1, 0);
973             break;
974         case 15:
975             // LE Scan Parameters: active scanning, 300 ms interval, 30 ms window, public address, accept all advs
976             hci_send_cmd(&hci_le_set_scan_parameters, 1, 0x1e0, 0x30, 0, 0);
977             break;
978 #endif
979 
980         // DONE
981         case 16:
982             // done.
983             hci_stack->state = HCI_STATE_WORKING;
984             hci_emit_state();
985             break;
986         default:
987             break;
988     }
989     hci_stack->substate++;
990 }
991 
992 // avoid huge local variables
993 #ifndef EMBEDDED
994 static device_name_t device_name;
995 #endif
996 static void event_handler(uint8_t *packet, int size){
997 
998     uint16_t event_length = packet[1];
999 
1000     // assert packet is complete
1001     if (size != event_length + 2){
1002         log_error("hci.c: event_handler called with event packet of wrong size %u, expected %u => dropping packet", size, event_length + 2);
1003         return;
1004     }
1005 
1006     bd_addr_t addr;
1007     bd_addr_type_t addr_type;
1008     uint8_t link_type;
1009     hci_con_handle_t handle;
1010     hci_connection_t * conn;
1011     int i;
1012 
1013     // log_info("HCI:EVENT:%02x", packet[0]);
1014 
1015     switch (packet[0]) {
1016 
1017         case HCI_EVENT_COMMAND_COMPLETE:
1018             // get num cmd packets
1019             // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u", hci_stack->num_cmd_packets, packet[2]);
1020             hci_stack->num_cmd_packets = packet[2];
1021 
1022             if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){
1023                 // from offset 5
1024                 // status
1025                 // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets"
1026                 hci_stack->acl_data_packet_length = READ_BT_16(packet, 6);
1027                 hci_stack->sco_data_packet_length = packet[8];
1028                 hci_stack->acl_packets_total_num  = packet[9];
1029                 hci_stack->sco_packets_total_num  = packet[10];
1030 
1031                 if (hci_stack->state == HCI_STATE_INITIALIZING){
1032                     // determine usable ACL payload size
1033                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->acl_data_packet_length){
1034                         hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
1035                     }
1036                     log_info("hci_read_buffer_size: used size %u, count %u",
1037                              hci_stack->acl_data_packet_length, hci_stack->acl_packets_total_num);
1038                 }
1039             }
1040 #ifdef HAVE_BLE
1041             if (COMMAND_COMPLETE_EVENT(packet, hci_le_read_buffer_size)){
1042                 hci_stack->le_data_packets_length = READ_BT_16(packet, 6);
1043                 hci_stack->le_acl_packets_total_num  = packet[8];
1044                     // determine usable ACL payload size
1045                     if (HCI_ACL_PAYLOAD_SIZE < hci_stack->le_data_packets_length){
1046                         hci_stack->le_data_packets_length = HCI_ACL_PAYLOAD_SIZE;
1047                     }
1048                 log_info("hci_le_read_buffer_size: size %u, count %u", hci_stack->le_data_packets_length, hci_stack->le_acl_packets_total_num);
1049             }
1050 #endif
1051             // Dump local address
1052             if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) {
1053                 bt_flip_addr(hci_stack->local_bd_addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]);
1054                 log_info("Local Address, Status: 0x%02x: Addr: %s",
1055                     packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(hci_stack->local_bd_addr));
1056             }
1057             if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
1058                 hci_emit_discoverable_enabled(hci_stack->discoverable);
1059             }
1060             // Note: HCI init checks
1061             if (COMMAND_COMPLETE_EVENT(packet, hci_read_local_supported_features)){
1062                 memcpy(hci_stack->local_supported_features, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE+1], 8);
1063                 log_info("Local Supported Features: 0x%02x%02x%02x%02x%02x%02x%02x%02x",
1064                     hci_stack->local_supported_features[0], hci_stack->local_supported_features[1],
1065                     hci_stack->local_supported_features[2], hci_stack->local_supported_features[3],
1066                     hci_stack->local_supported_features[4], hci_stack->local_supported_features[5],
1067                     hci_stack->local_supported_features[6], hci_stack->local_supported_features[7]);
1068 
1069                 // determine usable ACL packet types based on host buffer size and supported features
1070                 hci_stack->packet_types = hci_acl_packet_types_for_buffer_size_and_local_features(HCI_ACL_PAYLOAD_SIZE, &hci_stack->local_supported_features[0]);
1071                 log_info("packet types %04x", hci_stack->packet_types);
1072 
1073                 // Classic/LE
1074                 log_info("BR/EDR support %u, LE support %u", hci_classic_supported(), hci_le_supported());
1075             }
1076             break;
1077 
1078         case HCI_EVENT_COMMAND_STATUS:
1079             // get num cmd packets
1080             // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u", hci_stack->num_cmd_packets, packet[3]);
1081             hci_stack->num_cmd_packets = packet[3];
1082             break;
1083 
1084         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:{
1085             int offset = 3;
1086             for (i=0; i<packet[2];i++){
1087                 handle = READ_BT_16(packet, offset);
1088                 offset += 2;
1089                 uint16_t num_packets = READ_BT_16(packet, offset);
1090                 offset += 2;
1091 
1092                 conn = hci_connection_for_handle(handle);
1093                 if (!conn){
1094                     log_error("hci_number_completed_packet lists unused con handle %u", handle);
1095                     continue;
1096                 }
1097 
1098                 if (conn->num_acl_packets_sent >= num_packets){
1099                     conn->num_acl_packets_sent -= num_packets;
1100                 } else {
1101                     log_error("hci_number_completed_packets, more slots freed then sent.");
1102                     conn->num_acl_packets_sent = 0;
1103                 }
1104                 // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u", num_packets, handle, conn->num_acl_packets_sent);
1105             }
1106             break;
1107         }
1108         case HCI_EVENT_CONNECTION_REQUEST:
1109             bt_flip_addr(addr, &packet[2]);
1110             // TODO: eval COD 8-10
1111             link_type = packet[11];
1112             log_info("Connection_incoming: %s, type %u", bd_addr_to_str(addr), link_type);
1113             if (link_type == 1) { // ACL
1114                 conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1115                 if (!conn) {
1116                     conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
1117                 }
1118                 if (!conn) {
1119                     // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D)
1120                     hci_stack->decline_reason = 0x0d;
1121                     BD_ADDR_COPY(hci_stack->decline_addr, addr);
1122                     break;
1123                 }
1124                 conn->state = RECEIVED_CONNECTION_REQUEST;
1125                 hci_run();
1126             } else {
1127                 // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A)
1128                 hci_stack->decline_reason = 0x0a;
1129                 BD_ADDR_COPY(hci_stack->decline_addr, addr);
1130             }
1131             break;
1132 
1133         case HCI_EVENT_CONNECTION_COMPLETE:
1134             // Connection management
1135             bt_flip_addr(addr, &packet[5]);
1136             log_info("Connection_complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1137             addr_type = BD_ADDR_TYPE_CLASSIC;
1138             conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
1139             if (conn) {
1140                 if (!packet[2]){
1141                     conn->state = OPEN;
1142                     conn->con_handle = READ_BT_16(packet, 3);
1143                     conn->bonding_flags |= BONDING_REQUEST_REMOTE_FEATURES;
1144 
1145                     // restart timer
1146                     run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1147                     run_loop_add_timer(&conn->timeout);
1148 
1149                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1150 
1151                     hci_emit_nr_connections_changed();
1152                 } else {
1153                     int notify_dedicated_bonding_failed = conn->bonding_flags & BONDING_DEDICATED;
1154                     uint8_t status = packet[2];
1155                     bd_addr_t bd_address;
1156                     memcpy(&bd_address, conn->address, 6);
1157 
1158                     // connection failed, remove entry
1159                     linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
1160                     btstack_memory_hci_connection_free( conn );
1161 
1162                     // notify client if dedicated bonding
1163                     if (notify_dedicated_bonding_failed){
1164                         log_info("hci notify_dedicated_bonding_failed");
1165                         hci_emit_dedicated_bonding_result(bd_address, status);
1166                     }
1167 
1168                     // if authentication error, also delete link key
1169                     if (packet[2] == 0x05) {
1170                         hci_drop_link_key_for_bd_addr(&addr);
1171                     }
1172                 }
1173             }
1174             break;
1175 
1176         case HCI_EVENT_SYNCHRONOUS_CONNECTION_COMPLETE:
1177             bt_flip_addr(addr, &packet[5]);
1178             log_info("Synchronous Connection Complete (status=%u) %s", packet[2], bd_addr_to_str(addr));
1179             if (!packet[2]){
1180                 // connection failed
1181                 break;
1182             }
1183             // conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_SCO);
1184             // if (!conn) break;
1185             break;
1186 
1187         case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE:
1188             handle = READ_BT_16(packet, 3);
1189             conn = hci_connection_for_handle(handle);
1190             if (!conn) break;
1191             if (!packet[2]){
1192                 uint8_t * features = &packet[5];
1193                 if (features[6] & (1 << 3)){
1194                     conn->bonding_flags |= BONDING_REMOTE_SUPPORTS_SSP;
1195                 }
1196             }
1197             conn->bonding_flags |= BONDING_RECEIVED_REMOTE_FEATURES;
1198             log_info("HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE, bonding flags %x", conn->bonding_flags);
1199             if (conn->bonding_flags & BONDING_DEDICATED){
1200                 conn->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
1201             }
1202             break;
1203 
1204         case HCI_EVENT_LINK_KEY_REQUEST:
1205             log_info("HCI_EVENT_LINK_KEY_REQUEST");
1206             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST);
1207             // non-bondable mode: link key negative reply will be sent by HANDLE_LINK_KEY_REQUEST
1208             if (hci_stack->bondable && !hci_stack->remote_device_db) break;
1209             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST);
1210             hci_run();
1211             // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set
1212             return;
1213 
1214         case HCI_EVENT_LINK_KEY_NOTIFICATION: {
1215             bt_flip_addr(addr, &packet[2]);
1216             conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
1217             if (!conn) break;
1218             conn->authentication_flags |= RECV_LINK_KEY_NOTIFICATION;
1219             link_key_type_t link_key_type = (link_key_type_t)packet[24];
1220             // Change Connection Encryption keeps link key type
1221             if (link_key_type != CHANGED_COMBINATION_KEY){
1222                 conn->link_key_type = link_key_type;
1223             }
1224             if (!hci_stack->remote_device_db) break;
1225             hci_stack->remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8], conn->link_key_type);
1226             // still forward event to allow dismiss of pairing dialog
1227             break;
1228         }
1229 
1230         case HCI_EVENT_PIN_CODE_REQUEST:
1231             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], LEGACY_PAIRING_ACTIVE);
1232             // non-bondable mode: pin code negative reply will be sent
1233             if (!hci_stack->bondable){
1234                 hci_add_connection_flags_for_flipped_bd_addr(&packet[2], DENY_PIN_CODE_REQUEST);
1235                 hci_run();
1236                 return;
1237             }
1238             // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key
1239             if (!hci_stack->remote_device_db) break;
1240             bt_flip_addr(addr, &packet[2]);
1241             hci_stack->remote_device_db->delete_link_key(&addr);
1242             break;
1243 
1244         case HCI_EVENT_IO_CAPABILITY_REQUEST:
1245             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_IO_CAPABILITIES_REQUEST);
1246             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_IO_CAPABILITIES_REPLY);
1247             break;
1248 
1249         case HCI_EVENT_USER_CONFIRMATION_REQUEST:
1250             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1251             if (!hci_stack->ssp_auto_accept) break;
1252             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_CONFIRM_REPLY);
1253             break;
1254 
1255         case HCI_EVENT_USER_PASSKEY_REQUEST:
1256             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SSP_PAIRING_ACTIVE);
1257             if (!hci_stack->ssp_auto_accept) break;
1258             hci_add_connection_flags_for_flipped_bd_addr(&packet[2], SEND_USER_PASSKEY_REPLY);
1259             break;
1260 
1261         case HCI_EVENT_ENCRYPTION_CHANGE:
1262             handle = READ_BT_16(packet, 3);
1263             conn = hci_connection_for_handle(handle);
1264             if (!conn) break;
1265             if (packet[2] == 0) {
1266                 if (packet[5]){
1267                     conn->authentication_flags |= CONNECTION_ENCRYPTED;
1268                 } else {
1269                     conn->authentication_flags &= ~CONNECTION_ENCRYPTED;
1270                 }
1271             }
1272             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1273             break;
1274 
1275         case HCI_EVENT_AUTHENTICATION_COMPLETE_EVENT:
1276             handle = READ_BT_16(packet, 3);
1277             conn = hci_connection_for_handle(handle);
1278             if (!conn) break;
1279 
1280             // dedicated bonding: send result and disconnect
1281             if (conn->bonding_flags & BONDING_DEDICATED){
1282                 conn->bonding_flags &= ~BONDING_DEDICATED;
1283                 conn->bonding_flags |= BONDING_DISCONNECT_DEDICATED_DONE;
1284                 conn->bonding_status = packet[2];
1285                 break;
1286             }
1287 
1288             if (packet[2] == 0 && gap_security_level_for_link_key_type(conn->link_key_type) >= conn->requested_security_level){
1289                 // link key sufficient for requested security
1290                 conn->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
1291                 break;
1292             }
1293             // not enough
1294             hci_emit_security_level(handle, gap_security_level_for_connection(conn));
1295             break;
1296 
1297 #ifndef EMBEDDED
1298         case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE:
1299             if (!hci_stack->remote_device_db) break;
1300             if (packet[2]) break; // status not ok
1301             bt_flip_addr(addr, &packet[3]);
1302             // fix for invalid remote names - terminate on 0xff
1303             for (i=0; i<248;i++){
1304                 if (packet[9+i] == 0xff){
1305                     packet[9+i] = 0;
1306                     break;
1307                 }
1308             }
1309             memset(&device_name, 0, sizeof(device_name_t));
1310             strncpy((char*) device_name, (char*) &packet[9], 248);
1311             hci_stack->remote_device_db->put_name(&addr, &device_name);
1312             break;
1313 
1314         case HCI_EVENT_INQUIRY_RESULT:
1315         case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:{
1316             if (!hci_stack->remote_device_db) break;
1317             // first send inq result packet
1318             hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
1319             // then send cached remote names
1320             int offset = 3;
1321             for (i=0; i<packet[2];i++){
1322                 bt_flip_addr(addr, &packet[offset]);
1323                 offset += 14; // 6 + 1 + 1 + 1 + 3 + 2;
1324                 if (hci_stack->remote_device_db->get_name(&addr, &device_name)){
1325                     hci_emit_remote_name_cached(&addr, &device_name);
1326                 }
1327             }
1328             return;
1329         }
1330 #endif
1331 
1332         // HCI_EVENT_DISCONNECTION_COMPLETE
1333         // has been split, to first notify stack before shutting connection down
1334         // see end of function, too.
1335         case HCI_EVENT_DISCONNECTION_COMPLETE:
1336             if (packet[2]) break;   // status != 0
1337             handle = READ_BT_16(packet, 3);
1338             hci_connection_t * conn = hci_connection_for_handle(handle);
1339             if (!conn) break;       // no conn struct anymore
1340             conn->state = RECEIVED_DISCONNECTION_COMPLETE;
1341             break;
1342 
1343         case HCI_EVENT_HARDWARE_ERROR:
1344             if(hci_stack->control && hci_stack->control->hw_error){
1345                 (*hci_stack->control->hw_error)();
1346             } else {
1347                 // if no special requests, just reboot stack
1348                 hci_power_control_off();
1349                 hci_power_control_on();
1350             }
1351             break;
1352 
1353         case DAEMON_EVENT_HCI_PACKET_SENT:
1354             // release packet buffer only for asynchronous transport and if there are not further fragements
1355             if (hci_transport_synchronous()) {
1356                 log_error("Synchronous HCI Transport shouldn't send DAEMON_EVENT_HCI_PACKET_SENT");
1357                 return; // instead of break: to avoid re-entering hci_run()
1358             }
1359             if (hci_stack->acl_fragmentation_total_size) break;
1360             hci_release_packet_buffer();
1361             break;
1362 
1363 #ifdef HAVE_BLE
1364         case HCI_EVENT_LE_META:
1365             switch (packet[2]){
1366                 case HCI_SUBEVENT_LE_ADVERTISING_REPORT:
1367                     log_info("advertising report received");
1368                     if (hci_stack->le_scanning_state != LE_SCANNING) break;
1369                     le_handle_advertisement_report(packet, size);
1370                     break;
1371                 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
1372                     // Connection management
1373                     bt_flip_addr(addr, &packet[8]);
1374                     addr_type = (bd_addr_type_t)packet[7];
1375                     log_info("LE Connection_complete (status=%u) type %u, %s", packet[3], addr_type, bd_addr_to_str(addr));
1376                     // LE connections are auto-accepted, so just create a connection if there isn't one already
1377                     conn = hci_connection_for_bd_addr_and_type(&addr, addr_type);
1378                     if (packet[3]){
1379                         if (conn){
1380                             // outgoing connection failed, remove entry
1381                             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
1382                             btstack_memory_hci_connection_free( conn );
1383                         }
1384                         // if authentication error, also delete link key
1385                         if (packet[3] == 0x05) {
1386                             hci_drop_link_key_for_bd_addr(&addr);
1387                         }
1388                         break;
1389                     }
1390                     if (!conn){
1391                         conn = create_connection_for_bd_addr_and_type(addr, addr_type);
1392                     }
1393                     if (!conn){
1394                         // no memory
1395                         break;
1396                     }
1397 
1398                     conn->state = OPEN;
1399                     conn->con_handle = READ_BT_16(packet, 4);
1400 
1401                     // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock
1402 
1403                     // restart timer
1404                     // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
1405                     // run_loop_add_timer(&conn->timeout);
1406 
1407                     log_info("New connection: handle %u, %s", conn->con_handle, bd_addr_to_str(conn->address));
1408 
1409                     hci_emit_nr_connections_changed();
1410                     break;
1411 
1412             // log_info("LE buffer size: %u, count %u", READ_BT_16(packet,6), packet[8]);
1413 
1414                 default:
1415                     break;
1416             }
1417             break;
1418 #endif
1419         default:
1420             break;
1421     }
1422 
1423     // handle BT initialization
1424     if (hci_stack->state == HCI_STATE_INITIALIZING){
1425         hci_initializing_event_handler(packet, size);
1426     }
1427 
1428     // help with BT sleep
1429     if (hci_stack->state == HCI_STATE_FALLING_ASLEEP
1430         && hci_stack->substate == 1
1431         && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){
1432         hci_stack->substate++;
1433     }
1434 
1435     // notify upper stack
1436     hci_stack->packet_handler(HCI_EVENT_PACKET, packet, size);
1437 
1438     // moved here to give upper stack a chance to close down everything with hci_connection_t intact
1439     if (packet[0] == HCI_EVENT_DISCONNECTION_COMPLETE){
1440         if (!packet[2]){
1441             handle = READ_BT_16(packet, 3);
1442             hci_connection_t * conn = hci_connection_for_handle(handle);
1443             if (conn) {
1444                 uint8_t status = conn->bonding_status;
1445                 uint16_t flags = conn->bonding_flags;
1446                 bd_addr_t bd_address;
1447                 memcpy(&bd_address, conn->address, 6);
1448                 hci_shutdown_connection(conn);
1449                 // connection struct is gone, don't access anymore
1450                 if (flags & BONDING_EMIT_COMPLETE_ON_DISCONNECT){
1451                     hci_emit_dedicated_bonding_result(bd_address, status);
1452                 }
1453             }
1454         }
1455     }
1456 
1457 	// execute main loop
1458 	hci_run();
1459 }
1460 
1461 static void sco_handler(uint8_t * packet, uint16_t size){
1462     // not handled yet
1463 }
1464 
1465 static void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
1466     hci_dump_packet(packet_type, 1, packet, size);
1467     switch (packet_type) {
1468         case HCI_EVENT_PACKET:
1469             event_handler(packet, size);
1470             break;
1471         case HCI_ACL_DATA_PACKET:
1472             acl_handler(packet, size);
1473             break;
1474         case HCI_SCO_DATA_PACKET:
1475             sco_handler(packet, size);
1476         default:
1477             break;
1478     }
1479 }
1480 
1481 /** Register HCI packet handlers */
1482 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
1483     hci_stack->packet_handler = handler;
1484 }
1485 
1486 static void hci_state_reset(){
1487     // no connections yet
1488     hci_stack->connections = NULL;
1489 
1490     // keep discoverable/connectable as this has been requested by the client(s)
1491     // hci_stack->discoverable = 0;
1492     // hci_stack->connectable = 0;
1493     // hci_stack->bondable = 1;
1494 
1495     // buffer is free
1496     hci_stack->hci_packet_buffer_reserved = 0;
1497 
1498     // no pending cmds
1499     hci_stack->decline_reason = 0;
1500     hci_stack->new_scan_enable_value = 0xff;
1501 
1502     // LE
1503     hci_stack->adv_addr_type = 0;
1504     memset(hci_stack->adv_address, 0, 6);
1505     hci_stack->le_scanning_state = LE_SCAN_IDLE;
1506     hci_stack->le_scan_type = 0xff;
1507     hci_stack->le_connection_parameter_range.le_conn_interval_min = 0x0006;
1508     hci_stack->le_connection_parameter_range.le_conn_interval_max = 0x0C80;
1509     hci_stack->le_connection_parameter_range.le_conn_latency_min = 0x0000;
1510     hci_stack->le_connection_parameter_range.le_conn_latency_max = 0x03E8;
1511     hci_stack->le_connection_parameter_range.le_supervision_timeout_min = 0x000A;
1512     hci_stack->le_connection_parameter_range.le_supervision_timeout_max = 0x0C80;
1513 }
1514 
1515 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control, remote_device_db_t const* remote_device_db){
1516 
1517 #ifdef HAVE_MALLOC
1518     if (!hci_stack) {
1519         hci_stack = (hci_stack_t*) malloc(sizeof(hci_stack_t));
1520     }
1521 #else
1522     hci_stack = &hci_stack_static;
1523 #endif
1524     memset(hci_stack, 0, sizeof(hci_stack_t));
1525 
1526     // reference to use transport layer implementation
1527     hci_stack->hci_transport = transport;
1528 
1529     // references to used control implementation
1530     hci_stack->control = control;
1531 
1532     // reference to used config
1533     hci_stack->config = config;
1534 
1535     // higher level handler
1536     hci_stack->packet_handler = dummy_handler;
1537 
1538     // store and open remote device db
1539     hci_stack->remote_device_db = remote_device_db;
1540     if (hci_stack->remote_device_db) {
1541         hci_stack->remote_device_db->open();
1542     }
1543 
1544     // max acl payload size defined in config.h
1545     hci_stack->acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE;
1546 
1547     // register packet handlers with transport
1548     transport->register_packet_handler(&packet_handler);
1549 
1550     hci_stack->state = HCI_STATE_OFF;
1551 
1552     // class of device
1553     hci_stack->class_of_device = 0x007a020c; // Smartphone
1554 
1555     // bondable by default
1556     hci_stack->bondable = 1;
1557 
1558     // Secure Simple Pairing default: enable, no I/O capabilities, general bonding, mitm not required, auto accept
1559     hci_stack->ssp_enable = 1;
1560     hci_stack->ssp_io_capability = SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT;
1561     hci_stack->ssp_authentication_requirement = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_GENERAL_BONDING;
1562     hci_stack->ssp_auto_accept = 1;
1563 
1564     hci_state_reset();
1565 }
1566 
1567 void hci_close(){
1568     // close remote device db
1569     if (hci_stack->remote_device_db) {
1570         hci_stack->remote_device_db->close();
1571     }
1572     while (hci_stack->connections) {
1573         // cancel all l2cap connections
1574         hci_emit_disconnection_complete(((hci_connection_t *) hci_stack->connections)->con_handle, 0x16); // terminated by local host
1575         hci_shutdown_connection((hci_connection_t *) hci_stack->connections);
1576     }
1577     hci_power_control(HCI_POWER_OFF);
1578 
1579 #ifdef HAVE_MALLOC
1580     free(hci_stack);
1581 #endif
1582     hci_stack = NULL;
1583 }
1584 
1585 void hci_set_class_of_device(uint32_t class_of_device){
1586     hci_stack->class_of_device = class_of_device;
1587 }
1588 
1589 // Set Public BD ADDR - passed on to Bluetooth chipset if supported in bt_control_h
1590 void hci_set_bd_addr(bd_addr_t addr){
1591     memcpy(hci_stack->custom_bd_addr, addr, 6);
1592     hci_stack->custom_bd_addr_set = 1;
1593 }
1594 
1595 void hci_disable_l2cap_timeout_check(){
1596     disable_l2cap_timeouts = 1;
1597 }
1598 // State-Module-Driver overview
1599 // state                    module  low-level
1600 // HCI_STATE_OFF             off      close
1601 // HCI_STATE_INITIALIZING,   on       open
1602 // HCI_STATE_WORKING,        on       open
1603 // HCI_STATE_HALTING,        on       open
1604 // HCI_STATE_SLEEPING,    off/sleep   close
1605 // HCI_STATE_FALLING_ASLEEP  on       open
1606 
1607 static int hci_power_control_on(void){
1608 
1609     // power on
1610     int err = 0;
1611     if (hci_stack->control && hci_stack->control->on){
1612         err = (*hci_stack->control->on)(hci_stack->config);
1613     }
1614     if (err){
1615         log_error( "POWER_ON failed");
1616         hci_emit_hci_open_failed();
1617         return err;
1618     }
1619 
1620     // open low-level device
1621     err = hci_stack->hci_transport->open(hci_stack->config);
1622     if (err){
1623         log_error( "HCI_INIT failed, turning Bluetooth off again");
1624         if (hci_stack->control && hci_stack->control->off){
1625             (*hci_stack->control->off)(hci_stack->config);
1626         }
1627         hci_emit_hci_open_failed();
1628         return err;
1629     }
1630     return 0;
1631 }
1632 
1633 static void hci_power_control_off(void){
1634 
1635     log_info("hci_power_control_off");
1636 
1637     // close low-level device
1638     hci_stack->hci_transport->close(hci_stack->config);
1639 
1640     log_info("hci_power_control_off - hci_transport closed");
1641 
1642     // power off
1643     if (hci_stack->control && hci_stack->control->off){
1644         (*hci_stack->control->off)(hci_stack->config);
1645     }
1646 
1647     log_info("hci_power_control_off - control closed");
1648 
1649     hci_stack->state = HCI_STATE_OFF;
1650 }
1651 
1652 static void hci_power_control_sleep(void){
1653 
1654     log_info("hci_power_control_sleep");
1655 
1656 #if 0
1657     // don't close serial port during sleep
1658 
1659     // close low-level device
1660     hci_stack->hci_transport->close(hci_stack->config);
1661 #endif
1662 
1663     // sleep mode
1664     if (hci_stack->control && hci_stack->control->sleep){
1665         (*hci_stack->control->sleep)(hci_stack->config);
1666     }
1667 
1668     hci_stack->state = HCI_STATE_SLEEPING;
1669 }
1670 
1671 static int hci_power_control_wake(void){
1672 
1673     log_info("hci_power_control_wake");
1674 
1675     // wake on
1676     if (hci_stack->control && hci_stack->control->wake){
1677         (*hci_stack->control->wake)(hci_stack->config);
1678     }
1679 
1680 #if 0
1681     // open low-level device
1682     int err = hci_stack->hci_transport->open(hci_stack->config);
1683     if (err){
1684         log_error( "HCI_INIT failed, turning Bluetooth off again");
1685         if (hci_stack->control && hci_stack->control->off){
1686             (*hci_stack->control->off)(hci_stack->config);
1687         }
1688         hci_emit_hci_open_failed();
1689         return err;
1690     }
1691 #endif
1692 
1693     return 0;
1694 }
1695 
1696 static void hci_power_transition_to_initializing(void){
1697     // set up state machine
1698     hci_stack->num_cmd_packets = 1; // assume that one cmd can be sent
1699     hci_stack->hci_packet_buffer_reserved = 0;
1700     hci_stack->state = HCI_STATE_INITIALIZING;
1701     hci_stack->substate = 0;
1702 }
1703 
1704 int hci_power_control(HCI_POWER_MODE power_mode){
1705 
1706     log_info("hci_power_control: %u, current mode %u", power_mode, hci_stack->state);
1707 
1708     int err = 0;
1709     switch (hci_stack->state){
1710 
1711         case HCI_STATE_OFF:
1712             switch (power_mode){
1713                 case HCI_POWER_ON:
1714                     err = hci_power_control_on();
1715                     if (err) {
1716                         log_error("hci_power_control_on() error %u", err);
1717                         return err;
1718                     }
1719                     hci_power_transition_to_initializing();
1720                     break;
1721                 case HCI_POWER_OFF:
1722                     // do nothing
1723                     break;
1724                 case HCI_POWER_SLEEP:
1725                     // do nothing (with SLEEP == OFF)
1726                     break;
1727             }
1728             break;
1729 
1730         case HCI_STATE_INITIALIZING:
1731             switch (power_mode){
1732                 case HCI_POWER_ON:
1733                     // do nothing
1734                     break;
1735                 case HCI_POWER_OFF:
1736                     // no connections yet, just turn it off
1737                     hci_power_control_off();
1738                     break;
1739                 case HCI_POWER_SLEEP:
1740                     // no connections yet, just turn it off
1741                     hci_power_control_sleep();
1742                     break;
1743             }
1744             break;
1745 
1746         case HCI_STATE_WORKING:
1747             switch (power_mode){
1748                 case HCI_POWER_ON:
1749                     // do nothing
1750                     break;
1751                 case HCI_POWER_OFF:
1752                     // see hci_run
1753                     hci_stack->state = HCI_STATE_HALTING;
1754                     break;
1755                 case HCI_POWER_SLEEP:
1756                     // see hci_run
1757                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
1758                     hci_stack->substate = 0;
1759                     break;
1760             }
1761             break;
1762 
1763         case HCI_STATE_HALTING:
1764             switch (power_mode){
1765                 case HCI_POWER_ON:
1766                     hci_power_transition_to_initializing();
1767                     break;
1768                 case HCI_POWER_OFF:
1769                     // do nothing
1770                     break;
1771                 case HCI_POWER_SLEEP:
1772                     // see hci_run
1773                     hci_stack->state = HCI_STATE_FALLING_ASLEEP;
1774                     hci_stack->substate = 0;
1775                     break;
1776             }
1777             break;
1778 
1779         case HCI_STATE_FALLING_ASLEEP:
1780             switch (power_mode){
1781                 case HCI_POWER_ON:
1782 
1783 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1784                     // nothing to do, if H4 supports power management
1785                     if (bt_control_iphone_power_management_enabled()){
1786                         hci_stack->state = HCI_STATE_INITIALIZING;
1787                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1788                         break;
1789                     }
1790 #endif
1791                     hci_power_transition_to_initializing();
1792                     break;
1793                 case HCI_POWER_OFF:
1794                     // see hci_run
1795                     hci_stack->state = HCI_STATE_HALTING;
1796                     break;
1797                 case HCI_POWER_SLEEP:
1798                     // do nothing
1799                     break;
1800             }
1801             break;
1802 
1803         case HCI_STATE_SLEEPING:
1804             switch (power_mode){
1805                 case HCI_POWER_ON:
1806 
1807 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
1808                     // nothing to do, if H4 supports power management
1809                     if (bt_control_iphone_power_management_enabled()){
1810                         hci_stack->state = HCI_STATE_INITIALIZING;
1811                         hci_stack->substate = HCI_INTIALIZING_SUBSTATE_AFTER_SLEEP;
1812                         hci_update_scan_enable();
1813                         break;
1814                     }
1815 #endif
1816                     err = hci_power_control_wake();
1817                     if (err) return err;
1818                     hci_power_transition_to_initializing();
1819                     break;
1820                 case HCI_POWER_OFF:
1821                     hci_stack->state = HCI_STATE_HALTING;
1822                     break;
1823                 case HCI_POWER_SLEEP:
1824                     // do nothing
1825                     break;
1826             }
1827             break;
1828     }
1829 
1830     // create internal event
1831 	hci_emit_state();
1832 
1833 	// trigger next/first action
1834 	hci_run();
1835 
1836     return 0;
1837 }
1838 
1839 static void hci_update_scan_enable(void){
1840     // 2 = page scan, 1 = inq scan
1841     hci_stack->new_scan_enable_value  = hci_stack->connectable << 1 | hci_stack->discoverable;
1842     hci_run();
1843 }
1844 
1845 void hci_discoverable_control(uint8_t enable){
1846     if (enable) enable = 1; // normalize argument
1847 
1848     if (hci_stack->discoverable == enable){
1849         hci_emit_discoverable_enabled(hci_stack->discoverable);
1850         return;
1851     }
1852 
1853     hci_stack->discoverable = enable;
1854     hci_update_scan_enable();
1855 }
1856 
1857 void hci_connectable_control(uint8_t enable){
1858     if (enable) enable = 1; // normalize argument
1859 
1860     // don't emit event
1861     if (hci_stack->connectable == enable) return;
1862 
1863     hci_stack->connectable = enable;
1864     hci_update_scan_enable();
1865 }
1866 
1867 bd_addr_t * hci_local_bd_addr(void){
1868     return &hci_stack->local_bd_addr;
1869 }
1870 
1871 void hci_run(){
1872 
1873     hci_connection_t * connection;
1874     linked_item_t * it;
1875 
1876     // send continuation fragments first, as they block the prepared packet buffer
1877     if (hci_stack->acl_fragmentation_total_size > 0) {
1878         hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(hci_stack->hci_packet_buffer);
1879         if (hci_can_send_prepared_acl_packet_now(con_handle)){
1880             hci_connection_t *connection = hci_connection_for_handle(con_handle);
1881             if (connection) {
1882                 hci_send_acl_packet_fragments(connection);
1883                 return;
1884             }
1885             // connection gone -> discard further fragments
1886             hci_stack->acl_fragmentation_total_size = 0;
1887             hci_stack->acl_fragmentation_pos = 0;
1888         }
1889     }
1890 
1891     if (!hci_can_send_command_packet_now()) return;
1892 
1893     // global/non-connection oriented commands
1894 
1895     // decline incoming connections
1896     if (hci_stack->decline_reason){
1897         uint8_t reason = hci_stack->decline_reason;
1898         hci_stack->decline_reason = 0;
1899         hci_send_cmd(&hci_reject_connection_request, hci_stack->decline_addr, reason);
1900         return;
1901     }
1902 
1903     // send scan enable
1904     if (hci_stack->state == HCI_STATE_WORKING && hci_stack->new_scan_enable_value != 0xff && hci_classic_supported()){
1905         hci_send_cmd(&hci_write_scan_enable, hci_stack->new_scan_enable_value);
1906         hci_stack->new_scan_enable_value = 0xff;
1907         return;
1908     }
1909 
1910 #ifdef HAVE_BLE
1911     // handle le scan
1912     if (hci_stack->state == HCI_STATE_WORKING){
1913         switch(hci_stack->le_scanning_state){
1914             case LE_START_SCAN:
1915                 hci_stack->le_scanning_state = LE_SCANNING;
1916                 hci_send_cmd(&hci_le_set_scan_enable, 1, 0);
1917                 return;
1918 
1919             case LE_STOP_SCAN:
1920                 hci_stack->le_scanning_state = LE_SCAN_IDLE;
1921                 hci_send_cmd(&hci_le_set_scan_enable, 0, 0);
1922                 return;
1923             default:
1924                 break;
1925         }
1926         if (hci_stack->le_scan_type != 0xff){
1927             // defaults: active scanning, accept all advertisement packets
1928             int scan_type = hci_stack->le_scan_type;
1929             hci_stack->le_scan_type = 0xff;
1930             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);
1931             return;
1932         }
1933     }
1934 #endif
1935 
1936     // send pending HCI commands
1937     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
1938         connection = (hci_connection_t *) it;
1939 
1940         switch(connection->state){
1941             case SEND_CREATE_CONNECTION:
1942                 switch(connection->address_type){
1943                     case BD_ADDR_TYPE_CLASSIC:
1944                         log_info("sending hci_create_connection");
1945                         hci_send_cmd(&hci_create_connection, connection->address, hci_usable_acl_packet_types(), 0, 0, 0, 1);
1946                         break;
1947                     default:
1948 #ifdef HAVE_BLE
1949                         log_info("sending hci_le_create_connection");
1950                         hci_send_cmd(&hci_le_create_connection,
1951                                      0x0060,    // scan interval: 60 ms
1952                                      0x0030,    // scan interval: 30 ms
1953                                      0,         // don't use whitelist
1954                                      connection->address_type, // peer address type
1955                                      connection->address,      // peer bd addr
1956                                      hci_stack->adv_addr_type, // our addr type:
1957                                      0x0008,    // conn interval min
1958                                      0x0018,    // conn interval max
1959                                      0,         // conn latency
1960                                      0x0048,    // supervision timeout
1961                                      0x0001,    // min ce length
1962                                      0x0001     // max ce length
1963                                      );
1964 
1965                         connection->state = SENT_CREATE_CONNECTION;
1966 #endif
1967                         break;
1968                 }
1969                 return;
1970 
1971             case RECEIVED_CONNECTION_REQUEST:
1972                 log_info("sending hci_accept_connection_request");
1973                 connection->state = ACCEPTED_CONNECTION_REQUEST;
1974                 hci_send_cmd(&hci_accept_connection_request, connection->address, 1);
1975                 return;
1976 
1977 #ifdef HAVE_BLE
1978             case SEND_CANCEL_CONNECTION:
1979                 connection->state = SENT_CANCEL_CONNECTION;
1980                 hci_send_cmd(&hci_le_create_connection_cancel);
1981                 return;
1982 #endif
1983             case SEND_DISCONNECT:
1984                 connection->state = SENT_DISCONNECT;
1985                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13); // remote closed connection
1986                 return;
1987 
1988             default:
1989                 break;
1990         }
1991 
1992         if (connection->authentication_flags & HANDLE_LINK_KEY_REQUEST){
1993             log_info("responding to link key request");
1994             connectionClearAuthenticationFlags(connection, HANDLE_LINK_KEY_REQUEST);
1995             link_key_t link_key;
1996             link_key_type_t link_key_type;
1997             if ( hci_stack->remote_device_db
1998               && hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)
1999               && gap_security_level_for_link_key_type(link_key_type) >= connection->requested_security_level){
2000                connection->link_key_type = link_key_type;
2001                hci_send_cmd(&hci_link_key_request_reply, connection->address, &link_key);
2002             } else {
2003                hci_send_cmd(&hci_link_key_request_negative_reply, connection->address);
2004             }
2005             return;
2006         }
2007 
2008         if (connection->authentication_flags & DENY_PIN_CODE_REQUEST){
2009             log_info("denying to pin request");
2010             connectionClearAuthenticationFlags(connection, DENY_PIN_CODE_REQUEST);
2011             hci_send_cmd(&hci_pin_code_request_negative_reply, connection->address);
2012             return;
2013         }
2014 
2015         if (connection->authentication_flags & SEND_IO_CAPABILITIES_REPLY){
2016             connectionClearAuthenticationFlags(connection, SEND_IO_CAPABILITIES_REPLY);
2017             log_info("IO Capability Request received, stack bondable %u, io cap %u", hci_stack->bondable, hci_stack->ssp_io_capability);
2018             if (hci_stack->bondable && (hci_stack->ssp_io_capability != SSP_IO_CAPABILITY_UNKNOWN)){
2019                 // tweak authentication requirements
2020                 uint8_t authreq = hci_stack->ssp_authentication_requirement;
2021                 if (connection->bonding_flags & BONDING_DEDICATED){
2022                     authreq = SSP_IO_AUTHREQ_MITM_PROTECTION_NOT_REQUIRED_DEDICATED_BONDING;
2023                 }
2024                 if (gap_mitm_protection_required_for_security_level(connection->requested_security_level)){
2025                     authreq |= 1;
2026                 }
2027                 hci_send_cmd(&hci_io_capability_request_reply, &connection->address, hci_stack->ssp_io_capability, NULL, authreq);
2028             } else {
2029                 hci_send_cmd(&hci_io_capability_request_negative_reply, &connection->address, ERROR_CODE_PAIRING_NOT_ALLOWED);
2030             }
2031             return;
2032         }
2033 
2034         if (connection->authentication_flags & SEND_USER_CONFIRM_REPLY){
2035             connectionClearAuthenticationFlags(connection, SEND_USER_CONFIRM_REPLY);
2036             hci_send_cmd(&hci_user_confirmation_request_reply, &connection->address);
2037             return;
2038         }
2039 
2040         if (connection->authentication_flags & SEND_USER_PASSKEY_REPLY){
2041             connectionClearAuthenticationFlags(connection, SEND_USER_PASSKEY_REPLY);
2042             hci_send_cmd(&hci_user_passkey_request_reply, &connection->address, 000000);
2043             return;
2044         }
2045 
2046         if (connection->bonding_flags & BONDING_REQUEST_REMOTE_FEATURES){
2047             connection->bonding_flags &= ~BONDING_REQUEST_REMOTE_FEATURES;
2048             hci_send_cmd(&hci_read_remote_supported_features_command, connection->con_handle);
2049             return;
2050         }
2051 
2052         if (connection->bonding_flags & BONDING_DISCONNECT_SECURITY_BLOCK){
2053             connection->bonding_flags &= ~BONDING_DISCONNECT_SECURITY_BLOCK;
2054             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x0005);  // authentication failure
2055             return;
2056         }
2057         if (connection->bonding_flags & BONDING_DISCONNECT_DEDICATED_DONE){
2058             connection->bonding_flags &= ~BONDING_DISCONNECT_DEDICATED_DONE;
2059             connection->bonding_flags |= BONDING_EMIT_COMPLETE_ON_DISCONNECT;
2060             hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // authentication done
2061             return;
2062         }
2063         if (connection->bonding_flags & BONDING_SEND_AUTHENTICATE_REQUEST){
2064             connection->bonding_flags &= ~BONDING_SEND_AUTHENTICATE_REQUEST;
2065             hci_send_cmd(&hci_authentication_requested, connection->con_handle);
2066             return;
2067         }
2068         if (connection->bonding_flags & BONDING_SEND_ENCRYPTION_REQUEST){
2069             connection->bonding_flags &= ~BONDING_SEND_ENCRYPTION_REQUEST;
2070             hci_send_cmd(&hci_set_connection_encryption, connection->con_handle, 1);
2071             return;
2072         }
2073 
2074 #ifdef HAVE_BLE
2075         if (connection->le_con_parameter_update_state == CON_PARAMETER_UPDATE_CHANGE_HCI_CON_PARAMETERS){
2076             connection->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
2077 
2078             uint16_t connection_interval_min = connection->le_conn_interval_min;
2079             connection->le_conn_interval_min = 0;
2080             hci_send_cmd(&hci_le_connection_update, connection->con_handle, connection_interval_min,
2081                 connection->le_conn_interval_max, connection->le_conn_latency, connection->le_supervision_timeout,
2082                 0x0000, 0xffff);
2083         }
2084 #endif
2085     }
2086 
2087     switch (hci_stack->state){
2088         case HCI_STATE_INITIALIZING:
2089             hci_initializing_state_machine();
2090             break;
2091 
2092         case HCI_STATE_HALTING:
2093 
2094             log_info("HCI_STATE_HALTING");
2095             // close all open connections
2096             connection =  (hci_connection_t *) hci_stack->connections;
2097             if (connection){
2098 
2099                 // send disconnect
2100                 if (!hci_can_send_command_packet_now()) return;
2101 
2102                 log_info("HCI_STATE_HALTING, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
2103                 hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
2104 
2105                 // send disconnected event right away - causes higher layer connections to get closed, too.
2106                 hci_shutdown_connection(connection);
2107                 return;
2108             }
2109             log_info("HCI_STATE_HALTING, calling off");
2110 
2111             // switch mode
2112             hci_power_control_off();
2113 
2114             log_info("HCI_STATE_HALTING, emitting state");
2115             hci_emit_state();
2116             log_info("HCI_STATE_HALTING, done");
2117             break;
2118 
2119         case HCI_STATE_FALLING_ASLEEP:
2120             switch(hci_stack->substate) {
2121                 case 0:
2122                     log_info("HCI_STATE_FALLING_ASLEEP");
2123                     // close all open connections
2124                     connection =  (hci_connection_t *) hci_stack->connections;
2125 
2126 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
2127                     // don't close connections, if H4 supports power management
2128                     if (bt_control_iphone_power_management_enabled()){
2129                         connection = NULL;
2130                     }
2131 #endif
2132                     if (connection){
2133 
2134                         // send disconnect
2135                         if (!hci_can_send_command_packet_now()) return;
2136 
2137                         log_info("HCI_STATE_FALLING_ASLEEP, connection %p, handle %u", connection, (uint16_t)connection->con_handle);
2138                         hci_send_cmd(&hci_disconnect, connection->con_handle, 0x13);  // remote closed connection
2139 
2140                         // send disconnected event right away - causes higher layer connections to get closed, too.
2141                         hci_shutdown_connection(connection);
2142                         return;
2143                     }
2144 
2145                     if (hci_classic_supported()){
2146                         // disable page and inquiry scan
2147                         if (!hci_can_send_command_packet_now()) return;
2148 
2149                         log_info("HCI_STATE_HALTING, disabling inq scans");
2150                         hci_send_cmd(&hci_write_scan_enable, hci_stack->connectable << 1); // drop inquiry scan but keep page scan
2151 
2152                         // continue in next sub state
2153                         hci_stack->substate++;
2154                         break;
2155                     }
2156                     // fall through for ble-only chips
2157 
2158                 case 2:
2159                     log_info("HCI_STATE_HALTING, calling sleep");
2160 #if defined(USE_POWERMANAGEMENT) && defined(USE_BLUETOOL)
2161                     // don't actually go to sleep, if H4 supports power management
2162                     if (bt_control_iphone_power_management_enabled()){
2163                         // SLEEP MODE reached
2164                         hci_stack->state = HCI_STATE_SLEEPING;
2165                         hci_emit_state();
2166                         break;
2167                     }
2168 #endif
2169                     // switch mode
2170                     hci_power_control_sleep();  // changes hci_stack->state to SLEEP
2171                     hci_emit_state();
2172                     break;
2173 
2174                 default:
2175                     break;
2176             }
2177             break;
2178 
2179         default:
2180             break;
2181     }
2182 }
2183 
2184 int hci_send_cmd_packet(uint8_t *packet, int size){
2185     bd_addr_t addr;
2186     hci_connection_t * conn;
2187     // house-keeping
2188 
2189     // create_connection?
2190     if (IS_COMMAND(packet, hci_create_connection)){
2191         bt_flip_addr(addr, &packet[3]);
2192         log_info("Create_connection to %s", bd_addr_to_str(addr));
2193 
2194         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2195         if (!conn){
2196             conn = create_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
2197             if (!conn){
2198                 // notify client that alloc failed
2199                 hci_emit_connection_complete(conn, BTSTACK_MEMORY_ALLOC_FAILED);
2200                 return 0; // don't sent packet to controller
2201             }
2202             conn->state = SEND_CREATE_CONNECTION;
2203         }
2204         log_info("conn state %u", conn->state);
2205         switch (conn->state){
2206             // if connection active exists
2207             case OPEN:
2208                 // and OPEN, emit connection complete command, don't send to controller
2209                 hci_emit_connection_complete(conn, 0);
2210                 return 0;
2211             case SEND_CREATE_CONNECTION:
2212                 // connection created by hci, e.g. dedicated bonding
2213                 break;
2214             default:
2215                 // otherwise, just ignore as it is already in the open process
2216                 return 0;
2217         }
2218         conn->state = SENT_CREATE_CONNECTION;
2219     }
2220 
2221     if (IS_COMMAND(packet, hci_link_key_request_reply)){
2222         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_REPLY);
2223     }
2224     if (IS_COMMAND(packet, hci_link_key_request_negative_reply)){
2225         hci_add_connection_flags_for_flipped_bd_addr(&packet[3], SENT_LINK_KEY_NEGATIVE_REQUEST);
2226     }
2227 
2228     if (IS_COMMAND(packet, hci_delete_stored_link_key)){
2229         if (hci_stack->remote_device_db){
2230             bt_flip_addr(addr, &packet[3]);
2231             hci_stack->remote_device_db->delete_link_key(&addr);
2232         }
2233     }
2234 
2235     if (IS_COMMAND(packet, hci_pin_code_request_negative_reply)
2236     ||  IS_COMMAND(packet, hci_pin_code_request_reply)){
2237         bt_flip_addr(addr, &packet[3]);
2238         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2239         if (conn){
2240             connectionClearAuthenticationFlags(conn, LEGACY_PAIRING_ACTIVE);
2241         }
2242     }
2243 
2244     if (IS_COMMAND(packet, hci_user_confirmation_request_negative_reply)
2245     ||  IS_COMMAND(packet, hci_user_confirmation_request_reply)
2246     ||  IS_COMMAND(packet, hci_user_passkey_request_negative_reply)
2247     ||  IS_COMMAND(packet, hci_user_passkey_request_reply)) {
2248         bt_flip_addr(addr, &packet[3]);
2249         conn = hci_connection_for_bd_addr_and_type(&addr, BD_ADDR_TYPE_CLASSIC);
2250         if (conn){
2251             connectionClearAuthenticationFlags(conn, SSP_PAIRING_ACTIVE);
2252         }
2253     }
2254 
2255 #ifdef HAVE_BLE
2256     if (IS_COMMAND(packet, hci_le_set_advertising_parameters)){
2257         hci_stack->adv_addr_type = packet[8];
2258     }
2259     if (IS_COMMAND(packet, hci_le_set_random_address)){
2260         bt_flip_addr(hci_stack->adv_address, &packet[3]);
2261     }
2262 #endif
2263 
2264     hci_stack->num_cmd_packets--;
2265 
2266     hci_dump_packet(HCI_COMMAND_DATA_PACKET, 0, packet, size);
2267     int err = hci_stack->hci_transport->send_packet(HCI_COMMAND_DATA_PACKET, packet, size);
2268 
2269     // release packet buffer for synchronous transport implementations
2270     if (hci_transport_synchronous() && (packet == hci_stack->hci_packet_buffer)){
2271         hci_stack->hci_packet_buffer_reserved = 0;
2272     }
2273 
2274     return err;
2275 }
2276 
2277 // disconnect because of security block
2278 void hci_disconnect_security_block(hci_con_handle_t con_handle){
2279     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2280     if (!connection) return;
2281     connection->bonding_flags |= BONDING_DISCONNECT_SECURITY_BLOCK;
2282 }
2283 
2284 
2285 // Configure Secure Simple Pairing
2286 
2287 // enable will enable SSP during init
2288 void hci_ssp_set_enable(int enable){
2289     hci_stack->ssp_enable = enable;
2290 }
2291 
2292 int hci_local_ssp_activated(){
2293     return hci_ssp_supported() && hci_stack->ssp_enable;
2294 }
2295 
2296 // if set, BTstack will respond to io capability request using authentication requirement
2297 void hci_ssp_set_io_capability(int io_capability){
2298     hci_stack->ssp_io_capability = io_capability;
2299 }
2300 void hci_ssp_set_authentication_requirement(int authentication_requirement){
2301     hci_stack->ssp_authentication_requirement = authentication_requirement;
2302 }
2303 
2304 // if set, BTstack will confirm a numberic comparion and enter '000000' if requested
2305 void hci_ssp_set_auto_accept(int auto_accept){
2306     hci_stack->ssp_auto_accept = auto_accept;
2307 }
2308 
2309 /**
2310  * pre: numcmds >= 0 - it's allowed to send a command to the controller
2311  */
2312 int hci_send_cmd(const hci_cmd_t *cmd, ...){
2313 
2314     if (!hci_can_send_command_packet_now()){
2315         log_error("hci_send_cmd called but cannot send packet now");
2316         return 0;
2317     }
2318 
2319     // for HCI INITIALIZATION
2320     // log_info("hci_send_cmd: opcode %04x", cmd->opcode);
2321     hci_stack->last_cmd_opcode = cmd->opcode;
2322 
2323     hci_reserve_packet_buffer();
2324     uint8_t * packet = hci_stack->hci_packet_buffer;
2325 
2326     va_list argptr;
2327     va_start(argptr, cmd);
2328     uint16_t size = hci_create_cmd_internal(packet, cmd, argptr);
2329     va_end(argptr);
2330 
2331     return hci_send_cmd_packet(packet, size);
2332 }
2333 
2334 // Create various non-HCI events.
2335 // TODO: generalize, use table similar to hci_create_command
2336 
2337 void hci_emit_state(){
2338     log_info("BTSTACK_EVENT_STATE %u", hci_stack->state);
2339     uint8_t event[3];
2340     event[0] = BTSTACK_EVENT_STATE;
2341     event[1] = sizeof(event) - 2;
2342     event[2] = hci_stack->state;
2343     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2344     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2345 }
2346 
2347 void hci_emit_connection_complete(hci_connection_t *conn, uint8_t status){
2348     uint8_t event[13];
2349     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
2350     event[1] = sizeof(event) - 2;
2351     event[2] = status;
2352     bt_store_16(event, 3, conn->con_handle);
2353     bt_flip_addr(&event[5], conn->address);
2354     event[11] = 1; // ACL connection
2355     event[12] = 0; // encryption disabled
2356     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2357     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2358 }
2359 
2360 void hci_emit_le_connection_complete(uint8_t address_type, bd_addr_t * address, uint16_t conn_handle, uint8_t status){
2361     uint8_t event[21];
2362     event[0] = HCI_EVENT_LE_META;
2363     event[1] = sizeof(event) - 2;
2364     event[2] = HCI_SUBEVENT_LE_CONNECTION_COMPLETE;
2365     event[3] = status;
2366     bt_store_16(event, 4, conn_handle);
2367     event[6] = 0; // TODO: role
2368     event[7] = address_type;
2369     bt_flip_addr(&event[8], *address);
2370     bt_store_16(event, 14, 0); // interval
2371     bt_store_16(event, 16, 0); // latency
2372     bt_store_16(event, 18, 0); // supervision timeout
2373     event[20] = 0; // master clock accuracy
2374     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2375     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2376 }
2377 
2378 void hci_emit_disconnection_complete(uint16_t handle, uint8_t reason){
2379     uint8_t event[6];
2380     event[0] = HCI_EVENT_DISCONNECTION_COMPLETE;
2381     event[1] = sizeof(event) - 2;
2382     event[2] = 0; // status = OK
2383     bt_store_16(event, 3, handle);
2384     event[5] = reason;
2385     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2386     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2387 }
2388 
2389 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
2390     if (disable_l2cap_timeouts) return;
2391     log_info("L2CAP_EVENT_TIMEOUT_CHECK");
2392     uint8_t event[4];
2393     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
2394     event[1] = sizeof(event) - 2;
2395     bt_store_16(event, 2, conn->con_handle);
2396     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event));
2397     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2398 }
2399 
2400 void hci_emit_nr_connections_changed(){
2401     log_info("BTSTACK_EVENT_NR_CONNECTIONS_CHANGED %u", nr_hci_connections());
2402     uint8_t event[3];
2403     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
2404     event[1] = sizeof(event) - 2;
2405     event[2] = nr_hci_connections();
2406     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2407     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2408 }
2409 
2410 void hci_emit_hci_open_failed(){
2411     log_info("BTSTACK_EVENT_POWERON_FAILED");
2412     uint8_t event[2];
2413     event[0] = BTSTACK_EVENT_POWERON_FAILED;
2414     event[1] = sizeof(event) - 2;
2415     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2416     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2417 }
2418 
2419 #ifndef EMBEDDED
2420 void hci_emit_btstack_version() {
2421     log_info("BTSTACK_EVENT_VERSION %u.%u", BTSTACK_MAJOR, BTSTACK_MINOR);
2422     uint8_t event[6];
2423     event[0] = BTSTACK_EVENT_VERSION;
2424     event[1] = sizeof(event) - 2;
2425     event[2] = BTSTACK_MAJOR;
2426     event[3] = BTSTACK_MINOR;
2427     bt_store_16(event, 4, BTSTACK_REVISION);
2428     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2429     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2430 }
2431 #endif
2432 
2433 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
2434     log_info("BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED %u", enabled);
2435     uint8_t event[3];
2436     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
2437     event[1] = sizeof(event) - 2;
2438     event[2] = enabled;
2439     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2440     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2441 }
2442 
2443 void hci_emit_remote_name_cached(bd_addr_t *addr, device_name_t *name){
2444     uint8_t event[2+1+6+248+1]; // +1 for \0 in log_info
2445     event[0] = BTSTACK_EVENT_REMOTE_NAME_CACHED;
2446     event[1] = sizeof(event) - 2 - 1;
2447     event[2] = 0;   // just to be compatible with HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE
2448     bt_flip_addr(&event[3], *addr);
2449     memcpy(&event[9], name, 248);
2450 
2451     event[9+248] = 0;   // assert \0 for log_info
2452     log_info("BTSTACK_EVENT_REMOTE_NAME_CACHED %s = '%s'", bd_addr_to_str(*addr), &event[9]);
2453 
2454     hci_dump_packet(HCI_EVENT_PACKET, 0, event, sizeof(event)-1);
2455     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event)-1);
2456 }
2457 
2458 void hci_emit_discoverable_enabled(uint8_t enabled){
2459     log_info("BTSTACK_EVENT_DISCOVERABLE_ENABLED %u", enabled);
2460     uint8_t event[3];
2461     event[0] = BTSTACK_EVENT_DISCOVERABLE_ENABLED;
2462     event[1] = sizeof(event) - 2;
2463     event[2] = enabled;
2464     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2465     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2466 }
2467 
2468 void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level){
2469     log_info("hci_emit_security_level %u for handle %x", level, con_handle);
2470     uint8_t event[5];
2471     int pos = 0;
2472     event[pos++] = GAP_SECURITY_LEVEL;
2473     event[pos++] = sizeof(event) - 2;
2474     bt_store_16(event, 2, con_handle);
2475     pos += 2;
2476     event[pos++] = level;
2477     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2478     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2479 }
2480 
2481 void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status){
2482     log_info("hci_emit_dedicated_bonding_result %u ", status);
2483     uint8_t event[9];
2484     int pos = 0;
2485     event[pos++] = GAP_DEDICATED_BONDING_COMPLETED;
2486     event[pos++] = sizeof(event) - 2;
2487     event[pos++] = status;
2488     bt_flip_addr( * (bd_addr_t *) &event[pos], address);
2489     pos += 6;
2490     hci_dump_packet( HCI_EVENT_PACKET, 0, event, sizeof(event));
2491     hci_stack->packet_handler(HCI_EVENT_PACKET, event, sizeof(event));
2492 }
2493 
2494 // query if remote side supports SSP
2495 int hci_remote_ssp_supported(hci_con_handle_t con_handle){
2496     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2497     if (!connection) return 0;
2498     return (connection->bonding_flags & BONDING_REMOTE_SUPPORTS_SSP) ? 1 : 0;
2499 }
2500 
2501 int hci_ssp_supported_on_both_sides(hci_con_handle_t handle){
2502     return hci_local_ssp_activated() && hci_remote_ssp_supported(handle);
2503 }
2504 
2505 // GAP API
2506 /**
2507  * @bbrief enable/disable bonding. default is enabled
2508  * @praram enabled
2509  */
2510 void gap_set_bondable_mode(int enable){
2511     hci_stack->bondable = enable ? 1 : 0;
2512 }
2513 
2514 /**
2515  * @brief map link keys to security levels
2516  */
2517 gap_security_level_t gap_security_level_for_link_key_type(link_key_type_t link_key_type){
2518     switch (link_key_type){
2519         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P256:
2520             return LEVEL_4;
2521         case COMBINATION_KEY:
2522         case AUTHENTICATED_COMBINATION_KEY_GENERATED_FROM_P192:
2523             return LEVEL_3;
2524         default:
2525             return LEVEL_2;
2526     }
2527 }
2528 
2529 static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection){
2530     if (!connection) return LEVEL_0;
2531     if ((connection->authentication_flags & CONNECTION_ENCRYPTED) == 0) return LEVEL_0;
2532     return gap_security_level_for_link_key_type(connection->link_key_type);
2533 }
2534 
2535 
2536 int gap_mitm_protection_required_for_security_level(gap_security_level_t level){
2537     log_info("gap_mitm_protection_required_for_security_level %u", level);
2538     return level > LEVEL_2;
2539 }
2540 
2541 /**
2542  * @brief get current security level
2543  */
2544 gap_security_level_t gap_security_level(hci_con_handle_t con_handle){
2545     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2546     if (!connection) return LEVEL_0;
2547     return gap_security_level_for_connection(connection);
2548 }
2549 
2550 /**
2551  * @brief request connection to device to
2552  * @result GAP_AUTHENTICATION_RESULT
2553  */
2554 void gap_request_security_level(hci_con_handle_t con_handle, gap_security_level_t requested_level){
2555     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2556     if (!connection){
2557         hci_emit_security_level(con_handle, LEVEL_0);
2558         return;
2559     }
2560     gap_security_level_t current_level = gap_security_level(con_handle);
2561     log_info("gap_request_security_level %u, current level %u", requested_level, current_level);
2562     if (current_level >= requested_level){
2563         hci_emit_security_level(con_handle, current_level);
2564         return;
2565     }
2566 
2567     connection->requested_security_level = requested_level;
2568 
2569 #if 0
2570     // sending encryption request without a link key results in an error.
2571     // TODO: figure out how to use it properly
2572 
2573     // would enabling ecnryption suffice (>= LEVEL_2)?
2574     if (hci_stack->remote_device_db){
2575         link_key_type_t link_key_type;
2576         link_key_t      link_key;
2577         if (hci_stack->remote_device_db->get_link_key( &connection->address, &link_key, &link_key_type)){
2578             if (gap_security_level_for_link_key_type(link_key_type) >= requested_level){
2579                 connection->bonding_flags |= BONDING_SEND_ENCRYPTION_REQUEST;
2580                 return;
2581             }
2582         }
2583     }
2584 #endif
2585 
2586     // try to authenticate connection
2587     connection->bonding_flags |= BONDING_SEND_AUTHENTICATE_REQUEST;
2588     hci_run();
2589 }
2590 
2591 /**
2592  * @brief start dedicated bonding with device. disconnect after bonding
2593  * @param device
2594  * @param request MITM protection
2595  * @result GAP_DEDICATED_BONDING_COMPLETE
2596  */
2597 int gap_dedicated_bonding(bd_addr_t device, int mitm_protection_required){
2598 
2599     // create connection state machine
2600     hci_connection_t * connection = create_connection_for_bd_addr_and_type(device, BD_ADDR_TYPE_CLASSIC);
2601 
2602     if (!connection){
2603         return BTSTACK_MEMORY_ALLOC_FAILED;
2604     }
2605 
2606     // delete linkn key
2607     hci_drop_link_key_for_bd_addr( (bd_addr_t *) &device);
2608 
2609     // configure LEVEL_2/3, dedicated bonding
2610     connection->state = SEND_CREATE_CONNECTION;
2611     connection->requested_security_level = mitm_protection_required ? LEVEL_3 : LEVEL_2;
2612     log_info("gap_dedicated_bonding, mitm %u -> level %u", mitm_protection_required, connection->requested_security_level);
2613     connection->bonding_flags = BONDING_DEDICATED;
2614 
2615     // wait for GAP Security Result and send GAP Dedicated Bonding complete
2616 
2617     // handle: connnection failure (connection complete != ok)
2618     // handle: authentication failure
2619     // handle: disconnect on done
2620 
2621     hci_run();
2622 
2623     return 0;
2624 }
2625 
2626 void gap_set_local_name(const char * local_name){
2627     hci_stack->local_name = local_name;
2628 }
2629 
2630 le_command_status_t le_central_start_scan(){
2631     if (hci_stack->le_scanning_state == LE_SCANNING) return BLE_PERIPHERAL_OK;
2632     hci_stack->le_scanning_state = LE_START_SCAN;
2633     hci_run();
2634     return BLE_PERIPHERAL_OK;
2635 }
2636 
2637 le_command_status_t le_central_stop_scan(){
2638     if ( hci_stack->le_scanning_state == LE_SCAN_IDLE) return BLE_PERIPHERAL_OK;
2639     hci_stack->le_scanning_state = LE_STOP_SCAN;
2640     hci_run();
2641     return BLE_PERIPHERAL_OK;
2642 }
2643 
2644 void le_central_set_scan_parameters(uint8_t scan_type, uint16_t scan_interval, uint16_t scan_window){
2645     hci_stack->le_scan_type     = scan_type;
2646     hci_stack->le_scan_interval = scan_interval;
2647     hci_stack->le_scan_window   = scan_window;
2648     hci_run();
2649 }
2650 
2651 le_command_status_t le_central_connect(bd_addr_t * addr, bd_addr_type_t addr_type){
2652     hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, addr_type);
2653     if (!conn){
2654         log_info("le_central_connect: no connection exists yet, creating context");
2655         conn = create_connection_for_bd_addr_and_type(*addr, addr_type);
2656         if (!conn){
2657             // notify client that alloc failed
2658             hci_emit_le_connection_complete(addr_type, addr, 0, BTSTACK_MEMORY_ALLOC_FAILED);
2659             log_info("le_central_connect: failed to alloc hci_connection_t");
2660             return BLE_PERIPHERAL_NOT_CONNECTED; // don't sent packet to controller
2661         }
2662         conn->state = SEND_CREATE_CONNECTION;
2663         log_info("le_central_connect: send create connection next");
2664         hci_run();
2665         return BLE_PERIPHERAL_OK;
2666     }
2667 
2668     if (!hci_is_le_connection(conn) ||
2669         conn->state == SEND_CREATE_CONNECTION ||
2670         conn->state == SENT_CREATE_CONNECTION) {
2671         hci_emit_le_connection_complete(conn->address_type, &conn->address, 0, ERROR_CODE_COMMAND_DISALLOWED);
2672         log_error("le_central_connect: classic connection or connect is already being created");
2673         return BLE_PERIPHERAL_IN_WRONG_STATE;
2674     }
2675 
2676     log_info("le_central_connect: context exists with state %u", conn->state);
2677     hci_emit_le_connection_complete(conn->address_type, &conn->address, conn->con_handle, 0);
2678     hci_run();
2679     return BLE_PERIPHERAL_OK;
2680 }
2681 
2682 // @assumption: only a single outgoing LE Connection exists
2683 static hci_connection_t * le_central_get_outgoing_connection(){
2684     linked_item_t *it;
2685     for (it = (linked_item_t *) hci_stack->connections; it ; it = it->next){
2686         hci_connection_t * conn = (hci_connection_t *) it;
2687         if (!hci_is_le_connection(conn)) continue;
2688         switch (conn->state){
2689             case SEND_CREATE_CONNECTION:
2690             case SENT_CREATE_CONNECTION:
2691                 return conn;
2692             default:
2693                 break;
2694         };
2695     }
2696     return NULL;
2697 }
2698 
2699 le_command_status_t le_central_connect_cancel(){
2700     hci_connection_t * conn = le_central_get_outgoing_connection();
2701     switch (conn->state){
2702         case SEND_CREATE_CONNECTION:
2703             // skip sending create connection and emit event instead
2704             hci_emit_le_connection_complete(conn->address_type, &conn->address, 0, ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER);
2705             linked_list_remove(&hci_stack->connections, (linked_item_t *) conn);
2706             btstack_memory_hci_connection_free( conn );
2707             break;
2708         case SENT_CREATE_CONNECTION:
2709             // request to send cancel connection
2710             conn->state = SEND_CANCEL_CONNECTION;
2711             hci_run();
2712             break;
2713         default:
2714             break;
2715     }
2716     return BLE_PERIPHERAL_OK;
2717 }
2718 
2719 /**
2720  * @brief Updates the connection parameters for a given LE connection
2721  * @param handle
2722  * @param conn_interval_min (unit: 1.25ms)
2723  * @param conn_interval_max (unit: 1.25ms)
2724  * @param conn_latency
2725  * @param supervision_timeout (unit: 10ms)
2726  * @returns 0 if ok
2727  */
2728 int gap_update_connection_parameters(hci_con_handle_t con_handle, uint16_t conn_interval_min,
2729     uint16_t conn_interval_max, uint16_t conn_latency, uint16_t supervision_timeout){
2730     hci_connection_t * connection = hci_connection_for_handle(con_handle);
2731     if (!connection) return ERROR_CODE_UNKNOWN_CONNECTION_IDENTIFIER;
2732     connection->le_conn_interval_min = conn_interval_min;
2733     connection->le_conn_interval_max = conn_interval_max;
2734     connection->le_conn_latency = conn_latency;
2735     connection->le_supervision_timeout = supervision_timeout;
2736     return 0;
2737 }
2738 
2739 le_command_status_t gap_disconnect(hci_con_handle_t handle){
2740     hci_connection_t * conn = hci_connection_for_handle(handle);
2741     if (!conn){
2742         hci_emit_disconnection_complete(handle, 0);
2743         return BLE_PERIPHERAL_OK;
2744     }
2745     conn->state = SEND_DISCONNECT;
2746     hci_run();
2747     return BLE_PERIPHERAL_OK;
2748 }
2749 
2750 void hci_disconnect_all(){
2751     linked_list_iterator_t it;
2752     linked_list_iterator_init(&it, &hci_stack->connections);
2753     while (linked_list_iterator_has_next(&it)){
2754         hci_connection_t * con = (hci_connection_t*) linked_list_iterator_next(&it);
2755         if (con->state == SENT_DISCONNECT) continue;
2756         con->state = SEND_DISCONNECT;
2757     }
2758     hci_run();
2759 }
2760