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