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