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